Learn DOM by building a Roll the Dice game
Do not miss this exclusive book on Binary Tree Problems. Get it now for free.
In this article, we will introduce you to important DOM concepts by building roll the dice game. This article will be divided into five core sections so that you can follow along.
So as to fully understand how to code rolling the dice game, let us be familiar with the rule of the game.
- The game has 2 players, playing in rounds
- In each turn, a player rolls a dice as many times as he whishes. 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 50 points on GLOBAL score wins the game
We will, now, work on building our Dice game and learn DOM concepts along the way.
- Step 1 of this app: create a random number
- Step 2 of this app: create first click event
- Step 3 of this app: complement first click event
- Step 4 of this app: create second click event
- Step 5 of this app: create third click event
This is how our game will look like at the end:
First section
1.What we have done in the step: displaying the dice of activePlayer 1 rolling to use property context;
2.In the step with dom ideas and the flow chart which shows you a map to arrive the "destination"are listed below:
- getElementById the method will catch a unique ID of element and returns a object.
- querySelector the method is difference from the previous one. It starts form a hash tag , grab any element without a unique ID and returns an array.
- .testContent the property is to set/get content of the element we target.
- code below only Javascript:
3.1 we have four variables respectively:
var scores,roundScore,activePlayer,dice;
scores = [0,0];
roundScore = 0;
activePlayer = 0;
dice=0;
3.2 we use the method random and floor on Math object to get the dice socre.
dice = Math.floor(Math.random()*6)+1;
console.log("this is a dice number" + " "+ dice);
3.3 we use the method querySelector on document object to catch HTML elements that we are targeting - current 0(player-1)or current 1(player-2).
Becasue the varaible activePlayer is 0 and JavaScript type coercion,using the method to target element is current 0 .
Next, we use property textContent on document object to set player-1 current score equal to a rondom number which variable dice is.
document.querySelector('#current-'+ activePlayer).textContent=dice;
3.4 Agian, we use the same method and property on document object to save player-1 dice score in a variable X and console.log it to verify the result.
var x = document.querySelector('#current-0').textContent;
console.log("the player 0 score is " + " "x);
4.Please click The link to check out the full version of code:
5.the screenshot of first section:
Second section
1.What we have done in the section: displaying dice of activePlayer 0 rolling by dice pictures;
2.In the step ,We need to use getElementById to obtain each picture object and addEventListener to keep track of what happened after users cilcking the roll dice button.Lastly,flow chart listed below shows you more details after clicking the button.
3.Code below only Javascript:
3.1 we stated in first section;
var scores, roundScore, activePlayer;
scores = [0, 0];
roundScore = 0;
activePlayer = 0;
dice=0;
3.2
Global score of player-1 is called 'score-0'in HTML elements.Global score of player-2 is called 'score-1'in HTML elements.
You might ask where global scores are. You might see it in the first section screenshort. The number 43 is the default global score of player-1. The number 72 is the default global score of player-2.
we use the method getElementByID on docuemnt object to target four HTML elements and property textContent on document object to set two player's current score and global score =0.
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
3.3 As we talked before, please check out more details in the flow chart:
document.querySelector('.btn-roll').addEventListener('click', function () {
var dice = Math.floor(Math.random() * 6) + 1;
console.log(dice);
var img1 = document.getElementById('dice-1.png');
var img2 = document.getElementById('dice-2.png');
var img3 = document.getElementById('dice-3.png');
var img4 = document.getElementById('dice-4.png');
var img5 = document.getElementById('dice-5.png');
var img6 = document.getElementById('dice-6.png');
var imgArr = [img1,img2,img3,img4,img5,img6];
imgArr[0].style.display = "none";
imgArr[1].style.display = "none";
imgArr[2].style.display = "none";
imgArr[3].style.display = "none";
imgArr[4].style.display = "none";
imgArr[5].style.display = "none";
if(dice ==1 ){
imgArr[0].style.display = "block";
}
else if(dice == 2){
imgArr[1].style.display = "block";
}
else if(dice == 3){
imgArr[2].style.display = "block";
}
else if(dice == 4){
imgArr[3].style.display = "block";
}
else if(dice == 5){
imgArr[4].style.display = "block";
}
else {
imgArr[5].style.display = "block";
}
}
);
- Please click the linkThe link of full version of code:
Third section
1.what we have done in this section:switching the Player when dice of activePlayer rolling is equal to one;
2. In the step,before switching the activePlayer ,the process is as same as the second step.
The flow chart listed below shows you more details after swiching Player.
- code below only Javascript:
if(dice !== 1){
roundScore += dice;
document.querySelector("#current-" + activePlayer).textContent = roundScore;
}
else {
document.querySelector('.dice').style.display = 'none';
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
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');
}
- Please click the link link of full version of code:
Forth section:
1.what we have done in this section: checking which the activePlayer won the game when the total score of the activePlayer is equal or greater than 50 in second click event.
2.Before users clicking hold button, the process is as same as the step three.
After users clicking hold button, we need to use addEventListenerto keep track of what happened and please check out more details about after cilcking the button in the flow chart.
" Dry" principle The full name of "dry" is dont repeat yourself. As you can see from the flowchart, nextPlayer function was used by two evens function.
- code below only Javascript:
3.1 In the first click event, we use function nextPlayer to swtich the activePlayer.
document.querySelector('.btn-roll').addEventListener('click', function ()
{if(dice !== 1){}
else {nextPlayer();}
});
3.2 to complete the second click event:
document.querySelector('.btn-hold').addEventListener('click', function () {
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
if (scores[activePlayer] >= 50) {
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();
}
});
3.3 the function being called nextPlayer is used by "dry" principle;
function nextPlayer() {
document.querySelector('.dice').style.display = 'none';
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
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');
}
- Please click the linkThe link of full version of code:
Fifth section
1.what we have done in this section:Adding a state variable is in order to control when the game start/end off.
Before we starting the code, we need to understand what the state variable is and why we use it.
state varaible. It simply tell us the condition of a system.We need a state variable when we need to remember something or state something.
In the rolling dice game, the state varaible is called gamePlaying. When users want to re-start the game anytime, this is could happen as the state varaible we have.
Besides,you might have a question how the dice game start/end off?
A new button called New_Game will be created in this section.Again, we need to use addEventListener to trigger the event.
After users clicking the button we created in the section,
current score and global score of each player will be reset to 0.In addtion,it is like everything doesn't happen to remove all the css classList of each player and only to add css classList being called 'active' to the player 0.
- code below only Javascript:
// In this section,as you can see firstly we invoked the function called init(). After the user clicking the new-game button,addEventListener will call the function init agian.
var scores, roundScore, activePlayer, gamePlaying;
init();
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.querySelector('.btn-roll').addEventListener('click', function () {
if (gamePlaying) {
// 1. Random number
var dice = Math.floor(Math.random() * 6) + 1;
console.log(dice);
var img1 = document.getElementById('dice-1.png');
var img2 = document.getElementById('dice-2.png');
var img3 = document.getElementById('dice-3.png');
var img4 = document.getElementById('dice-4.png');
var img5 = document.getElementById('dice-5.png');
var img6 = document.getElementById('dice-6.png');
var imgArr = [img1, img2, img3, img4, img5, img6];
console.log(imgArr);
// 2. display results
if (dice == 1) {
imgArr[0].style.display = "block"
imgArr[1].style.display = "none"
imgArr[2].style.display = "none"
imgArr[3].style.display = "none"
imgArr[4].style.display = "none"
imgArr[5].style.display = "none"
} else if (dice == 2) {
imgArr[0].style.display = "none"
imgArr[1].style.display = "block"
imgArr[2].style.display = "none"
imgArr[3].style.display = "none"
imgArr[4].style.display = "none"
imgArr[5].style.display = "none"
} else if (dice == 3) {
imgArr[0].style.display = "none"
imgArr[1].style.display = "none"
imgArr[2].style.display = "block"
imgArr[3].style.display = "none"
imgArr[4].style.display = "none"
imgArr[5].style.display = "none"
} else if (dice == 4) {
imgArr[0].style.display = "none"
imgArr[1].style.display = "none"
imgArr[2].style.display = "none"
imgArr[3].style.display = "block"
imgArr[4].style.display = "none"
imgArr[5].style.display = "none"
} else if (dice == 5) {
imgArr[0].style.display = "none"
imgArr[1].style.display = "none"
imgArr[2].style.display = "none"
imgArr[3].style.display = "none"
imgArr[4].style.display = "block"
imgArr[5].style.display = "none"
} else {
imgArr[0].style.display = "none"
imgArr[1].style.display = "none"
imgArr[2].style.display = "none"
imgArr[3].style.display = "none"
imgArr[4].style.display = "none"
imgArr[5].style.display = "block"
}
if (dice !== 1) {
roundScore += dice;
document.querySelector("#current-" + activePlayer).textContent = roundScore;
} else {
// next player
document.querySelector('.dice').style.display = 'none';
nextPlayer();
}
}
}
);
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] >= 40) {
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();
}
}
});
function nextPlayer() {
document.querySelector('.dice').style.display = 'none';
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
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('.btn-new').addEventListener('click', init);
function init() {
gamePlaying = true;
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
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');
}
- Please click the link of full version of code:
4.the screenshot of fifth section:
Complete code on GitHub
With this article at OpenGenus, you must have the complete idea of building this game and get the idea of basic concepts of DOM as well. Enjoy.
Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.