Certainly! Below is a complete snake game implemented in one HTML document. You can copy and paste this code into a file with an .html extension and open it in a modern web browser (like Chrome, Firefox, or Edge) to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
/* Style reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: #fff;
font-family: Arial, sans-serif;
}
#game-area {
position: relative;
border: 2px solid #555;
background: #111;
}
#score {
position: absolute;
top: -40px;
font-size: 24px;
}
</style>
</head>
<body>
<div id="game-area">
<canvas id="game" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
</div>
<script>
// Canvas setup
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
// Game constants
const gridSize = 20;
const canvasSize = canvas.width;
const cellSize = canvasSize / gridSize;
// Game variables
let snake = [{ x: 10, y: 10 }];
let food = getRandomPosition();
let velocity = { x: 0, y: 0 };
let score = 0;
let gameLoopId;
// Start the game
function startGame() {
document.addEventListener('keydown', changeDirection);
gameLoopId = setInterval(gameLoop, 100);
}
// Game loop
function gameLoop() {
update();
draw();
}
// Update game state
function update() {
// Move snake
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
snake.unshift(head);
// Check for food collision
if (head.x === food.x && head.y === food.y) {
score++;
document.getElementById('score').textContent = 'Score: ' + score;
food = getRandomPosition();
} else {
snake.pop();
}
// Check for wall collision
if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
endGame();
}
// Check for self collision
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
endGame();
}
}
}
// Draw everything
function draw() {
// Clear canvas
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvasSize, canvasSize);
// Draw snake
ctx.fillStyle = 'lime';
snake.forEach(segment => {
ctx.fillRect(segment.x * cellSize, segment.y * cellSize, cellSize - 1, cellSize - 1);
});
// Draw food
ctx.fillStyle = 'red';
ctx.fillRect(food.x * cellSize, food.y * cellSize, cellSize - 1, cellSize - 1);
}
// Change snake direction
function changeDirection(e) {
const { key } = e;
if (key === 'ArrowUp' && velocity.y === 0) {
velocity = { x: 0, y: -1 };
} else if (key === 'ArrowDown' && velocity.y === 0) {
velocity = { x: 0, y: 1 };
} else if (key === 'ArrowLeft' && velocity.x === 0) {
velocity = { x: -1, y: 0 };
} else if (key === 'ArrowRight' && velocity.x === 0) {
velocity = { x: 1, y: 0 };
}
}
// Get random position for food
function getRandomPosition() {
return {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize),
};
}
// End game
function endGame() {
clearInterval(gameLoopId);
alert('Game Over! Your score was ' + score);
// Reset game
snake = [{ x: 10, y: 10 }];
velocity = { x: 0, y: 0 };
food = getRandomPosition();
score = 0;
document.getElementById('score').textContent = 'Score: ' + score;
gameLoopId = setInterval(gameLoop, 100);
}
// Start the game
startGame();
</script>
</body>
</html>
How the Code Works
-
HTML Structure: The <canvas> element is used for drawing the game graphics. A <div> displays the current score.
-
CSS Styling: Basic styling centers the game on the page, styles the game area, and positions the score display.
-
JavaScript Logic:
- Game Initialization: Sets up the canvas, game variables (snake array, food position, velocity, score), and starts the game loop.
- Game Loop: The
setInterval function calls gameLoop every 100 milliseconds to update and redraw the game.
- Update Function: Moves the snake, checks for collisions with food, walls, and itself, updates the score, and handles game over conditions.
- Draw Function: Clears the canvas and redraws the snake and food on the updated positions.
- Controls: Listens for arrow key presses to change the snake's direction.
- Food Positioning: The
getRandomPosition function places the food at a random position within the grid.
- Game Over Handling: Alerts the player, resets the game variables, and restarts the game loop.
How to Use
- Save the Code: Copy the entire code and paste it into a new text file.
- Save As HTML: Save the file with a
.html extension, for example, snake-game.html.
- Open in Browser: Open the HTML file in a modern web browser.
- Play the Game:
- Use the Arrow Keys to control the snake's movement.
- Eat the red food squares to grow the snake and increase your score.
- Avoid running into the walls or the snake's own body.
- The game restarts automatically upon game over.
Customization Options
- Change Game Speed: Adjust the interval in
setInterval(gameLoop, 100) to make the game faster (<100) or slower (>100).
- Adjust Grid Size: Change the
gridSize variable to increase or decrease the number of cells.
- Modify Snake and Food Colors: Change the
ctx.fillStyle values in the draw function to customize colors.
- Enhance Features: Add levels, sound effects, or mobile touch controls for an enriched gaming experience.
Feel free to customize the game to your liking! If you have any questions or need assistance with modifications, let me know!