<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
canvas {
background: #f0f0f0;
display: block;
margin: 0 auto;
}
body {
text-align: center;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Snake Game</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let score = 0;
let snake = [{x: 9 * box, y: 9 * box}];
let direction = null;
const food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
document.addEventListener('keydown', event => {
if (event.key === 'ArrowUp' && direction !== 'DOWN') direction = 'UP';
else if (event.key === 'ArrowDown' && direction !== 'UP') direction = 'DOWN';
else if (event.key === 'ArrowLeft' && direction !== 'RIGHT') direction = 'LEFT';
else if (event.key === 'ArrowRight' && direction !== 'LEFT') direction = 'RIGHT';
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
// Draw the food
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
// Draw the snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'lightgreen';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'white';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'UP') snakeY -= box;
if (direction === 'DOWN') snakeY += box;
if (direction === 'LEFT') snakeX -= box;
if (direction === 'RIGHT') snakeX += box;
// Check for collision with food
if (snakeX === food.x && snakeY === food.y) {
score++;
food.x = Math.floor(Math.random() * 20) * box;
food.y = Math.floor(Math.random() * 20) * box;
} else {
snake.pop(); // Remove the tail
}
// Add new head
const newHead = {x: snakeX, y: snakeY};
// Check for collision with walls or itself
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert('Game Over! Your score is ' + score);
}
snake.unshift(newHead); // Add new head to the snake
}
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; // Collision detected
}
}
return false;
}
const game = setInterval(draw, 100); // Call the draw function every 100 ms
</script>
</body>
</html>
Feel free to modify and enhance the game by adding features like a scoreboard, levels, or improved graphics!