<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: white;
font-family: Arial, sans-serif;
}
canvas {
background-color: #111;
border: 2px solid #0f0;
}
</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
};
document.addEventListener("keydown", event => {
if (event.key === "ArrowLeft" && direction !== "right") direction = "left";
if (event.key === "ArrowUp" && direction !== "down") direction = "up";
if (event.key === "ArrowRight" && direction !== "left") direction = "right";
if (event.key === "ArrowDown" && direction !== "up") direction = "down";
});
function draw() {
ctx.clearRect(0, 0, 400, 400);
// Draw food
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
// Draw snake
ctx.fillStyle = "lime";
for (let segment of snake) {
ctx.fillRect(segment.x, segment.y, box, box);
}
// Movement
let head = { ...snake[0] };
if (direction === "left") head.x -= box;
if (direction === "right") head.x += box;
if (direction === "up") head.y -= box;
if (direction === "down") head.y += box;
// Collision with food
if (head.x === food.x && head.y === food.y) {
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
// Check collision with walls or body
if (
head.x < 0 || head.x >= 400 ||
head.y < 0 || head.y >= 400 ||
snake.some(segment => segment.x === head.x && segment.y === head.y)
) {
clearInterval(game);
alert("Game Over");
}
snake.unshift(head);
}
const game = setInterval(draw, 100);
</script>
</body>
</html>