Конечно! Вот полный HTML-код простой игры "Змейка", выполненной с использованием HTML5 и JavaScript:
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Игра Змейка</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
background-color: #000;
border: 2px solid #555;
}
</style>
</head>
<body>
<canvas id="snakeCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('snakeCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
const snake = [{ x: 9 * box, y: 9 * box }];
let direction;
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp' && direction !== 'down') {
direction = 'up';
} else if (event.key === 'ArrowDown' && direction !== 'up') {
direction = 'down';
} else if (event.key === 'ArrowLeft' && direction !== 'right') {
direction = 'left';
} else if (event.key === 'ArrowRight' && direction !== 'left') {
direction = 'right';
}
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'white';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'black';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'left') snakeX -= box;
if (direction === 'up') snakeY -= box;
if (direction === 'right') snakeX += box;
if (direction === 'down') snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
const newHead = { x: snakeX, y: snakeY };
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert('Игра окончена!');
}
snake.unshift(newHead);
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
const game = setInterval(draw, 100);
</script>
</body>
</html>
Этот код создает простую игру "Змейка", в которой игрок управляет змеей с помощью стрелок на клавиатуре, собирает еду и пытается не столкнуться с границами поля и самим собой.