Welcome to this interactive guide on how to create your very own Snake game using HTML, CSS, and JavaScript. Whether you’re a coding novice or an experienced developer, this step-by-step tutorial will help you build a classic game while enhancing your web development skills. Let’s dive in and start coding!
Step 1: Set Up the HTML Structure
We’ll create a simple HTML structure for our game. In your code editor, create a new HTML file and add the following code:
<!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>
<link rel="stylesheet" href="snake.css">
</head>
<body>
<canvas id="game-board" width="300" height="300"></canvas>
<script src="snake.js"></script>
</body>
</html>
This code sets up a basic HTML structure, linking to an external CSS file (snake.css) and an external JavaScript file (snake.js), which we’ll create later.
Related Content: Play HTML Video in Next Js.
Step 2: Design the Game Board with CSS
Now, let’s add some styles to our game. Create a new file named ‘styles.css’ and add the following code:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #222;
margin: 0;
}
canvas {
border: 1px solid #fff;
}
Step 3: Create the Snake Game Logic with JavaScript
Now, let’s add interactivity and game logic using JavaScript. Create a new file named ‘snake.js’ and add the following code:
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const gridSize = 10;
let snake = [{ x: 150, y: 150 }];
let food = { x: 50, y: 50 };
let dx = 0;
let dy = 0;
document.addEventListener('keydown', handleKeydown);
function handleKeydown(e) {
if (e.key === 'ArrowUp' && dy === 0) { dy = -gridSize; dx = 0; }
if (e.key === 'ArrowDown' && dy === 0) { dy = gridSize; dx = 0; }
if (e.key === 'ArrowLeft' && dx === 0) { dx = -gridSize; dy = 0; }
if (e.key === 'ArrowRight' && dx === 0) { dx = gridSize; dy = 0; }
}
function moveSnake() {
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
generateFood();
} else {
snake.pop();
}
}
function generateFood() {
food = {
x: Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize,
y: Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize
};
}
function checkCollision(head) {
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
return true;
}
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'lime';
for (const segment of snake) {
ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, gridSize, gridSize);
}
function gameLoop() {
moveSnake();
if (checkCollision(snake[0])) {
snake = [{ x: 150, y: 150 }];
dx = 0;
dy = 0;
}
draw();
setTimeout(gameLoop, 100);
}
gameLoop();
This JavaScript code adds the game logic to move the snake, spawn food, detect collisions, and change the snake’s direction based on keyboard input. The game loop (main function) is called recursively with a 100ms delay to control the game’s speed.
Related Content, How to link css to html in vs code?
FAQ
What programming languages do I need to know to make a Snake game in HTML?
You need to have a basic understanding of HTML, CSS, and JavaScript to create a Snake game in HTML.
Can I create a Snake game using only HTML?
No, you need JavaScript to handle the game logic and CSS to style the game elements.
How do I start building the Snake game in HTML?
Begin by setting up your HTML structure with a canvas element, and then use JavaScript to create the game logic and CSS to style the game.
How do I handle the movement of the snake in the game?
Use JavaScript to track the snake’s position, direction, and speed, updating its coordinates at regular intervals to create smooth movement.
Conclusion
Congratulations! You’ve successfully built a Snake game in HTML, CSS, and JavaScript. This guide provided you with step-by-step instructions and example code, ensuring a smooth coding experience. As you continue to develop your skills, consider enhancing the game by adding features like scoring, levels, or different visual themes. Happy coding!