Skip to content
Shivam Singh

Snake Game

Project, Game, HTML, CSS, JavaScript1 min read

Snake Game screenshot

Introduction.

A snake game is a simple game where a snake moves around a box trying to eat an apple. Once it successfully eats the apple, the length of the snake increases and the movement becomes faster.

Then the game is over when the snake runs into itself or any of the four walls of the box.

Initialising the canvas.

./index.html
1<canvas id="snakeCanvas"></canvas>

Initialised the canvas with an id snakeCanvas

Initialising the Snake

./js/main.js
1snake = {
2 init_len: 5,
3 color: "#FDBF5F",
4 cells: [],
5 size: 5,
6 direction: "right",
7
8
9 createSnake: function () {
10 for (var i = this.init_len; i >= 0; i--) {
11 this.cells.push({
12 x: i,
13 y: 0
14 });
15 }
16 },

Where init_len is the initial lenght of the canvas, the cells array will store the position of the snake and the initial direction of snake is right.
Inside the createSnake function the initial cordinates of the position of snake are being pushed inside the cells array.
Since, the initial position of the snake is horizontal the cordinates of y remain 0 and x varies from init_len to 0.

Taking input from the keyboard.

./js/main.js
1function keyPressed(e) {
2 if (e.key == "ArrowRight" && snake.direction != "left") {
3 snake.direction = "right";
4 } else if (e.key == "ArrowLeft" && snake.direction != "right") {
5 snake.direction = "left";
6 } else if (e.key == "ArrowDown" && snake.direction != "up") {
7 snake.direction = "down";
8 } else if (e.key == "ArrowUp" && snake.direction != "down") {
9 snake.direction = "up";
10 console.log(e.key);
11 }
12 }

The keyPressed function receives a parameter e which contains all the information about the key being pressed. But we are only interested in the key which is pressed so we will access it by e.key.
if e.key = ArrowRight the direction of the snake will become right and so on.

To play the game click here
To checkout the full source code click here