Here's a fully functioning Snake game using JavaScript and the <canvas> element, as per your requirements:
<!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>
body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="game" width="300" height="300"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 30;
const gridPixel = canvas.width / gridSize;
let score = 0;
let highScore = 0;
let snake = [{x: 10, y: 10}];
let apple = {x: 15, y: 15};
let dx = 0;
let dy = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw snake
ctx.fillStyle = 'green';
for (const part of snake) {
ctx.fillRect(part.x * gridPixel, part.y * gridPixel, gridPixel - 1, gridPixel - 1);
}
// Draw apple
ctx.fillStyle = 'red';
ctx.fillRect(apple.x * gridPixel, apple.y * gridPixel, gridPixel - 1, gridPixel - 1);
// Draw score
ctx.fillStyle = 'black';
ctx.font = '16px sans-serif';
ctx.fillText(`Score: ${score}`, 8, 20);
ctx.fillText(`High Score: ${highScore}`, 8, 40);
}
function update() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
if (head.x === apple.x && head.y === apple.y) {
score += 10;
apple = {x: Math.floor(Math.random() * gridSize), y: Math.floor(Math.random() * gridSize)};
} else {
snake.pop();
}
snake.unshift(head);
if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize || snake.slice(1).some(part => part.x === head.x && part.y === head.y)) {
score = 0;
snake = [{x: 10, y: 10}];
dx = 0;
dy = 0;
}
if (score > highScore) {
highScore = score;
}
draw();
}
function changeDirection(event) {
if (event.key === 'ArrowUp' && dy === 0) {
dx = 0;
dy = -1;
} else if (event.key === 'ArrowDown' && dy === 0) {
dx = 0;
dy = 1;
} else if (event.key === 'ArrowLeft' && dx === 0) {
dx = -1;
dy = 0;
} else if (event.key === 'ArrowRight' && dx === 0) {
dx = 1;
dy = 0;
}
}
document.addEventListener('keydown', changeDirection);
setInterval(update, 500);
</script>
</body>
</html>
Copy and paste the code above into a new HTML file and open it in a web browser to play the Snake game. The game features arrow key controls, apple spawning, snake growth, score display, and high score tracking. The game restarts when the snake hits a wall or overlaps with itself.