Guess The Die : Javascript Game

fidalmathew

Fidal Mathew

Posted on December 30, 2021

Guess The Die : Javascript Game

Hi guys, hope you are doing good. In this post, we are going to make a game using Javascript.
The game involves the following functionalities-

  • The user has to guess a number on the die 🎲 while it gets rolled in a span of 10 secs.
  • If the guess is right then the score will be incremented by one.
  • There is a 10 second wait/countdown between rolls during which we have to guess the number on the die.
  • When the user select his/her guess, the roll happens immediately and the result is displayed.
  • If the 10 seconds on the roll expires, it simply resets and there is no impact to the score.

Dice Load

Gameplay

First, let us look at the HTML structure.

Index.html

<!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 the Dice Game</title>

    <link rel="stylesheet" href="css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
</head>

<body>


    <div class="container">

        <h1>ROLL THE DICE</h1>
        <div class="info">
            <div>
                <div style="display: inline-block">Selected<br> variable:</div> <span id="SV">_</span>
            </div>
            <div class="image-dice">
                <img id="dice" src="img/load.gif" alt="">

            </div>

            <div>Score: <span id="CV">0</span></div>
        </div>

        <div class="number">

            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button>4</button>
            <button>5</button>
            <button>6</button>

        </div>

        <div id="report"> </div>

        <div id="h">Dice will change in <span id="timeS">0</span> seconds</div>

        <div id="result"></div>

    </div>


    <script src="index.js"></script>
</body>

</html>

Enter fullscreen mode Exit fullscreen mode

And here’s the index.js

Index.js

"use strict";

let score = 0;
let randomVar;

let buttonVal = document.getElementsByTagName("button");
let result = document.getElementById("result");
let report = document.getElementById("report");
let timeS = document.getElementById("timeS");
let dice = document.getElementById("dice");



const Clicked = (e) => {
    let selectVar = (e.target.innerText);

    dice.src = `img/${randomVar}.png`;        //To change the dice picture          

    document.getElementById("SV").innerHTML = selectVar;


    if (randomVar == selectVar) {
        result.style.color = "#1CE1BE";
        result.innerHTML = "Guess was right!";
        score++;
        document.getElementById("CV").innerHTML = score;

    }
    else {
        result.style.color = "#FF6D2E";
        result.innerHTML = "Guess was wrong!";
    }


    Array.from(buttonVal).forEach(element => {
        element.disabled = true;
        element.classList.toggle("disabled");
    });

}




const load = () => {
    report.innerHTML = "loading game will start in a few seconds!";
    document.getElementById('h').style.display = "none";
    document.getElementById('result').style.display = "none";

    Array.from(buttonVal).forEach(element => {

        element.addEventListener("click", Clicked); //added event click

        element.disabled = false;
        element.classList.add("disabled");

    });


    setTimeout(() => {
        document.getElementById('report').style.display = "none";
        document.getElementById('h').style.display = "block";
        document.getElementById('result').style.display = "block";


    }, 6000);

}



const DisplayTime = () => {
    let timesecond = 9;

    setInterval(() => {

        timeS.innerHTML = timesecond;
        timesecond--;
        if (timesecond == 0) {

            timesecond = 10;
        }


    }, 1000);


}


const addNewRandom = () => {

    setInterval(() => {
        randomVar = Math.floor(Math.random() * 6) + 1;

        dice.src = `img/load.gif`;
        dice.style.width = "37.5%";
        result.innerHTML = "";
    document.getElementById("SV").innerHTML = "_";


        Array.from(buttonVal).forEach(element => {

            element.disabled = false;
            element.classList.remove("disabled");

        });

    }, 10000);

}



window.onload = () => {

    load();
    DisplayTime();
    addNewRandom();
}





Enter fullscreen mode Exit fullscreen mode

Game Description

Before moving to Javascript part, do take a look at index.html and game UI. It will help you understand the game better.

Declaration

Declare all necessary variables in index.js

let score = 0;
let randomVar;  // to select a random value from 1 to 6 

let buttonVal = document.getElementsByTagName("button");
let result = document.getElementById("result");
let report = document.getElementById("report");
let timeS = document.getElementById("timeS");
let dice = document.getElementById("dice");
Enter fullscreen mode Exit fullscreen mode

The game mainly comprises 3 sections, we call these functions after the browser window loads

window.onload = () => {

    load();
    DisplayTime();
    addNewRandom();
}
Enter fullscreen mode Exit fullscreen mode

Load()

The load() function involves-

  • Setting up report element =" loading game will start in a few seconds!"
  • Setting display of id “h” and “result” as none.
  • Add event listener to all the buttons/numbers element.addEventListener("click", Clicked); and add class “disabled” which disables pointer events. ( I will tell you about Clicked() later on in the tutorial.)
.disabled{
    background-color: gray;
    pointer-events: none;
}

.disabled:hover{
    background-color: gray;
    color: white;

}
Enter fullscreen mode Exit fullscreen mode

Add a set timeout of 6 secs after which “report” is not displayed
meanwhile “h” & “result” are displayed

DisplayTime()

DisplayTime() function is used to-

  • Display time, which is denoted by
    timeS.innerHTML = timesecond;

  • Timesecond value is updated each sec using setInterval()

addNewRandom()

addNewRandom() function consists of a set interval of 10 secs.

  • It sets a new random value to randomVal between 1 and 6.
    randomVar = Math.floor(Math.random() * 6) + 1;

  • After updating randomVar, we remove class "disabled" from each of the keys/buttons.

Clicked()

Last but not least, let’s look at Clicked() function.
It's functionalites include -

  • Set the picture of die depending on randomVar.

  • Compare the selected button and randomVar and
    display the result and score accordingly.

Source Code : https://github.com/FidalMathew/ROLL-THE-DICE
Note: Some additional features have been added to the game

Thank you all for reading, have a great day :)

Connect with me on -

💖 💪 🙅 🚩
fidalmathew
Fidal Mathew

Posted on December 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related