We encounter several games everyday, it takes lot of effort to maintain and develop these games as they involve heavy maintenance of JavaScript , HTML , CSS and logging each and every request provided by the server. In this, you’ll learn to develop a Dice rolling game, using JavaScript in just 9 minutes.

Yes, you’ve heard it right. It just takes 9 minutes of your time and blimey! you could develop a Game and yes, have fun with it. Prerequisites for this are few concepts bound with JavaScript, HTML and CSS. These three form the bedrock in building one such Game.

Let’s deep dive into it and get to know answers to all the basic questions like how to use the above mentioned languages, what’s the role of each one and how do they contribute in building this Game.

Why JavaScript?

An object-oriented computer programming language commonly used to create interactive effects within web browsers. It’s one of the robust language which is known for its simplicity, flexibility and several add-ons which can later be included if the user wishes to do so.

You can find the source code from here. And you can play the game here.

First Step, Write rules for the Game.

So, writing the rules will make game development a lot easier. Rules which should be initialized right in the beginning of the game. Rules are as follows:

The Game has 2 players, playing in round. In each turn, a player rolls a dice as many times as he wishes. Each result get added to his ROUND score. BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it’s the next player’s turn. The Player can choose to ‘HOLD’, which means that his ROUND score gets added to his GLOBAL score. After that, it’s the next player’s turn. The first player to reach 100 points on GLOBAL score wins the GAME.

What You will learn in Part-1.

How to create our fundamental game variables; How to generate a random number; How to manipulate the DOM (Document Object Model); How to read from the DOM; How to change CSS styles.

Now let’s start building this Game, are you excited?

So, first step is to make fundamental game variables. So, the variables will be scores(global score), roundScore, activePlayer and dice. Then we’ll take an array which will store the global score of the two players. Initially, this array and other variables will be set to 0.

var scores, roundScore, activePlayer, dice;

scores = [0,0]; roundScore = 0; activePlayer = 0; //Now, activePlayer could be either 0 or 1

Second step was to generate a RANDOM number. dice will be the random number which is achieved by rolling the dice. So, dice will be equal to..

dice = Math.floor(Math.random()*6)+1;

Third step is manipulation of DOM, now DOM is used to connect webpages to scripts like JavaScript. Now to connect both HTML and JS use “document.querySelector” to connect id or class of HTML to CSS.

document.querySelector(‘#current-’ + activePlayer).textContent = dice;

‘current’ is a id of current score, you can look it in the HTML code provided.

var x = document.querySelector(‘#score-0’).textContent; document.querySelector(‘.dice’).style.display = ‘none’;

We have set dice to ‘none’ to make sure that dice does not generate any random number before the start of the game and x is storing the Global Score of player 1.

EVENTS

Now, before moving to Part-2 we have to understand what are events. So, events are the notifications sent to notify the code that something happened on the webpage. It occurs while clicking a button, resizing a window, scrolling down or pressing a key. We can use Event Listeners to respond to these events.

Now, how events are processed can be seen in the picture below.

Events processing sequence.

What You will learn in Part-2.

How to setup an event handler; What a callback function is; What a anonymous function is; Another way to select elements by ID; how to change the image in an <img> element.

Now, coming back to first step we have to setup an event handler, that can be done by

document.querySelector('.btn-roll').addEventListener('click', function() {

// display the number var dice = Math.floor(Math.random()*6)+1;

//display the result. var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block' //block: The element displayed as a block-level element (like paragraphs and headers) diceDOM.src = 'dice-' + dice + '.png';

}) //click is the first arguement to eventlistener

Once again, i want to remind you here is that ‘btn-roll’ is a class which can be found in HTML code provided. function declared as argument of any function is known as anonymous function.If this function was declared outside this eventListener and then called inside eventListener that function would have been called as callback function. In 7th line we are displaying the image of dice by setting the display back to ‘block’ from ‘none’.

This is how your game should look at the end of this PART. What you will learn in Part-3. What the ternary operator is; How to add, remove and toggle HTML classes. document.querySelector('.btn-roll').addEventListener('click', function() { // display the number var dice = Math.floor(Math.random()*6)+1; //display the result. var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block' //block: The element displayed as a block-level element (like paragraphs and headers) diceDOM.src = 'dice-' + dice + '.png'; if(dice !== 1){ //Add the scores roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else{ //Next Player activePlayer === 0 ? activePlayer = 1 : activePlayer = 0; //ternary operator roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; } Now, what we have done here is we have added four lines of code in ‘else’ part. So, when dice becomes ‘1’ then current Scores of both the players will be set to ‘0’. And then we have used toggle operator to toggle the class player-0-panel and player-1-panel. Toggle adds the active command to the class which is not active and remove the active command from the class which is already active. This is the real beauty of JavaScript. What you will learn in Part-4. How to use functions to correctly apply the DRY principle. How to think about the game logic like a programmer. DRY Principle is the principle which means don't repeat yourself. var scores, roundScore, activePlayer; scores = [0,0]; roundScore = 0; activePlayer = 0; document.querySelector('.dice').style.display = 'none'; document.getElementById('score-0').textContent = '0'; //we could have used querySelector, but getElementById('id') is fast comparitively document.getElementById('score-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; // function btn() = { // // //do something here // // } document.querySelector('.btn-roll').addEventListener('click', function() { // display the number var dice = Math.floor(Math.random()*6)+1; //display the result. var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block' //block: The element displayed as a block-level element (like paragraphs and headers) diceDOM.src = 'dice-' + dice + '.png'; if(dice !== 1){ //Add the scores roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else{ //Next Player nextPlayer(); } }); //click is the first arguement to eventlistener document.querySelector('.btn-hold').addEventListener('click', function() { //Add current score to global score scores[activePlayer] += roundScore; //Update the UI document.querySelector('#score-'+ activePlayer).textContent = scores[activePlayer]; //Check if player won the game if(scores[activePlayer] >= 100){ document.querySelector('#name-'+ activePlayer).textContent = 'Winner'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+ activePlayer + '-panel').classList.add('winner'); document.querySelector('.player-'+ activePlayer + '-panel').classList.remove('active'); } else{ nextPlayer(); } //Next player }); function nextPlayer() { activePlayer === 0 ? activePlayer = 1 : activePlayer = 0; //ternary operator roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; } We have added another event which is for hold button. In that event we have added the current score to the global score. Then we have updated the UI. Then we are checking if any player has won or not. Then to avoid repeating the steps we have created a function ‘nextPlayer’ ,which satisfies the DRY principle. What you will learn in Part-5. Create event for ‘new button’. var scores, roundScore, activePlayer; init(); document.querySelector('.btn-roll').addEventListener('click', function() { // display the number var dice = Math.floor(Math.random()*6)+1; //display the result. var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block' //block: The element displayed as a block-level element (like paragraphs and headers) diceDOM.src = 'dice-' + dice + '.png'; if(dice !== 1){ //Add the scores roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else{ //Next Player nextPlayer(); } }); //click is the first arguement to eventlistener document.querySelector('.btn-hold').addEventListener('click', function() { //Add current score to global score scores[activePlayer] += roundScore; //Update the UI document.querySelector('#score-'+ activePlayer).textContent = scores[activePlayer]; //Check if player won the game if(scores[activePlayer] >= 100){ document.querySelector('#name-'+ activePlayer).textContent = 'Winner'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+ activePlayer + '-panel').classList.add('winner'); document.querySelector('.player-'+ activePlayer + '-panel').classList.remove('active'); } else{ nextPlayer(); } //Next player }); function nextPlayer() { activePlayer === 0 ? activePlayer = 1 : activePlayer = 0; //ternary operator roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; } document.querySelector('.btn-new').addEventListener('click', init); function init() { scores = [0,0]; activePlayer = 0; roundScore = 0; document.querySelector('.dice').style.display = 'none'; document.getElementById('score-0').textContent = '0'; document.getElementById('score-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.getElementById('name-0').textContent = 'Player 1'; document.getElementById('name-1').textContent = 'Player 2'; document.querySelector('.player-0-panel').classList.remove('winner'); document.querySelector('.player-1-panel').classList.remove('winner'); document.querySelector('.player-0-panel').classList.remove('active'); document.querySelector('.player-1-panel').classList.remove('active'); document.querySelector('.player-0-panel').classList.add('active'); } We have designed a init function in order to avoid repetition of code. In init function all the variables are set back to their default values. Now, here the problem is we can’t stop rolling the dice even after winning the game. So, in next Part we’ll solve that problem also. What you will learn in Part-6. What a state variable is and how to use it and why. So, what is a state variable. Its actually very simple, honestly speaking. A state variable simply tells us the condition of a system. We need state variable when we need to remember something or the state of something. In this section we are going to use a state variable by the name ‘gamePlaying’ .It will be set to ‘true’ if the game is not over and false if the winner is decided. So, the problem of rolling the dice after winning the game from Part-5 can be solved by just setting gamePlaying state variable to ‘false’. var scores, roundScore, activePlayer, gamePlaying; init(); document.querySelector('.btn-roll').addEventListener('click', function() { if(gamePlaying){ var dice = Math.floor(Math.random()*6)+1; //display the result. var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block' //block: The element displayed as a block-level element (like paragraphs and headers) diceDOM.src = 'dice-' + dice + '.png'; if(dice !== 1){ //Add the scores roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else{ //Next Player nextPlayer(); } } // display the number }); //click is the first arguement to eventlistener document.querySelector('.btn-hold').addEventListener('click', function() { if(gamePlaying){ //Add current score to global score scores[activePlayer] += roundScore; //Update the UI document.querySelector('#score-'+ activePlayer).textContent = scores[activePlayer]; //Check if player won the game if(scores[activePlayer] >= 100){ document.querySelector('#name-'+ activePlayer).textContent = 'Winner'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+ activePlayer + '-panel').classList.add('winner'); document.querySelector('.player-'+ activePlayer + '-panel').classList.remove('active'); gamePlaying=false; } else{ nextPlayer(); } //Next player } }); function nextPlayer() { activePlayer === 0 ? activePlayer = 1 : activePlayer = 0; //ternary operator roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; } document.querySelector('.btn-new').addEventListener('click', init); function init() { scores = [0,0]; activePlayer = 0; roundScore = 0; gamePlaying = true; document.querySelector('.dice').style.display = 'none'; document.getElementById('score-0').textContent = '0'; document.getElementById('score-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.getElementById('name-0').textContent = 'Player 1'; document.getElementById('name-1').textContent = 'Player 2'; document.querySelector('.player-0-panel').classList.remove('winner'); document.querySelector('.player-1-panel').classList.remove('winner'); document.querySelector('.player-0-panel').classList.remove('active'); document.querySelector('.player-1-panel').classList.remove('active'); So, our Game is complete and you can play this game with your friends and can tell them that you have coded this game. How cool is that! right.