Skip to main content

Building your first Game using JavaScript in 9 minutes

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:
  1. The Game has 2 players, playing in round.
  2. In each turn, a player rolls a dice as many times as he wishes. Each result get added to his ROUND score.
  3. BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it’s the next player’s turn.
  4. 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.
  5. The first player to reach 100 points on GLOBAL score wins the GAME.

What You will learn in Part-1.

  1. How to create our fundamental game variables;
  2. How to generate a random number;
  3. How to manipulate the DOM (Document Object Model);
  4. How to read from the DOM;
  5. 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.

  1. How to setup an event handler;
  2. What a callback function is;
  3. What a anonymous function is;
  4. Another way to select elements by ID;
  5. 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.

  1. What the ternary operator is;
  2. 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.

  1. How to use functions to correctly apply the DRY principle.
  2. 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.

  1. 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.

  1. 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.

Hey, I’ll be back with more fun elements in JavaScript . Meanwhile, you can check out my Hotel Price comparison API. This API compares more than 200 hotel booking websites and provide JSON data with top three vendors and lot more. Thank you all for your support. Have a productive day.

Comments

  1. Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on
    updating...

    indiaunimagined
    Guest posting sites

    ReplyDelete
  2. This is an awesome post. Really very informative and creative contents.
    WordPress website development Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

This Is Exactly How You Should Train Yourself To Be Smarter [Infographic]

Design inspired by the Cognitive Bias Codex
View the high resolution version of the infographic by clicking here. Out of all the interventions we can do to make smarter decisions in our life and career, mastering the most useful and universal mental models is arguably the most important. Over the last few months, I’ve written about how many of the most successful self-made billionaire entrepreneurs like Ray Dalio, Elon Musk, and Charlie Munger swear by mental models… “Developing the habit of mastering the multiple models which underlie reality is the best thing you can do. “ — Charlie Munger “Those who understand more of them and understand them well [principles / mental models] know how to interact with the world more effectively than those who know fewer of them or know them less well. “ — Ray Dalio “It is important to view knowledge as sort of a semantic tree — make sure you understand the fundamental principles, i.e. the trunk and big branches, before you get into the leav…

Warren Buffett: “Really Successful People Say No To Almost Everything”

When I tell people that Warren Buffett follows the 5-Hour Rule and spends 80% of his time reading and thinking, they have an immediate and predictable reaction: “Well, he can do that because he’s Warren Buffett, one of the richest people in the world. I could never do that.” While this response may help people feel better about themselves, it certainly won’t make them smarter. Because the reality is: Buffett has spent most of his time reading and thinking since he was in grade school. Having more money or managing a large company doesn’t magically give you free time. Having free time is never the default. People don’t just fall into huge blocks of free time unless they retire. Rather, free time is the result of strategy. It’s the result of looking at time differently. Curious about Buffett’s unique strategies, I’ve read several books about him, read most of his annual letters to stockholders, and watched nearly all of his interviews. And make no mistake about it… behind Buffett’s jovia…

If you want to be massively successful, do NOT set ambitious goals, according to studies

The conventional model to having great success in your career is setting and ardently pursuing big, hairy, audacious goals (BHAGs), even if you have no idea how you’re going to achieve them when you start. Want to build a billion dollar company? Set the goal and work backward from long-term goals to medium-term goals to short-term goals to today’s to-do list. Then take action, measure your progress along the way, and constantly course correct so you’re always on the most direct path (that you’re aware of) toward your ultimate goal. Want to cure cancer? Set the goal and work backward. Measure your progress. Want to find the love of your life or be happy? Set the goal. Rinse and repeat. This goals model is so obvious in our culture, it goes without saying. It’s central to our collective success recipe. Goals give motivation, meaning, and focus when we feel lazy or distracted — at least so we’re told. However, recent research from the field of artificial intelligence is putting a nail in t…