/
hrkatsvill
/
homework
Обзор
Документация
Войти
/
hrkatsvill
/
homework
Код
Запросы
1
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
script.js
111 строк
3 KB
Alexander Berezin
Input fix
30 янв 2025, 15:30
30 янв 2025, 15:30
247644c
Код
Авторство
О чём код?
// Размеры игрового поля const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const cellSize = 10; // Размер одной клетки змеи const widthInCells = canvas.width / cellSize; const heightInCells = canvas.height / cellSize; // Направления движения const directions = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } }; let currentDirection = directions.right; // Начальная позиция змеи let snake = [ { x: Math.floor(widthInCells / 2), y: Math.floor(heightInCells / 2) } ]; // Положение еды let food = generateFood(); // Генерация новой позиции для еды function generateFood() { let x = Math.floor(Math.random() * widthInCells); let y = Math.floor(Math.random() * heightInCells); return { x, y }; } // Отрисовка элемента function drawCell(x, y, color) { ctx.fillStyle = color; ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize); } // Отрисовка змеи function drawSnake() { for (let segment of snake) { drawCell(segment.x, segment.y, 'green'); } } // Отрисовка еды function drawFood() { drawCell(food.x, food.y, 'red'); } // Обновление состояния игры function updateGameState() { const head = { ...snake[0] }; head.x += currentDirection.x; head.y += currentDirection.y; if (head.x === food.x && head.y === food.y) { food = generateFood(); } else { snake.pop(); // Удаляем хвост } snake.unshift(head); // Добавляем новую голову // Проверка столкновений со стенами и самой собой if ( head.x < 0 || head.x >= widthInCells || head.y < 0 || head.y >= heightInCells || snake.slice(1).some(seg => seg.x === head.x && seg.y === head.y) ) { alert("Игра окончена!"); location.reload(); // Перезагрузка страницы для начала новой игры } } // Обработка нажатий клавиш document.addEventListener('keydown', event => { switch (event.keyCode) { case 37: // Left arrow key if (currentDirection !== directions.right) { currentDirection = directions.left; } break; case 38: // Up arrow key if (currentDirection !== directions.down) { currentDirection = directions.up; } break; case 39: // Right arrow key if (currentDirection !== directions.left) { currentDirection = directions.right; } break; case 40: // Down arrow key if (currentDirection !== directions.up) { currentDirection = directions.down; } break; } }); // Основной игровой цикл function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); updateGameState(); drawSnake(); drawFood(); setTimeout(gameLoop, 100); // Скорость игры (меньше значение = быстрее игра) } // Запуск игры gameLoop();