Making a Snake Game with JavaScript under 7 Days

A simple Snake Game built using JavaScript, HTML, and CSS to enhance understanding of Java Script fundamentals


Day 1

Learning java script has been one of the key thing that i would like to understand on a deeper level as a computer engineering student java script and web development was field of specialty but learning the java script basics by building a product and game that would allow you to teach the basics of web development i think is a great way to learn something faster.

I have decided to learn and create a java script simple game that is same as the famous Nokia snake game. and the idea is to make a simple game under 7 days and challenge my self in learning java script through this journey.

I started on making the movement function by changing the styles and moving a div in html using the style.top and style.left to make the square look like it is moving.

document.addEventListener('keydown', movePlayer)
 
function movePlayer(event){
    const player = document.getElementById("player");
    let currentTop = parseInt(player.style.top) || 0;
    let currentLeft = parseInt(player.style.left) || 0;
 
    const distance = 10
 
    switch (event.key){
        case 'w':
            player.style.top = (currentTop - distance) + 'px';
            break;
        case 's':
            player.style.top = (currentTop + distance) + 'px';
            break;
        case 'a':
            player.style.left = (currentLeft - distance) + 'px';
            break;
        case 'd':
            player.style.left = (currentLeft + distance) + 'px';
            break;
    }
 
}

For this java script code i have used an event Listener to get the input of the 'key down' from the player.

The function movePlayer was made so i could implement it better and for future cases to easier upgrade the game in the future that i would want to implement new functions to it.

Changing HTML Elements using DOM

I used DOM or HTML Document Object Model

  • it is a standard object model and programming for HTML
  • it can be accessed by the java script (and other programming languages)

The best way to access a html element is to use the id element in HTML, to access it we can use the getElementById and you can see that the player variable is got to the html by putting the id of that in the html and now can be controlled using the .style function of the java script to change the direction that i would want it to move or make it look like that it is moving.

Making a button for prototyping the scoreboard

let score = 0;
 
function addScore(event){
    const scoreboard = document.getElementById("score");
 
    score++;
    scoreboard.innerHTML = score;
}
<div class="scoreboard">
	<h2 id="score">0</h2>
</div>
 
<button onclick="addScore()"> Add Score</button>

We can use element.innerHTML = new value to make a new value for an html.

So the two codes on top are in line with each other, the first one the java script code is a function that increments the score with score++ i also pointed it to the scoreboard with the id score to implement and put the change to the html i have used the DOM .innerHTML and equaled it to the score variable so i can track the information that i have in that and also i have learned that you can embed the function on a button so i just did that that on my onclick function to embed the java script function that i made addScore() and then increment it for every click that i do.

As for day one implementing java script with HTML DOM is one of key foundation that i have learned through this journey. Next day we would be focusing on making an interactive environment and making the snake class for our snake game

Day 2

At day 2 refresh my learning about math functions in java script i have used math Round and math.random this tow was actually useful in determining the spawn location of the food that we are going to be drawing later.

function randomFood(min,max){
	const randNum = Math.round((Math.random() * (max - min) + min) / unitSize) * unitSize;
 
	return randNum
}

I have also adjusted the html structure and used canvas so we can draw everything on the exact div that we are going to do.

<div id="gameContainer">
	<canvas id="gameBoard" width="500" height="500"></canvas>
	<div id="scoreText">0</div>
	<button id="reset">Reset</button>
</div>

this allows us to draw on the canvas by making our food and possibly rendering our snake too. now rendering the food i just use the fill style

const foodColor = "green"
const unitSize = 25;
 
function drawFood(){
    ctx.fillStyle = foodColor;
    ctx.fillRect(foodX, foodY, unitSize, unitSize);
}

this allows me to fill Style to create the food color that i set in the variable also used unit size to have a certain size of the blocks in the system and just call it so if i need to calculate it same with the random food can just call the variable and process it.

This day i was able to create the create food and draw food functions

// Creation of the Food Location
function createFood(){
    // Function to create the random food Location by using the max and min variable
    function randomFood(min,max){
        const randNum = Math.round((Math.random() * (max - min) + min) / unitSize) * unitSize;
        return randNum
    }
    // declaration of the randomFood function by using the gameWidth along wth unitSize
    foodX = randomFood(0, gameWidth - unitSize)
    foodY = randomFood(0, gameWidth - unitSize)
    console.log(foodX)
}
// Draw the food using the ctx fill style and rect
function drawFood(){
    ctx.fillStyle = foodColor;
    ctx.fillRect(foodX, foodY, unitSize, unitSize);
}

I was able to understand the language deeper with the math functions and their use cases refreshing the knowledge in basic java script with this game