Developing a Simple jQuery Game to Improve Your Memory

This tutorial will show you how to create a simple game using jQuery and HTML. The resulting game is intended to help you improve your memory skills. We will have an 8×6 grid of squares as the game window. Once you start the game, images of birds will appear in six of the squares, disappearing after a few seconds. Your goal is to remember the positions of the displayed images and click those squares.

Once you click six squares you will be given points according to your accuracy, and birds will be displayed again at random positions. This process will continue until the allocated time expires. You will get one point for each accurate click, and a bonus of 100 points if you click all six birds correctly. Having now identified the rules of the game, we can move onto creating the start screen.

Designing the Screen Layout

First, the HTML file for the game is shown below. All of the game’s statistics are placed inside the game_results element. You can see Time Left, Score, and Clicks Left for a single level in this area. All of the windows related to gameplay are placed inside the game_window element. This includes the initial start screen, which is contained in the start_window element. Once the game is started, the start screen is hidden, and the game is played in the play_window element. Finally, the results are displayed in the end_window element. You can find the necessary CSS code inside the styles section.

<html>
<head>
  <title>Simple jQuery Memory Game</title>
  <script src='jquery-latest.js'></script>
</head>
<body>
  <div id="game_results">
    <ul>
      <li>
        <div class="field_label">Time Left</div>
        <div class="field_value">
          <div id="timer">40</div>
        </div>
      </li>
      <li>
        <div class="field_label">Your Score</div>
        <div class="field_value">
          <div id="score">0</div>
        </div>
      </li>
      <li>
        <div class="field_label">Clicks Left</div>
        <div class="field_value">
          <div id="clicks"></div>
        </div>
      </li>
      <li>
        <div id="bonus" class="bonus">100 Bonus</div>
      </li>
    </ul>
  </div>
  <div id='game_window'>
    <div id='start_window'>
      <div id='msg_game'>jQuery Memory Checker Game</div>
      <div id='start_game'>Start</div>
    </div>
    <div id='end_window'>
      <div id='complete_game'></div>
    </div>
    <div id='play_window'></div>
  </div>
</body>
</html>

Creating the Game Window

First, we have to create the elements for the game window before moving into any of the functionality. As mentioned earlier, play_window will be used for the game. Inside this section we have to create 48 squares on eight columns and six rows. The code for a few of the squares is shown below.

<div id="game_0_0" data-x="0" data-y="0" class="game_box"></div>
<div id="game_0_1" data-x="0" data-y="1" class="game_box"></div>
<div id="game_0_2" data-x="0" data-y="2" class="game_box"></div>
<div id="game_0_3" data-x="0" data-y="3" class="game_box"></div>
<div id="game_0_4" data-x="0" data-y="4" class="game_box"></div>
<div id="game_0_5" data-x="0" data-y="5" class="game_box"></div>
<div id="game_0_6" data-x="0" data-y="6" class="game_box"></div>
<div id="game_0_7" data-x="0" data-y="7" class="game_box"></div>

The above code represents the first row of the playing window. I have used a naming convention for the iddata-x, and data-y attributes which will come handy in later sections. Now that we have the play window designed, let’s move on to creating functions for starting the game.

Starting the Game

Once we click on the Start button, all other windows need to be closed so that the game window can be displayed. Consider the code below.

var game_interval;
var activeBirds = [];
var activeCount = 0;
var activeStatus = 1;

$("#start_game").click(function(){
  game_interval = setInterval(updateTimer,1000);
  $("#play_window").show();
  $("#start_window").hide();
  displayBirds();
});

The first four lines define global variables. game_interval will hold the value returned by setInterval(), while activeBirds is an array that will hold the positions of birds in the current level. activeCount is the number of clicks made inside a single level, and activeStatus is used to check the status for clicking. Inside the click handler function for the Start button, we call the updateTimer() function in one second intervals to update the time left to play. The code for the updateTimer() function is shown below.

function updateTimer(){
  var time_remaining = parseInt($("#timer").html());
  if(time_remaining == 0){
    window.clearInterval(game_interval);
    $("#play_window").hide();
    $("#start_window").hide();
    $("#end_window").show();
    $("#complete_game").html("You Have Scored "+$("#score").html());
  }else{
    $("#timer").html(--time_remaining);
  }
}

The function shown above will reduce the time count every second. When the time left becomes zero it stops the timer by calling the JavaScript clearInterval() function. Then, the playing window is hidden, and the results window is displayed. Now let’s move to the rest of start function.

$("#start_game").click(function(){
  game_interval = setInterval(updateTimer,1000);
  $("#play_window").show();
  $("#start_window").hide();
  displayBirds();
});

Next, we need to hide the start window and display the playing window. Finally, we call the displayBirds() function to display the birds and start the game. The displayBirds() function is discussed in the following section.

Displaying Birds to Click

Once the game is started birds will be displayed at six random positions in each level. Lets consider the following displayBirds()function. The function loops until the appropriate number of birds have been added to the activeBirds array. Inside the loop, random X and Y values are generated to pick the row and column numbers. Then, we check whether the generated position is already occupied by a bird. If the position is available, we take it. The image of the bird is then added to the generated position.

function displayBirds(){
  while (activeBirds.length < 6){
    var random_X = Math.floor(Math.random()*6);
    var random_Y = Math.floor(Math.random()*8);
    var array_index = $.inArray(random_X+""+random_Y, activeBirds);
    if(array_index == -1){
      activeBirds.push(random_X+""+random_Y);
    }
    $("#game_"+random_X+"_"+random_Y).html("<img src='bird.png' class='game_bird' />");
    level_interval = setTimeout(function(){
      $(".game_bird").remove();
      activeStatus = 1;
    },2000);
  }
}

Finally, setTimeout() is used to call an anonymous function which hides the birds. Birds will appear, and then disappear after two seconds. The user has to remember the places where the birds were shown and start clicking to get points. The next section focuses on handling the user’s clicks and keeping score.

Capturing User Clicks and Generating Points

The user scores points by clicking on the squares that previously displayed birds. We also have to generate the birds for next level once user completes clicking for the current level. The code to handle click events is shown below.

$(".game_box").click(function(){
  if(activeStatus == 1){
    // Section 1
    activeCount++;
    $("#clicks").html(6-activeCount);
    var clicked_x = $(this).attr("data-x");
    var clicked_y = $(this).attr("data-y");
    var clicked_box = clicked_x+""+clicked_y;
    // Section 2
    var array_index = $.inArray(clicked_box, activeBirds);
    if(array_index != -1){
      activeBirds.splice(array_index,1);
    }
    // Section 3
    if(activeCount == 6){
      var score = parseInt($("#score").html());
      score = score + (6-activeBirds.length);
      if(activeBirds.length == 0){
        score = score + 100;
        $("#bonus").slideDown("slow");
        $("#bonus").slideUp("slow");
      }
      $("#score").html(score);
      //Reset Variables
      activeCount = 0;
      activeBirds = [];
      displayBirds();
    }else{
      return;
    }
  }
});

First, I have assigned a function for the click event of each square by using the game_box class selector. The variable, activeCount, holds the number of user clicks in each level. We are going to increase it each time the user clicks on a square. Then, we display the remaining clicks by subtracting activeCount from six. For each click, we also get the square’s X and Y values using the data-x and data-y attributes.

Next, we check whether the clicked box is in the activeBirds array using jQuery’s inArray() function. On each correct guess, the user gets one point and the element is removed from activeBirds. Once the user is out of clicks, we calculate the score using the remaining entries in the activeBirds array. If all of the birds have been matched, the user is given 100 bonus points. When all of the birds are matched, we display a bonus tag which is hidden by default in the top section using jQuery’s slideDown() and slideUp() functions. Finally, we reset all the variables and call displayBirds() to show birds for the next level.

Conclusion

In this tutorial, we have created a simple jQuery game to improve your memory. If you get bored with our very simple game, you can try adding some of the following features.

  • Add different types of birds with different point values instead of same number of points for all the birds.
  • Increase the number of birds displayed for each level as user gets deep into the game.
  • Provide additional time for completing goals such as 500 or 1,000 points.

I hope you try out these features. Let me know about new features which might improve the game using the comments section. Enjoy!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://www.audero.it/ Aurelio De Rosa

    Is there a repository where I can download the full source?

  • Mixa_ru

    Any DEMO please?

  • Aniket Chaubey

    Hello,
    Thanks For The Post
    I am a beginner for HTML with jQuery so i really enjoyed read this.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello Aniket

      Thanks for your interest.

      As a beginner were you able to understand how this tutorial was written? If not let me know the ares I need to improve in order to make things simple for the readers.

      Also let me know what you would like to see from jspro in the future?