Below is an example of a simple Snake game implemented in a single HTML file. You can save this as, for example, snake.html and then open it in your browser to play the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
margin: 0;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: sans-serif;
}
canvas {
background-color: #111;
display: block;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const gridSize = 20; // Size of one grid block (20px by 20px)
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const columns = canvasWidth / gridSize;
const rows = canvasHeight / gridSize;
let snake;
let food;
let dx, dy;
let gameLoop;
const speed = 100; // Game update speed, in ms (100ms per frame)
// Initialize the game
function init() {
// Start the snake in the center of the canvas.
snake = [{ x: Math.floor(columns / 2), y: Math.floor(rows / 2) }];
// Start moving to the right.
dx = 1;
dy = 0;
placeFood();
document.addEventListener("keydown", keyDown);
if (gameLoop) {
clearInterval(gameLoop);
}
gameLoop = setInterval(gameTick, speed);
}
// Game loop tick: move snake, check collisions, and redraw
function gameTick() {
// Determine new head position based on direction.
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
// Check collision with walls.
if (
head.x < 0 ||
head.x >= columns ||
head.y < 0 ||
head.y >= rows ||
checkSnakeCollision(head)
) {
gameOver();
return;
}
// Add the new head to the snake.
snake.unshift(head);
// Check if snake has eaten the food.
if (head.x === food.x && head.y === food.y) {
placeFood();
} else {
// Remove the tail segment if no food is eaten.
snake.pop();
}
drawGame();
}
// Return true if the head collides with the body.
function checkSnakeCollision(head) {
return snake.some(segment => segment.x === head.x && segment.y === head.y);
}
// Place food at a random grid location; ensure it is not on the snake.
function placeFood() {
food = {
x: Math.floor(Math.random() * columns),
y: Math.floor(Math.random() * rows)
};
// If the random place is on the snake, try placing food again.
if (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
placeFood();
}
}
// Draw everything in the game: the background, food, and snake.
function drawGame() {
// Clear the canvas.
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
// Draw the food.
ctx.fillStyle = "#e74c3c";
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
// Draw the snake.
ctx.fillStyle = "#2ecc71";
snake.forEach(segment => {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
});
}
// Listen for arrow or WASD keys to change direction.
function keyDown(event) {
switch (event.keyCode) {
case 37: // Left arrow
case 65: // A
if (dx === 1) break; // Prevent reversing
dx = -1;
dy = 0;
break;
case 38: // Up arrow
case 87: // W
if (dy === 1) break;
dx = 0;
dy = -1;
break;
case 39: // Right arrow
case 68: // D
if (dx === -1) break;
dx = 1;
dy = 0;
break;
case 40: // Down arrow
case 83: // S
if (dy === -1) break;
dx = 0;
dy = 1;
break;
}
}
// Handle game over: stop the game and restart.
function gameOver() {
clearInterval(gameLoop);
alert("Game Over! Press OK to restart.");
init();
}
// Start the game.
init();
</script>
</body>
</html>
How It Works
-
HTML & Canvas:
The <canvas> element is used to render the game. The canvas is set to 400x400 pixels.
-
CSS:
The CSS centers the canvas on a black background.
-
JavaScript:
- The snake is represented as an array of objects, where each object holds the
x and y grid coordinates.
- The game grid is based on a grid cell size (20px).
- The game loop (
setInterval) updates every 100ms, moving the snake and checking for collisions.
- The
keydown event listener changes the snake's direction without allowing a 180° reversal.
- When the snake eats the food, the tail is not removed (thus growing the snake), and new food is placed randomly.
- If the snake hits a wall or its own body, the game stops and a restart is triggered after an alert.
Enjoy tweaking and playing with the code!