Certainly! Below is a simple implementation of the classic Snake game using HTML, CSS, and JavaScript. The code is separated into three parts for each language.
HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<!-- Link to the external CSS file -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Snake Game</h1>
<p>Score: <span id="score">0</span></p>
<!-- The game board -->
<canvas id="gameCanvas" width="400" height="400"></canvas>
<!-- Include the JavaScript file -->
<script src="script.js"></script>
</body>
</html>
CSS (styles.css)
body {
text-align: center;
background-color: #f0f0f0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
h1 {
color: #333;
}
#gameCanvas {
background-color: #fff;
border: 1px solid #ccc;
}
.snake-segment {
fill: #66bb6a;
}
.snake-eye {
fill: #000;
}
JavaScript (script.js)
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
// Game settings
const boxSize = 20;
const canvasSize = canvas.width;
let score = 0;
// Snake settings
let snake = [
{ x: boxSize * 5, y: boxSize * 5 },
{ x: boxSize * 4, y: boxSize * 5 },
{ x: boxSize * 3, y: boxSize * 5 }
];
let direction = 'RIGHT';
// Food position
let food = {
x: Math.floor(Math.random() * (canvasSize / boxSize)) * boxSize,
y: Math.floor(Math.random() * (canvasSize / boxSize)) * boxSize
};
// Control the snake
document.addEventListener('keydown', changeDirection);
function changeDirection(event) {
const key = event.keyCode;
if (key === 37 && direction !== 'RIGHT') {
direction = 'LEFT';
} else if (key === 38 && direction !== 'DOWN') {
direction = 'UP';
} else if (key === 39 && direction !== 'LEFT') {
direction = 'RIGHT';
} else if (key === 40 && direction !== 'UP') {
direction = 'DOWN';
}
}
function drawSnake() {
snake.forEach((segment, index) => {
// Draw snake segment
ctx.fillStyle = '#66bb6a';
ctx.fillRect(segment.x, segment.y, boxSize, boxSize);
ctx.strokeStyle = '#fff';
ctx.strokeRect(segment.x, segment.y, boxSize, boxSize);
// Add eyes to the head
if (index === 0) {
ctx.fillStyle = '#000';
// Left eye
ctx.beginPath();
ctx.arc(segment.x + boxSize / 4, segment.y + boxSize / 4, 2, 0, 2 * Math.PI);
ctx.fill();
// Right eye
ctx.beginPath();
ctx.arc(segment.x + (3 * boxSize) / 4, segment.y + boxSize / 4, 2, 0, 2 * Math.PI);
ctx.fill();
}
});
}
function drawFood() {
ctx.fillStyle = '#ff6f61';
ctx.fillRect(food.x, food.y, boxSize, boxSize);
}
function moveSnake() {
const head = { x: snake[0].x, y: snake[0].y };
// Move head
if (direction === 'LEFT') head.x -= boxSize;
if (direction === 'UP') head.y -= boxSize;
if (direction === 'RIGHT') head.x += boxSize;
if (direction === 'DOWN') head.y += boxSize;
// Add new head
snake.unshift(head);
// Check for food collision
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.textContent = score;
// Generate new food
food = {
x: Math.floor(Math.random() * (canvasSize / boxSize)) * boxSize,
y: Math.floor(Math.random() * (canvasSize / boxSize)) * boxSize
};
} else {
// Remove last segment
snake.pop();
}
// Check for wall collision
if (
head.x < 0 || head.x >= canvasSize ||
head.y < 0 || head.y >= canvasSize ||
collision(head, snake.slice(1))
) {
clearInterval(game);
alert('Game Over!');
}
}
function collision(head, snakeArray) {
return snakeArray.some(segment => segment.x === head.x && segment.y === head.y);
}
function draw() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
drawFood();
moveSnake();
drawSnake();
}
// Start the game
let game = setInterval(draw, 100);
Explanation
-
HTML
- The HTML file sets up the basic structure of the game, including a heading, a score display, and a
<canvas> element where the game is rendered.
- It links to the external CSS and JavaScript files.
-
CSS
- The CSS styles the body, heading, and the game canvas.
- It defines the colors for the snake and its eyes.
- Note: In this implementation, styling for the snake is handled via canvas drawing, but the CSS file includes classes (
.snake-segment, .snake-eye) if you choose to use SVG or HTML elements instead.
-
JavaScript
- The JavaScript file contains all the game logic.
- It initializes the game settings and snake starting position.
- It handles keyboard input to change the snake's direction.
- The
drawSnake function draws the snake on the canvas and adds eyes to the head.
- The
moveSnake function updates the snake's position, checks for collisions with the walls, itself, and food.
- The game loop is set using
setInterval, which calls the draw function every 100 milliseconds.
Running the Game
-
File Structure:
- Create a folder for your project.
- Inside the folder, create three files:
index.html, styles.css, and script.js.
- Ensure all files are in the same directory.
-
Starting the Game:
- Open the
index.html file in a web browser.
- Use the arrow keys on your keyboard to control the snake.
-
Features:
- The score increases by 10 points each time the snake eats the food.
- The snake has eyes drawn on its head for a visual effect.
- The game ends when the snake hits the walls or itself.
Feel free to customize the game by adjusting the colors, speeds, and sizes in the CSS and JavaScript files.