JavaScript Snakes and Ladders game Tutorial

JavaScript Snakes and Ladders game Tutorial

The best way to learn any programming language is through hands-on projects. The Snakes and Ladders is a game that you can make using the basics of JavaScript and HTML.

Snakes and ladders is an ancient Indian board game for two or more players regarded today as a worldwide classic. It is played on a game board with numbered, gridded squares. A number of "ladders" and "snakes" are pictured on the board, each connecting two specific board squares. The basic goal of the game is to navigate one's game piece, according to die rolls from the start (bottom square) to the finish (top square), helped by climbing ladders but hindered by falling snakes.

Today I'll show you how to create Snakes and Ladders game step-by-step. To succeed in this tutorial, you should have a basic understanding of JavaScript and HTML.

We'll go through the following steps today:

  1. Create the HTML page

  2. Create a 6*6 board with numbers on it.

  3. Add Snakes & Ladders

  4. Generate dice value.

  5. Change the current player's position based on dice value.

Step 1: Create the HTML page

First, we need to create an index.html page which will contain 2 divs:

  1. First div will contain game board which has the CSS class as "main-board".
  2. Second div will contain Dice and its respective side's images. These images will be saved in assets folder. There will be a button which will help in rolling the dice.

The <body> also contains an onload() which will be responsible to create the matrix and display it as the board. onload() will be fired as soon as the body loads.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Roll Dice</title>
    <link rel="stylesheet" href="style.css">
</head>
<body onload="createBoard()">
    <div class="container">
        <div class="main-board"></div>  
        <div class="dice-container">
            <img src="assets/dice1.png" id="dice-id"/>
            <button onclick="roll()">Roll Dice</button>
        </div>
    </div>
    <script src="main.js"></script>
</body>
</html>

Step2: Create the matrix and display it as a numbered board

After writing the HTML part, let's now focus on the good JS part which will help bring life to our game. We'll divide this section 3 parts

Create a Matrix

For this tutorial, I'm creating a 6x6 matrix.

A variable matrixArray is required as it will save the dynamically created array at the run time. Also, the snakes and ladders are required, I've saved snakes and ladders position in an object. It is a one-one mapping.

In the case of snakes, the key represents the head of snakes and the value represents the tail of snakes. Similarly, in the case of ladders, the key represents starting of ladders and the value represents the ending of ladders.

const n = 6;
const matrixArray = [];

const ladderMap = {
    3: 11,
    5: 23,
    7:15,
    21:33,
    26:31
}

const snakeMap = {
    13: 6,
    9: 4,
    19: 2,
    34: 22,
    29: 16
}

Function: createMatrix()

It will run as soon as the page loads. The main goal of this function is to create a n*n 2-D matrix with their block values. Matrix will be created in descending order, so if the column's value is odd that row will contain the value in descending order otherwise the value of the row will be in ascending order.

For example: 4*4 Matrix will be:
[[ 16 15 14 13]
[9 10 11 12]
[8 7 6 5]
[1 2 3 4]]

function createMatrix(n){
    let block = (n * n) + 1;
    for(let column=1;column<=n;column++){
        let rows = [];
            if (column % 2 === 0){
                block = block - n;
                let value = block;
                for(let row=1;row<=n;row++){
                    rows.push(value);
                    value++
                }
            }else{
                for(let row=1;row<=n;row++){
                block = block - 1;
                rows.push(block);
                }
            }
        matrixArray.push(rows)
    }
    return matrixArray;
}

Function createBoard()

This function helps in inserting the matrix array in main-board div row-wise. It selects the main-board div using document.querySelector() first. Then iterates on the matrixArray and creates a string that contains a div. Inside that, it iterates every row, and add the block value. Also, an active CSS class will be added to block number 1 because this is the starting point.

function createBoard(){
    const matrixArray = createMatrix(n);
    const board = document.querySelector('.main-board')
    let str = "";
    matrixArray.map(row => {
        str += `
            <div class="row">`
        row.map(block => {
            str += `
                    <div 
                      class="block ${block === 1 ? 'active' : ''} " data-value=${block}>
                      ${block}
                    </div>
                `
            })   
        str += `</div>`
    })
    board.innerHTML = str;
}

Step 3: Add Snakes and Ladders

We will conditionally check if the block value is equal to the snake's or ladder's object key then a snake/ladder image is inserted.

function createBoard(){
    const matrixArray = createMatrix(n);
    const board = document.querySelector('.main-board')
    let str = "";
    matrixArray.map(row => {
        str += `
            <div class="row">`
        row.map(block => {
            str += `
                    <div 
    class="block ${ladderMap[block] ? LADDER_CLASS : ''} ${snakeMap[block] ? SNAKE_CLASS : ''} ${block === 1 ? 'active' : ''} " data-value=${block}>
                      ${block}
                    </div>
                `
            })   
        str += `</div>`
    })
    board.innerHTML = str;
}

Step 4: Generate dice value

After displaying the board on the screen, let us focus on generating a random value between 1 to 6. Dice image will change basis on the dice value. This will be handled by a roll().

Function: roll()

This function will be called when the Roll Dice button will be clicked. This function will first add a shake CSS class which will make dice shake.

Then after a second, the same class will be removed and a random number will be generated using Math.random(). It will change the dice-image src using string interpolation.

function roll(){
    const dice = document.querySelector("img");
    dice.classList.add("shake");
    setTimeout(() => {
        dice.classList.remove("shake");
        const diceValue = Math.ceil(Math.random()* 6);
        document.querySelector("#dice-id").setAttribute("src", `assets/dice${diceValue}.png`);   
        changeCurrentPosition(diceValue);
    }, 1000); 
}

Step 5: Change the current player's position based on dice value

Roll function will call changeCurrentPosition() which accepts dice value as an argument.

This function selects the block which contains the active CSS class, parse its value to get the player's current position. The function then adds dice value to the player's current position and toggle the active class.

If the resultant block number contains a snake, then the resultant block number will change to the respective value of that snake's key-value pair. The same is the case with the ladder.

function changeCurrentPosition(diceValue){
    const activeBlock = document.querySelector('.active');
    const activeBlockValue = parseInt(activeBlock.outerText);
    let presentValue = diceValue + activeBlockValue;
    if (snakeMap[presentValue]){
        alert(`Oppsss! You're at ${presentValue} & a snake has bitten you go back to ${snakeMap[presentValue]}`)
        presentValue = snakeMap[presentValue];
        changeActiveClass(presentValue);
    }
    if (ladderMap[presentValue]){
        alert(`Yayyy! You're at ${presentValue},you got a ladder go to ${ladderMap[presentValue]}`)
        presentValue = ladderMap[presentValue];
        changeActiveClass(presentValue);
    }
    if (presentValue <= (n*n)){
        changeActiveClass(presentValue);
    }
}
function changeActiveClass(presentValue){
    const activeBlock = document.querySelector('.active');
    activeBlock.classList.remove('active');
    const block = document.querySelector(`[data-value = "${presentValue}"]`);
    block.classList.add('active');
}

There you go!

We’ve learned how to use JavaScript and HTML to create a functioning, interactive game. How cool! I hope you enjoyed creating a simple project.

Thanks for reading, you can follow me on twitter if you like this article.