Simple Snake game in HTML and JavaScript

Simple Snake game in HTML and JavaScript

Snake is so simple everyone can do it. But in case you need inspiration, here is how.

Image for postPhoto by Waldemar Brandt on Unsplash

Create an index.html file. And put the basic html stuff inside.

<!DOCTYPE html><html lang=”en”><head><meta charset=”UTF-8″ /><meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /><meta http-equiv=”X-UA-Compatible” content=”ie=edge” /><title>Snake</title></head><body></body></html>

Now inside body, add a canvas element.

<canvas id=”canvas” width=”400″ height=”400″></canvas>

Javascript

After the canvas add script tag, this is where the JavaScript will be, that will handle the snake logic and rendering to the canvas.

Let?s first define what should happen when window.onload triggers. We want to get context of the canvas, we want an event listener for player key presses and we want that the canvas redraws itself of the new position of the snake and the apple every so often.

var canvas, ctx;window.onload = function() { canvas = document.getElementById(“canvas”); ctx = canvas.getContext(“2d”); document.addEventListener(“keydown”, keyDownEvent); // render X times per second var x = 8; setInterval(draw, 1000 / x);};

I want draw to trigger every 8 times per second. You can make it faster or slower, by changing the X value.

Input

Now we need to define the keyDownEvent function. Key codes represent the arrow keys, starting with the left arrow key and going clockwise.

function keyDownEvent(e) { switch (e.keyCode) { case 37: nextX = -1; nextY = 0; break; case 38: nextX = 0; nextY = -1; break; case 39: nextX = 1; nextY = 0; break; case 40: nextX = 0; nextY = 1; break; }}

nextX and nextY represent direction of the snake. Meaning if we go left, we want the Y to be the same, but the X should be 1 minus the current position of the snakes X.

Snake

Lets define the Snake variables so we have a better idea.

// snakevar defaultTailSize = 3;var tailSize = defaultTailSize;var snakeTrail = ;var snakeX = snakeY = 10;

The default tail size will be 3. We start the tail size with the default value. Snake trail is the snakes body, it will be an array of X and Y positions. The snakeX and snakeY is the starting position of the snake.

Game world

The game world is where our snake and our apple lives. It?s defined as a 20×20 grid. So 20×20 = 400, which matches the canvas width & height.

// game worldvar gridSize = tileSize = 20; // 20 x 20 = 400var nextX = nextY = 0;

Apple

For apple we just need to define an X and Y position.

// applevar appleX = (appleY = 15);

Updating the game world (draw)

So every X times we call the function draw. It does a few things. First we need to move the snake to the next position.

// move snake in next possnakeX += nextX;snakeY += nextY;

But we also need to check if the snake is not out of bounds of the game world and reset the position so it looks like it comes out from the other side.

// snake over game world?if (snakeX < 0) { snakeX = gridSize – 1;}if (snakeX > gridSize – 1) { snakeX = 0;}if (snakeY < 0) { snakeY = gridSize – 1;}if (snakeY > gridSize – 1) { snakeY = 0;}

Now we check if in this next position, the snake bites the apple. If it does, we need to increase the tail size of the snake, and calculate a new X and Y position for the apple.

//snake bite apple?if (snakeX == appleX && snakeY == appleY) { tailSize++; appleX = Math.floor(Math.random() * gridSize); appleY = Math.floor(Math.random() * gridSize);}

Painting time. First we need to redraw the background.

//paint backgroundctx.fillStyle = “black”;ctx.fillRect(0, 0, canvas.width, canvas.height);

Now the snake. But while we draw the snake we must also check if the snake bite it?s own tail. Which would mean we need to reset tail back to the starting size.

// paint snakectx.fillStyle = “green”;for (var i = 0; i < snakeTrail.length; i++) { ctx.fillRect( snakeTrail[i].x * tileSize, snakeTrail[i].y * tileSize, tileSize, tileSize ); //snake bites it’s tail? if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) { tailSize = defaultTailSize; }}

Painting the apple is simple.

// paint applectx.fillStyle = “red”;ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);

And at the end we check if the snake trail exceeds the tail size. If it does, we shift the last positions out of the trail.

//set snake trailsnakeTrail.push({ x: snakeX, y: snakeY });while (snakeTrail.length > tailSize) { snakeTrail.shift();}

That?s it. Thats a snake game. Code here: https://github.com/zprima/snake-js-game

16

No Responses

Write a response