The Snake game in JavaScript is a classic game that involves a snake moving around on a grid, consuming food to grow longer. Here's a simple implementation that you can add to your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="snake-canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('snake-canvas');
const ctx = canvas.getContext('2d');
const snakeSpeed = 10;
// Set up initial snake position and food
let snake = [
{ x: 20, y: 20 },
{ x: 10, y: 20 },
{ x: 0, y: 20 },
{ x: 0, y: 10 },
];
let food = { x: 20, y: 20 };
function drawGrid() {
for (let x = 0; x <= canvas.width; x += 20) {
ctx.strokeRect(x, 0, 20, canvas.height);
}
for (let y = 0; y <= canvas.height; y += 20) {
ctx.strokeRect(0, y, canvas.width, 20);
}
}
function drawSnake() {
snake.forEach((s) => {
ctx.fillStyle = '#000';
ctx.fillRect(s.x, s.y, 20, 20);
});
}
function drawFood() {
ctx.fillStyle = '#f00';
ctx.fillRect(food.x, food.y, 20, 20);
}
function moveSnake(direction) {
let head = snake[0];
switch (direction) {
case 'up':
head.y -= 20;
break;
case 'down':
head.y += 20;
break;
case 'left':
head.x -= 20;
break;
case 'right':
head.x += 20;
break;
}
}
function startGame() {
document.addEventListener('keydown', (e) => {
switch (e.key) {
case 'ArrowUp':
moveSnake('up');
break;
case 'ArrowDown':
moveSnake('down');
break;
case 'ArrowLeft':
moveSnake('left');
break;
case 'ArrowRight':
moveSnake('right');
break;
}
});
let intervalId = setInterval(() => {
moveSnake();
drawGrid();
drawSnake();
drawFood();
}, snakeSpeed * 10);
}
startGame();
</script>
</body>
</html>
This code sets up a simple Snake game using JavaScript and the HTML5 canvas element. When you run it, you should see a grid with a snake moving around and a piece of food to eat. Use the arrow keys on your keyboard to control the snake's movement. The game loop updates the snake's position every snakeSpeed milliseconds.
Feel free to customize the code and add more features to the game. Enjoy!