<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<script>
// Set up the canvas
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
// Set up the snake
var snake = [
{x: 150, y: 150},
{x: 140, y: 150},
{x: 130, y: 150},
{x: 120, y: 150},
{x: 110, y: 150}
];
// Set the initial direction
var dx = 10;
var dy = 0;
// Set the initial score to 0
var score = 0;
// Set the initial food position
var foodX = Math.floor(Math.random() * 20) * 20;
var foodY = Math.floor(Math.random() * 20) * 20;
// Set the game speed (in milliseconds)
var gameSpeed = 100;
// Initialize the game
function init() {
// Set the canvas dimensions
canvas.width = 400;
canvas.height = 400;
// Start the game loop
setInterval(draw, gameSpeed);
}
// Main game loop
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move the snake in the current direction
var head = {x: snake[0].x + dx, y: snake[0].y + dy};
// Add the new head to the beginning of the snake
snake.unshift(head);
// Check if the snake has collided with the food
if (head.x === foodX && head.y === foodY) {
// Increase the score and create a new food item
score += 10;
foodX = Math.floor(Math.random() * 20) * 20;
foodY = Math.floor(Math.random() * 20) * 20;
} else {
// Remove the tail from the snake
snake.pop();
}
// Draw the snake on the canvas
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? '#00ff00' : '#009900';
ctx.fillRect(snake.x, snake.y, 10, 10);
}
// Draw the food on the canvas
ctx.fillStyle = '#ff0000';
ctx.fillRect(foodX, foodY, 10, 10);
// Draw the score on the canvas
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 12px sans-serif';
ctx.fillText('Score: ' + score, 10, 20);
}
// Initialize the game