<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
margin: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
background: #111;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [{x: 200, y: 200}];
let direction = "RIGHT";
let food = {
x: Math.floor(Math.random()*20)*box,
y: Math.floor(Math.random()*20)*box
};
let score = 0;
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
if (e.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
if (e.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
if (e.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
});
function game() {
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, 400, 400);
// еда
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
// змея
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "lime" : "green";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
let head = {...snake[0]};
if (direction === "UP") head.y -= box;
if (direction === "DOWN") head.y += box;
if (direction === "LEFT") head.x -= box;
if (direction === "RIGHT") head.x += box;
// столкновение со стеной
if (head.x < 0 || head.x >= 400 || head.y < 0 || head.y >= 400) {
alert("Game Over! Score: " + score);
document.location.reload();
}
// столкновение с собой
for (let part of snake) {
if (head.x === part.x && head.y === part.y) {
alert("Game Over! Score: " + score);
document.location.reload();
}
}
snake.unshift(head);
// еда
if (head.x === food.x && head.y === food.y) {
score++;
food = {
x: Math.floor(Math.random()*20)*box,
y: Math.floor(Math.random()*20)*box
};
} else {
snake.pop();
}
ctx.fillStyle = "white";
ctx.fillText("Score: " + score, 10, 10);
}
setInterval(game, 100);
</script>
</body>
</html>