Конечно! Ниже приведен полный HTML-код для простой игры "змейка" с использованием HTML, CSS и JavaScript:
<!DOCTYPE html>
<html lang="en">
<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;
font-family: Arial, sans-serif;
}
#game {
display: block;
border: 1px solid #000;
background-color: #fff;
}
.score-container {
margin-bottom: 10px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="score-container">Счет: <span id="score">0</span></div>
<canvas id="game" width="400" height="400"></canvas>
<script>
// Настройки игры
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [];
snake[0] = { x: 10 * box, y: 10 * box };
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
}
let score = 0;
let d;
document.addEventListener("keydown", direction);
function direction(event) {
if (event.keyCode === 37 && d !== "RIGHT") {
d = "LEFT";
} else if (event.keyCode === 38 && d !== "DOWN") {
d = "UP";
} else if (event.keyCode === 39 && d !== "LEFT") {
d = "RIGHT";
} else if (event.keyCode === 40 && d !== "UP") {
d = "DOWN";
}
}
function collision(newHead, array) {
for (let i = 0; i < array.length; i++) {
if (newHead.x === array[i].x && newHead.y === array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? "#000" : "#008000";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "#f0f0f0";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "#ff0000";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d === "LEFT") snakeX -= box;
if (d === "UP") snakeY -= box;
if (d === "RIGHT") snakeX += box;
if (d === "DOWN") snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
score++;
document.getElementById('score').innerText = score;
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);
}
snake.unshift(newHead);
}
const game = setInterval(draw, 100);
</script>
</body>
</html>
Этот код создает канвас, где змея начинает двигаться с помощью клавиш-стрелок на клавиатуре. Змея будет расти, поедая "еду" (красные квадраты), и игра завершится, если змея врежется в стену или в себя. Счет обновляется на экране каждый раз, когда змея съедает еду.