I Just Made A Snake Game! Know How I Did This
Replace this fantastic game in your web while learning about JavaScript game development.
A snake game is a standard programming activity that can help you improve your programming and problem-solving skills.
The game may be created in a web browser using HTML, CSS, and JavaScript.
You control a snake that moves across a board in the game. As you collect food, the snake grows in size.
If you collide with your tail or any of the walls, the game will end.
How to Build a Canvas UI
Create a canvas for the snake to move around on with HTML and CSS.
If you need to study any basic concepts, there are a few more HTML and CSS projects you may work on.
The full source code is available on this project’s GitHub site.
1. Make a new file called index.html.
2. Use any text editor, such as Visual Code or Atom, to open the file.
3. Add the following HTML code structure:
<!doctype html>
<html lang="en-US">
<head>
<title>Snake Game</title>
</head>
<body>
</body>
</html>
4. Add a canvas within the body tag to create the snake’s gaming board.
<h2>Snake Game</h2>
<div id="game">
<canvas id="snake"></canvas>
</div>
5. Make a new file named “styles.css” in the same folder as your HTML file.
6. Add some CSS for the whole web page within. Other important CSS tips and tricks can also be used to lay out your website.
#game {
width:400px;
height:400px;
margin:0 auto;
background-color:#eee;
}
h2 {
text-align:center;
font-family:Arial;
font-size:36px;
}
7. Provide a link to the CSS in the head tag of your HTML file:
<link rel="stylesheet" type="text/css" href="styles.css">
8. Open your “index.html” file in a web browser to see the canvas.
How to Make a Snake
The snake is shown by the black line in the image below:
Multiple squares or “sections” make up the snake. The number of squares increases as the snake grows.
The snake’s length is one piece at the start of the game.
1. At the bottom of the body tag in your HTML file, add a link to a new JavaScript file:
<body>
<!-- Your code here -->
<script src="script.js"></script>
</body>
2. Create script.js and start by getting the canvas’s DOM element:
var canvas = document.getElementById("snake");
3. Set the canvas HTML element’s context. You want the game to render a 2D canvas in this case. You may now draw multiple shapes or images onto the HTML element.
var canvas2d = canvas.getContext("2d");
4. Set other in-game variables, such as whether the game has ended and the canvas’s height and width:
var gameEnded = false;
canvas.width = 400;
canvas.height = 400;
5. Declare “snakeSegments” as a variable.
This will keep track of how many “squares” the snake will take.
You can alternatively maintain track of the snake’s length by using a variable:
var snakeSegments = [];
var snakeLength = 1;
6. Declare the snake’s starting X and Y positions:
var snakeX = 0;
var snakeY = 0;
7. Make a brand-new function. Inside, add the first snake segment to the snakeSegments array, along with its X and Y coordinates:
function moveSnake() {
snakeSegments.unshift({ x: snakeX, y: snakeY });
}
8. Make a brand-new function. Set the fill style to black inside.
It will use the matching color to draw the snake:
function drawSnake() {
canvas2d.fillStyle = "black";
}
9. Draw a square with a width and height of 10 pixels for every segment that makes up the snake’s size:
for (var i = 0; i < snakeSegments.length; i++) {
canvas2d.fillRect(snakeSegments[i].x, snakeSegments[i].y, 10, 10);
}
10. Make a game loop that repeats every 100 milliseconds.
This will force the game to constantly draw the snake in its new position, which will be important when the snake starts to move:
function gameLoop() {
moveSnake();
drawSnake();
11. Open the “index.html” file in a web browser to discover the snake in its starting position at its smallest size.
How to Move the Snake
Add some logic to move the snake in different ways based on which button on the keyboard the player presses.
1. Declare the snake’s starting direction at the top of the file:
var directionX = 10;
var directionY = 0;
2. When the player presses a key, add a function called that activates:
document.onkeydown = function(event) {
};
3. Change the snake’s movement direction based on the key hit inside the event handler:
switch (event.keyCode) {
case 37: // Left arrow
directionX = -10;
directionY = 0;
break;
case 38: // Up arrow
directionX = 0;
directionY = -10;
break;
case 39: // Right arrow
directionX = 10;
directionY = 0;
break;
case 40: // Down arrow
directionX = 0;
directionY = 10;
break;
}
4. Use the direction to update the snake’s X and Y coordinates in the moveSnake() function.
For example, if the snake must move to the left, the X direction will be “-10”. For each frame of the game, this will update the X coordinate to remove 10 pixels:
function moveSnake() {
snakeSegments.unshift({ x: snakeX, y: snakeY });
snakeX += directionX;
snakeY += directionY;
}
5. While the snake is moving, the game does not remove previous segments.
This will result in the snake appearing like this:
6. To solve this, at the start of the drawSnake() function, clean the canvas before drawing the new snake in each frame:
canvas2d.clearRect(0, 0, canvas.width, canvas.height);
7. Inside the moveSnake() function, you must also delete the final entry of the snakeSegments array:
while (snakeSegments.length > snakeLength) {
snakeSegments.pop();
}
8. To move the snake, open the “index.html” file and press the left, right, up, or down arrow keys.
How to Make Food on a Canvas
To illustrate food bits for the snake, add dots to the board game.
1. At the top of the code, declare a new variable to hold an array of food pieces:
var dots = [];
2. Make a brand-new function. Generate random X and Y coordinates for the dots within.
You may also limit the number of dots on the board to 10 at any given time:
function spawnDots() {
if(dots.length < 10) {
var dotX = Math.floor(Math.random() * canvas.width);
var dotY = Math.floor(Math.random() * canvas.height);
dots.push({ x: dotX, y: dotY });
}
}
3. After you’ve generated the X and Y coordinates for the food, draw them into the canvas in red:
for (var i = 0; i < dots.length; i++) {
canvas2d.fillStyle = "red";
canvas2d.fillRect(dots[i].x, dots[i].y, 10, 10);
}
4. Within the game round, use the new spawnDots() function:
function gameLoop() {
moveSnake();
drawSnake();
spawnDots();
if(!gameEnded) {
setTimeout(gameLoop, 100);
}
}
5. To see the food on the game board, open the “index.html” page.
How to Grow the Snake
When the snake comes into contact with a food dot, you may make it grow in length.
1. Make a brand-new function. Within it, go over each element of the dots array:
function checkCollision() {
for (var i = 0; i < dots.length; i++) {
}
}
2. If the snake’s position matches the coordinates of any dots, the snake’s length is increased and the dot is deleted:
if (snakeX < dots[i].x + 10 &&
snakeX + 10 > dots[i].x &&
snakeY < dots[i].y + 10 &&
snakeY + 10 > dots[i].y) {
snakeLength++;
dots.splice(i, 1);
}
3. In the game loop, use the new checkCollision() function:
function gameLoop() {
moveSnake();
drawSnake();
spawnDots();
checkCollision();
if(!gameEnded) {
setTimeout(gameLoop, 100);
}
}
4. In a web browser, open the “index.html” file. Move the snake around using the keyboard to collect food and grow the snake.
How to Finish the Game
Check to see if the snake hit with its tail or any of the walls to end the game.
1. Make a new function that prints a “Game Over” message.
function gameOver() {
setTimeout(function() {
alert("Game over!");
}, 500);
gameEnded = true
}
2. Check whether the snake hit on any of the canvas’s walls inside the checkCollision() function.
If this is the case, execute the gameOver() function:
if (snakeX < -10 ||
snakeY < -10 ||
snakeX > canvas.width+10 ||
snakeY > canvas.height+10) {
gameOver();
}
3. Loop through each section of the snake to see if the head of the snake hit with any of the tail segments:
for (var i = 1; i < snakeSegments.length; i++) {
}
4. Check within the for-loop to see if the snake’s head matches any of the tail segments.
If this is the case, it means the head collided with a tail, hence the game should be ended:
if (snakeX === snakeSegments[i].x && snakeY === snakeSegments[i].y) {
gameOver();
}
5. In a web browser, open the “index.html” file. To end the game, try to hit a wall or your tail.
Games for Learning JavaScript Concepts
Creating games can be a great way to make your learning experience more enjoyable.
Keep making more games to continue improving your JavaScript knowledge.