html Copy code
<!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 {
background-color: #f4f4f4;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
canvas {
border: 1px solid #000;
background-color: #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Начальные настройки змейки
const box = 20;
let snake = [];
snake[0] = {
x: 9 * box,
y: 10 * box
};
let direction;
document.addEventListener("keydown", changeDirection);
function changeDirection(event) {
if (event.keyCode == 37 && direction != "RIGHT") {
direction = "LEFT";
} else if (event.keyCode == 38 && direction != "DOWN") {
direction = "UP";
} else if (event.keyCode == 39 && direction != "LEFT") {
direction = "RIGHT";
} else if (event.keyCode == 40 && direction != "UP") {
direction = "DOWN";
}
}
let food = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
let score = 0;
function drawGame() {
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 = "red";
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) {
score++;
food = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
} else {
snake.pop();
}
let newHead = {
x: snakeX,
y: snakeY
};
if(snakeX < 0 || snakeX >= 18 * box || snakeY < 3 * box || snakeY >= 18 * box || collision(newHead, snake)){
clearInterval(game);
}
snake.unshift(newHead);
ctx.fillStyle = "black";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
}
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;
}
let game = setInterval(drawGame, 100);
</script>
</body>
</html>
Это простой HTML-документ с игровым канвасом и скриптом на JavaScript для реализации игры "Змейка". Вы можете запустить этот код в любом современном веб-браузере. Управление змейкой осуществляется с помощью стрелок клавиатуры.