make a snake game with html + CSS + JS
- User
make a snake game with html + CSS + JS
- Assistant
make a snake game with html + CSS + JS
Sure! I'd be happy to help you create a simple Snake game using HTML, CSS, and JavaScript. Below is the complete code along with explanations for each part.
We'll build a classic Snake game where the player controls a snake that moves around the game area, eating food to grow longer. The game ends if the snake collides with the walls or itself.
Create a project folder and include the following files:
snake-game/
├── index.html
├── styles.css
└── script.js
index.html)This file sets up the basic structure of the webpage and includes the canvas element where the game will be rendered.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
Explanation:
<canvas> element with id="gameCanvas" is where we'll draw the game.styles.css)Style the game canvas and the page.
body {
margin: 0;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#gameCanvas {
border: 1px solid #fff;
background-color: #111;
}
Explanation:
script.js)This is the main logic for the game.
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Cell size
const box = 20;
// Game variables
let snake = [];
snake[0] = {
x: 9 * box,
y: 9 * box
};
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
let score = 0;
let d = '';
// Control the snake
document.addEventListener('keydown', direction);
function direction(event) {
if (event.keyCode == 37 && d != 'RIGHT') {
d = 'LEFT';
} else if (event.keyCode == 38 && d != 'DOWN') {
d = 'UP';
} else if (event.keyCode == 39 && d != 'LEFT') {
d = 'RIGHT';
} else if (event.keyCode == 40 && d != 'UP') {
d = 'DOWN';
}
}
// Check collision
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
}
return false;
}
// Draw everything to the canvas
function draw() {
// Draw the background
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i == 0) ? '#66ff66' : '#99ff99';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = '#003300';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// Draw the food
ctx.fillStyle = '#ff3333';
ctx.fillRect(food.x, food.y, box, box);
// Old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Move snake in the direction
if (d == 'LEFT') snakeX -= box;
if (d == 'UP') snakeY -= box;
if (d == 'RIGHT') snakeX += box;
if (d == 'DOWN') snakeY += box;
// Snake eats food
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
// Don't remove the tail
} else {
// Remove the tail
snake.pop();
}
// New head position
let newHead = {
x: snakeX,
y: snakeY
};
// Game over conditions
if (snakeX < 0 || snakeX >= canvas.width || snakeY < 0 || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert('Game Over! Your score was: ' + score);
return;
}
// Add new head
snake.unshift(newHead);
// Display the score
ctx.fillStyle = '#fff';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, 10, 390);
}
// Call draw function every 100 milliseconds
let game = setInterval(draw, 100);
Explanation:
Variables:
canvas and ctx: Set up the canvas for drawing.box: The size of one cell in the game grid (20 pixels).snake: An array representing the snake's body parts.food: An object representing the food's position.score: The player's score.d: The current direction the snake is moving.Control Function:
d) accordingly.Collision Function:
Draw Function:
Game Loop:
draw function is called every 100 milliseconds using setInterval().Set Up Files:
index.html, styles.css, script.js) are saved in the same directory.Open in Browser:
index.html in your web browser.Controls:
Gameplay:
Restarting the Game:
Adjusting Speed:
setInterval(draw, 100); in script.js to adjust the game's speed.Improving the Game:
You've now created a basic Snake game using HTML, CSS, and JavaScript! Feel free to experiment with the code to add new features or improve the game's appearance.
If you have any questions or need further assistance, feel free to ask!
Not yet included in a published release.