<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const cellSize = 10;
let snake = [{x: 5, y: 5}];
let direction = "right";
let food = {x: 10, y: 10};
let score = 0;
function drawSnake() {
ctx.fillStyle = "green";
snake.forEach(function(cell) {
ctx.fillRect(cell.x * cellSize, cell.y * cellSize, cellSize, cellSize);
});
}
function moveSnake() {
let head = snake[0];
if (direction === "right") {
snake.unshift({x: head.x + 1, y: head.y});
} else if (direction === "left") {
snake.unshift({x: head.x - 1, y: head.y});
} else if (direction === "up") {
snake.unshift({x: head.x, y: head.y - 1});
} else if (direction === "down") {
snake.unshift({x: head.x, y: head.y + 1});
}
if (snake[0].x === food.x && snake[0].y === food.y) {
food = {
x: Math.floor(Math.random() * (canvas.width / cellSize)),
y: Math.floor(Math.random() * (canvas.height / cellSize))
};
score++;
} else {
snake.pop();
}
}
function drawFood() {
ctx.fillStyle = "red";
ctx.fillRect(food.x * cellSize, food.y * cellSize, cellSize, cellSize);
}
function drawScore() {
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText(`Score: ${score}`, 10, canvas.height - 10);
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
moveSnake();
drawFood();
drawScore();
}
function handleKeyDown(event) {
if (event.key === "ArrowRight" && direction !== "left") {
direction = "right";
} else if (event.key === "ArrowLeft" && direction !== "right") {
direction = "left";
} else if (event.key === "ArrowUp" && direction !== "down") {
direction = "up";
} else if (event.key === "ArrowDown" && direction !== "up") {
direction = "down";
}
}
setInterval(update, 100);
document.addEventListener("keydown", handleKeyDown);
</script>
</body>
</html>