напиши логику игры в тетрис на js для этого html используя функции
Assistant
Конечно! Вот пример кода для логики игры в тетрис на JavaScript:
javascript
// Создаем переменные для хранения элементов игры
const canvas = document.getElementById("field");
const context = canvas.getContext("2d");
const scoreElement = document.getElementById("score");
const startButton = document.getElementById("start");
const rotateButton = document.getElementById("rotate");
const topButton = document.getElementById("top");
const bottomButton = document.getElementById("bottom");
const leftButton = document.getElementById("left");
const rightButton = document.getElementById("right");
// Создаем игровое поле
const field = [];
for (let row = 0; row < 20; row++) {
field[row] = [];
for (let col = 0; col < 10; col++) {
field[row][col] = 0;
}
}
// Создаем текущую фигуру
let currentFigure = {
x: 0,
y: 0,
shape: [],
};
// Создаем следующую фигуру
let nextFigure = {
x: 0,
y: 0,
shape: [],
};
// Создаем счет
let score = 0;
// Инициализируем игру
function initGame() {
drawField();
drawFigure(currentFigure);
generateNextFigure();
drawNextFigure();
updateScore();
startButton.addEventListener("click", startGame);
rotateButton.addEventListener("click", rotateFigure);
topButton.addEventListener("click", moveTop);
bottomButton.addEventListener("click", moveBottom);
leftButton.addEventListener("click", moveLeft);
rightButton.addEventListener("click", moveRight);
}
// Начинаем игру
function startGame() {
if (!isCollision(0, 0, currentFigure.shape)) {
currentFigure.y++;
drawField();
drawFigure(currentFigure);
requestAnimationFrame(startGame);
} else {
mergeFigure();
clearLines();
generateNextFigure();
drawNextFigure();
if (isGameOver()) {
alert("Game over");
return;
}
currentFigure = nextFigure;
currentFigure.x = Math.floor(10 / 2 - currentFigure.shape[0].length / 2);
currentFigure.y = 0;
startGame();
}
}
// Генерируем следующую фигуру
function generateNextFigure() {
const figures = [
[[1, 1, 1], [0, 1, 0]],
[[1, 1], [1, 1]],
[[1, 1, 0], [0, 1, 1]],
[[0, 1, 1], [1, 1, 0]],
[[1, 1, 1, 1]],
[[1, 0], [1, 0], [1, 1]],
[[0, 1], [0, 1], [1, 1]],
];
const randomIndex = Math.floor(Math.random() * figures.length);
nextFigure.shape = figures[randomIndex];
}
// Рисуем поле
function drawField() {
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight);
for (let row = 0; row < field.length; row++) {
for (let col = 0; col < field[row].length; col++) {
if (field[row][col]) {
drawSquare(col, row, field[row][col]);
}
}
}
}
// Рисуем квадрат
function drawSquare(x, y, color) {
context.fillStyle = colors[color];
context.fillRect(x * squareSize, y * squareSize, squareSize, squareSize);
context.strokeStyle = "#fff";
context.strokeRect(x * squareSize, y * squareSize, squareSize, squareSize);
}
// Рисуем фигуру
function drawFigure(figure) {
for (let row = 0; row < figure.shape.length; row++) {
for (let col = 0; col < figure.shape[row].length; col++) {
if (figure.shape[row][col]) {
drawSquare(figure.x + col, figure.y + row, figure.shape[row][col]);
}
}
}
}
// Рисуем следующую фигуру
function drawNextFigure() {
const nextFigureCanvas = document.createElement("canvas");
nextFigureCanvas.width = 80;
nextFigureCanvas.height = 80;
const nextFigureContext = nextFigureCanvas.getContext("2d");
nextFigureContext.fillStyle = "#000";
nextFigureContext.fillRect(0, 0, nextFigureCanvas.width, nextFigureCanvas.height);
for (let row = 0; row < nextFigure.shape.length; row++) {
for (let col = 0; col < nextFigure.shape[row].length; col++) {
if (nextFigure.shape[row][col]) {
drawNextFigureSquare(nextFigureContext, col, row, nextFigure.shape[row][col]);
}
}
}
const nextFigureElement = document.getElementById("nextFigure");
nextFigureElement.innerHTML = "";
nextFigureElement.appendChild(nextFigureCanvas);
}
// Рисуем квадрат следующей фигуры
function drawNextFigureSquare(context, x, y, color) {
const squareSize = 20;
context.fillStyle = colors[color];
context.fillRect(x * squareSize + 20, y * squareSize + 20, squareSize, squareSize);
context.strokeStyle = "#fff";
context.strokeRect(x * squareSize + 20, y * squareSize + 20, squareSize, squareSize);
}
// Обновляем счет
function updateScore() {
scoreElement.innerText = score;
}
// Проверяем столкновение
function isCollision(dx, dy, figure) {
for (let row = 0; row < figure.length; row++) {
for (let col = 0; col < figure[row].length; col++) {
if (figure[row][col] && (field[currentFigure.y + row + dy] &&
field[currentFigure.y + row + dy][currentFigure.x + col + dx]) !== 0) {
return true;
}
}
}
return false;
}
// Поворачиваем фигуру
function rotateFigure() {
const newFigure = [];
for (let col = 0; col < currentFigure.shape[0].length; col++) {
newFigure[col] = [];
for (let row = currentFigure.shape.length - 1; row >= 0; row--) {
newFigure[col][currentFigure.shape.length - 1 - row] = currentFigure.shape[row][col];
}
}
if (!isCollision(0, 0, newFigure)) {
currentFigure.shape = newFigure;
drawField();
drawFigure(currentFigure);
}
}
// Перемещаем фигуру вверх
function moveTop() {
if (!isCollision(0, -1, currentFigure.shape)) {
currentFigure.y--;
drawField();
drawFigure(currentFigure);
}
}
// Перемещаем фигуру вниз
function moveBottom() {
if (!isCollision(0, 1, currentFigure.shape)) {
currentFigure.y++;
drawField();
drawFigure(currentFigure);
}
}
// Перемещаем фигуру влево
function moveLeft() {
if (!isCollision(-1, 0, currentFigure.shape)) {
currentFigure.x--;
drawField();
drawFigure(currentFigure);
}
}
// Перемещаем фигуру вправо
function moveRight() {
if (!isCollision(1, 0, currentFigure.shape)) {
currentFigure.x++;
drawField();
drawFigure(currentFigure);
}
}
// Объединяем фигуру с полем
function mergeFigure() {
for (let row = 0; row < currentFigure.shape.length; row++) {
for (let col = 0; col < currentFigure.shape[row].length; col++) {
if (currentFigure.shape[row][col]) {
field[currentFigure.y + row][currentFigure.x + col] = currentFigure.shape[row][col];
}
}
}
}
// Проверяем заполненные линии
function clearLines() {
for (let row = field.length - 1; row >= 0; row--) {
if (field[row].every(value => value !== 0)) {
field.splice(row, 1);
field.unshift(Array(10).fill(0));
score += 10;
updateScore();
}
}
}
// Проверяем, закончилась ли игра
function isGameOver() {
return field[0].some(value => value !== 0);
}
// Запускаем игру
initGame();
В этом коде мы создаем игровое поле, переменные для текущей и следующей фигуры, а также для счета. Затем мы создаем функции для инициализации игры, начала игры, генерации следующей фигуры, отрисовки поля и фигур, проверки столкновений, перемещений фигуры и других логических операций. Запускаем игру с помощью функции initGame().