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

Popular posts from this blog

Cheat Sheets for AI, Neural Networks, Machine Learning, Deep Learning & Big Data

Over the past few months, I have been collecting AI cheat sheets. From time to time I share them with friends and colleagues and recently I have been getting asked a lot, so I decided to organize and share the entire collection. To make things more interesting and give context, I added descriptions and/or excerpts for each major topic. This is the most complete list and the Big-O is at the very end, enjoy… If you like this list, you can let me know here Neural Networks

Neural Networks Cheat Sheet Neural Networks Graphs

Neural Networks Graphs Cheat Sheet



Neural Network Cheat Sheet Ultimate Guide to Leveraging NLP & Machine Learning for your Chatbot
Code Snippets and Github Includedchatbotslife.com
Machine Learning Overview

Machine Learning Cheat Sheet
Machine Learning: Scikit-learn algorithm This machine learning cheat sheet will help you find the right estimator for the job which is the most difficult part. The flowchart will help you check the documentation and rough guide of …

A Tour of The Top 10 Algorithms for Machine Learning Newbies

In machine learning, there’s something called the “No Free Lunch” theorem. In a nutshell, it states that no one algorithm works best for every problem, and it’s especially relevant for supervised learning (i.e. predictive modeling). For example, you can’t say that neural networks are always better than decision trees or vice-versa. There are many factors at play, such as the size and structure of your dataset. As a result, you should try many different algorithms for your problem, while using a hold-out “test set” of data to evaluate performance and select the winner. Of course, the algorithms you try must be appropriate for your problem, which is where picking the right machine learning task comes in. As an analogy, if you need to clean your house, you might use a vacuum, a broom, or a mop, but you wouldn’t bust out a shovel and start digging.
 "Try our Hotel price comparison API to compare more than 200 hotel websites." And if you love this post don't forge…

The Difference Between Artificial Intelligence, Machine Learning, and Deep Learning

Simple explanations of Artificial Intelligence, Machine Learning, and Deep Learning and how they’re all different. Plus, how AI and IoT are inextricably connected. We’re all familiar with the term “Artificial Intelligence.” After all, it’s been a popular focus in movies such as The Terminator, The Matrix, and Ex Machina (a personal favorite of mine). But you may have recently been hearing about other terms like “Machine Learning” and “Deep Learning,” sometimes used interchangeably with artificial intelligence. As a result, the difference between artificial intelligence, machine learning, and deep learning can be very unclear. I’ll begin by giving a quick explanation of what Artificial Intelligence (AI), Machine Learning (ML), and Deep Learning (DL) actually mean and how they’re different. Then, I’ll share how AI and the Internet of Things are inextricably intertwined, with several technological advances all converging at once to set the foundation for an AI and IoT exp…