Developing a Simple jQuery Game to Improve Your Memory

Share this article

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!

Frequently Asked Questions (FAQs) about Developing a Simple jQuery Game to Improve Your Memory

How can I add more cards to the memory game?

To add more cards to the memory game, you need to modify the JavaScript code. In the array that holds the card values, simply add more elements. Each element represents a card. Remember to add pairs of cards for the game to work correctly. Also, adjust the grid size in the CSS to accommodate the additional cards.

Can I use images instead of numbers for the cards?

Yes, you can use images instead of numbers. To do this, you need to modify the JavaScript code where the card values are defined. Instead of numbers, use the file paths of the images. Make sure the images are properly sized to fit the cards.

How can I add a timer to the game?

Adding a timer involves creating a function that increments a variable every second. You can use the setInterval method for this. Then, display this variable in your HTML. You can also add functionality to stop the timer when the game ends.

How can I make the game responsive for mobile devices?

To make the game responsive, you need to modify the CSS. Use media queries to adjust the layout and size of the elements based on the screen size. You might also need to adjust the JavaScript to handle touch events instead of click events.

How can I add a high score feature?

A high score feature involves storing the scores in a way that persists across different game sessions. You can use local storage for this. Create a function that checks if the current score is higher than the stored high score, and if it is, update the high score.

Can I use a different JavaScript library instead of jQuery?

Yes, you can use a different JavaScript library or even pure JavaScript. However, this might involve rewriting a significant part of the code. The principles of the game logic remain the same, but the syntax and methods might differ.

How can I add sound effects to the game?

To add sound effects, you can use the HTML5 audio API. You need to create an audio element for each sound effect, and then play these sounds at the appropriate times in your JavaScript code.

Can I add different difficulty levels to the game?

Yes, you can add different difficulty levels. This could involve changing the number of cards, the time limit, or other aspects of the game. You need to create a function that adjusts these variables based on the selected difficulty level.

How can I change the design of the cards?

The design of the cards is controlled by the CSS. You can change the colors, borders, fonts, and other properties. You can also add images or animations for a more engaging user experience.

How can I host the game on my own website?

To host the game on your own website, you need to upload the HTML, CSS, and JavaScript files to your web server. Make sure the file paths are correct. You can then link to the game from your website.

Rakhitha NimeshRakhitha Nimesh
View Author

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.

HTML5 GamingjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week