Как написать собственную игру на JavaScript
Основные подходы к разработке игр на JavaScript
Вопрос: как создать игру 'Змейка' на Canvas, используя setInterval для обновления состояния?
Базовый подход основывается на использовании таймера setInterval, который вызывает функцию обновления игрового цикла с заданной частотой (например, каждые 100 мс). Это самый простой способ реализовать пошаговое движение змейки. Ниже представлен минимальный код для такой игры.
// HTML: <canvas id="game" width="400" height="400"></canvas>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20;
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let direction = 'right';
let nextDirection = 'right';
function update() {
direction = nextDirection;
const head = {...snake[0]};
if (direction === 'right') head.x++;
else if (direction === 'left') head.x--;
else if (direction === 'up') head.y--;
else if (direction === 'down') head.y++;
if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) {
alert('Game Over');
resetGame();
return;
}
for (let part of snake) {
if (part.x === head.x && part.y === head.y) {
alert('Game Over');
resetGame();
return;
}
}
if (head.x === food.x && head.y === food.y) {
spawnFood();
} else {
snake.pop();
}
snake.unshift(head);
draw();
}
function draw() {
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, 400, 400);
ctx.fillStyle = 'lime';
for (let part of snake) {
ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize-1, gridSize-1);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-1, gridSize-1);
}
function spawnFood() {
food = {x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20)};
}
function resetGame() {
snake = [{x: 10, y: 10}];
direction = 'right';
nextDirection = 'right';
spawnFood();
}
document.addEventListener('keydown', (e) => {
const keyMap = {ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right'};
const dir = keyMap[e.key];
if (dir && (dir !== 'up' && direction !== 'down' || dir !== 'down' && direction !== 'up' || dir !== 'left' && direction !== 'right' || dir !== 'right' && direction !== 'left')) {
nextDirection = dir;
}
});
setInterval(update, 100);
draw();Js games (игры на javascript)
Цель и случаи использования: данный вариант подходит для быстрого прототипирования и обучения, когда не требуется высокая производительность. setInterval прост в понимании, но не идеален для игр с плавной графикой.
Вариант 1: использование requestAnimationFrame для плавного обновления
Вместо фиксированного таймера применяется цикл requestAnimationFrame, который синхронизирует обновление с частотой обновления экрана. Для контроля скорости используется разница во времени (delta time).
let lastTime = 0;
const moveInterval = 100; // ms
function gameLoop(timestamp) {
const delta = timestamp - lastTime;
if (delta >= moveInterval) {
update();
lastTime = timestamp;
}
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);Html game js (создание игры на html и javascript)
Цель: достижение плавной анимации без разрывов. Используется в большинстве современных браузерных игр.
Вариант 2: реализация на DOM-элементах без Canvas
Вся игровая сетка состоит из div-элементов, которые меняют свой класс или цвет для отображения змейки и еды. Подход проще для понимания начинающими, так как не требует работы с Canvas API.
<div id="gameGrid" style="display: grid; grid-template-columns: repeat(20, 20px);"></div>
const grid = document.getElementById('gameGrid');
const cells = [];
for (let i = 0; i < 400; i++) {
const cell = document.createElement('div');
cell.style.width = '20px';
cell.style.height = '20px';
cell.style.backgroundColor = '#111';
grid.appendChild(cell);
cells.push(cell);
}
function draw() {
cells.forEach(c => c.style.backgroundColor = '#111');
for (let part of snake) {
const idx = part.y * 20 + part.x;
cells[idx].style.backgroundColor = 'lime';
}
const foodIdx = food.y * 20 + food.x;
cells[foodIdx].style.backgroundColor = 'red';
}Javascript game (разработка игр на javascript)
Когда применять: для маленьких игр (до 20x20) или в учебных целях, когда хочется избежать работы с пикселями.
Вариант 3: объектно-ориентированная структура кода
Выделение классов Snake, Food, Game улучшает читаемость и расширяемость игры. Код легче тестировать и модифицировать.
class Snake {
constructor() {
this.body = [{x: 10, y: 10}];
this.dir = 'right';
}
move() {
const head = {...this.body[0]};
switch (this.dir) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
}
this.body.unshift(head);
return this.body.pop(); // возвращаем хвост для удаления
}
collideWithItself() {
const [head, ...rest] = this.body;
return rest.some(p => p.x === head.x && p.y === head.y);
}
}
class Food { ... }
class Game { ... }Применимость: когда игра разрастается (добавляются уровни, враги, предметы). ООП помогает организовать код.
Расширенные примеры реализации игры 'Змейка'
Ниже приведен полный код игры с использованием requestAnimationFrame, подсчетом очков, рекордом в localStorage и поддержкой мобильного управления.
// HTML: <canvas id="game" width="400" height="400"></canvas>
// CSS: черный фон
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const TICK_RATE = 120; // ms
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let gameOver = false;
let lastTime = 0;
function spawnFood() {
do {
food = {x: Math.floor(Math.random() * GRID_SIZE), y: Math.floor(Math.random() * GRID_SIZE)};
} while (snake.some(p => p.x === food.x && p.y === food.y));
}
function draw() {
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// змейка
ctx.fillStyle = '#00ff00';
snake.forEach((part, i) => {
if (i === 0) ctx.fillStyle = '#00cc00'; // голова
ctx.fillRect(part.x * CELL_SIZE, part.y * CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1);
if (i === 0) ctx.fillStyle = '#00ff00';
});
// еда
ctx.fillStyle = '#ff4444';
ctx.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1);
// отображение счета
ctx.fillStyle = '#fff';
ctx.font = '16px Arial';
ctx.fillText('Score: ' + score, 10, 20);
ctx.fillText('Record: ' + highScore, 300, 20);
}
function update() {
if (gameOver) return;
direction = nextDirection;
const head = {...snake[0]};
switch (direction) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
}
// столкновение со стеной
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
gameOver = true;
if (score > highScore) {
highScore = score;
localStorage.setItem('snakeHighScore', highScore);
}
return;
}
// столкновение с собой
for (let part of snake) {
if (part.x === head.x && part.y === head.y) {
gameOver = true;
if (score > highScore) {
highScore = score;
localStorage.setItem('snakeHighScore', highScore);
}
return;
}
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
spawnFood();
} else {
snake.pop();
}
}
function gameLoop(timestamp) {
if (timestamp - lastTime > TICK_RATE) {
update();
lastTime = timestamp;
}
draw();
requestAnimationFrame(gameLoop);
}
// Управление с клавиатуры
document.addEventListener('keydown', (e) => {
const key = e.key.replace('Arrow', '').toLowerCase();
if (['up','down','left','right'].includes(key)) {
const opposites = {up:'down', down:'up', left:'right', right:'left'};
if (key !== opposites[direction]) {
nextDirection = key;
}
}
});
// Мобильное управление (свайпы)
let touchStart = null;
canvas.addEventListener('touchstart', (e) => {
touchStart = {x: e.touches[0].clientX, y: e.touches[0].clientY};
});
canvas.addEventListener('touchmove', (e) => {
if (!touchStart) return;
const dx = e.touches[0].clientX - touchStart.x;
const dy = e.touches[0].clientY - touchStart.y;
if (Math.abs(dx) > Math.abs(dy)) {
nextDirection = dx > 0 ? 'right' : 'left';
} else {
nextDirection = dy > 0 ? 'down' : 'up';
}
touchStart = null; // предотвращаем повторные срабатывания
});
spawnFood();
requestAnimationFrame(gameLoop);Результат работы программы: на странице отображается черное поле размером 400x400 пикселей, по которому движется зеленая змейка. Красный квадрат - еда. Вверху слева показан текущий счет, справа - рекорд. При поедании еды счет увеличивается, змейка удлиняется. При столкновении с границей или собой игра останавливается, рекорд сохраняется в localStorage. Управление возможно как с клавиатуры (стрелки), так и с мобильного устройства (свайпы).
Дополнительный мини-пример: генерация еды в пустой клетке (с проверкой, чтобы не наложилась на змейку).
function spawnFood() {
let freeCells = [];
for (let x = 0; x < GRID_SIZE; x++) {
for (let y = 0; y < GRID_SIZE; y++) {
if (!snake.some(p => p.x === x && p.y === y)) {
freeCells.push({x, y});
}
}
}
food = freeCells[Math.floor(Math.random() * freeCells.length)];
}Этот гарантирует, что еда не появится на теле змеи. Результат: при каждой новой еде она всегда находится в доступной клетке.
Мини-пример сохранения рекорда:
// Сохранение
localStorage.setItem('snakeHighScore', highScore);
// Загрузка
highScore = parseInt(localStorage.getItem('snakeHighScore')) || 0;Результат: рекорд сохраняется между сессиями игры.