8 min read

 

(For more resources on this subject, see here.)

 

The following screenshot shows the final result we will create through this article. So, let’s get on with it:

HTML5 Games Development Using Local Storage

Storing data by using HTML5 local storage

Imagine now we have published our CSS3 memory matching game (Code Download-Ch:3) and players are trying their best to perform well in the game.

We want to show the players whether they played better or worse than the last time. We will save the latest score and inform players whether they are better or not this time by comparing the scores.

They may feel proud when performing better. This may make them addicted and they may keep trying to get higher scores.

Creating a game over dialog

Before actually saving anything in the local storage, we need a game over screen. Imagine now we are playing the CSS3 memory matching game that we built and we successfully match and remove all cards. Once we finish, a game over screen pops up and shows the time we utilized to complete the game.

Time for action – Creating a game over dialog with the elapsed played time

  1. Open the CSS3 matching game folder as our working directory.
  2. Download a background image from the following URL (we will use it as the background of the pop up):
    http://gamedesign.cc/html5games/popup_bg.jpg
  3. Place the image in the images folder.
  4. Open index.html into any text editor.
  5. We will need a font for the game over pop up. Add the following font embedding CSS into the head section:

    <link href="http://fonts.googleapis.com/css?family=Orbitron:400,
    700" rel="stylesheet" type="text/css" >

  6. Before the game section, we add a div named timer to show the elapsed playing time. In addition, we add a new popup section containing the HTML markup of the pop-up dialog:

    <div id="timer">
    Elapsed time: <span id="elapsed-time">00:00</span>
    </div>
    <section id="game">
    <div id="cards">
    <div class="card">
    <div class="face front"></div>
    <div class="face back"></div>
    </div> <!-- .card -->
    </div> <!-- #cards -->
    </section> <!-- #game -->
    <section id="popup" class="hide">
    <div id="popup-bg">
    </div>
    <div id="popup-box">
    <div id="popup-box-content">
    <h1>You Won!</h1>
    <p>Your Score:</p>
    <p><span class='score'>13</span></p>
    </div>
    </div>
    </section>

  7. We will now move on to the style sheet. As it is just for styling and not related to our logic yet, we can simply copy the matchgame.css file from matching_game_with_game_over in the code example bundle (Ch:3).
  8. It is time to edit the game logic part. Open the html5games.matchgame.js file in an editor.
  9. In the jQuery ready function, we need a variable to store the elapsed time of the game. Then, we create a timer to count the game every second as follows:

    $(function(){
    ...
    // reset the elapsed time to 0.
    matchingGame.elapsedTime = 0;

    // start the timer
    matchingGame.timer = setInterval(countTimer, 1000);
    }

  10. Next, add a countTimer function which will be executed every second. It displays the elapsed seconds in the minute and second format:

    function countTimer()
    {
    matchingGame.elapsedTime++;

    // calculate the minutes and seconds from elapsed time
    var minute = Math.floor(matchingGame.elapsedTime / 60);
    var second = matchingGame.elapsedTime % 60;

    // add padding 0 if minute and second is less then 10
    if (minute < 10) minute = "0" + minute;
    if (second < 10) second = "0" + second;

    // display the elapsed time
    $("#elapsed-time").html(minute+":"+second);
    }

  11. In the removeTookCards function which we wrote earlier, add the following highlighted code that executes the game over logic after removing all cards:

    function removeTookCards()
    {
    $(".card-removed").remove();

    // check if all cards are removed and show game over
    if ($(".card").length == 0)
    {
    gameover();
    }
    }

  12. At last, we create the following gameover function. It stops the counting timer, displays the elapsed time in the game over pop up, and finally shows the pop up:

    function gameover()
    {
    // stop the timer
    clearInterval(matchingGame.timer);

    // set the score in the game over popup
    $(".score").html($("#elapsed-time").html());
    // show the game over popup
    $("#popup").removeClass("hide");
    }

  13. Now, save all files and open the game in a browser. Try finishing the memory matching game and the game over screen will pop up, as shown in the following screenshot:

    HTML5 Games Development Using Local Storage

What just happened?

We have used the CSS3 transition animation to show the game over pop up. We benchmark the score by using the time a player utilized to finish the game.

Saving scores in the browser

Imagine now we are going to display how well the player played the last time. The game over screen includes the elapsed time as the last score alongside the current game score. Players can then see how well they do this time compared to last time.

Time for action – Saving the game score

  1. First, we need to add a few markups in the popup section to display the last score. Add the following HTML in the popup section in index.html:

    <p>
    <small>Last Score: <span class='last-score'>20</span>
    </small>
    </p>

  2. Then, we open the html5games.matchgame.js to modify some game logic in the gameover function.
  3. Add the following highlighted code in the gameover function. It loads the saved score from local storage and displays it as the score last time. Then, save the current score in the local storage:

    function gameover()
    {
    // stop the timer
    clearInterval(matchingGame.timer);

    // display the elapsed time in the game over popup
    $(".score").html($("#elapsed-time"));

    // load the saved last score from local storage
    var lastElapsedTime = localStorage.getItem
    ("last-elapsed-time");

    // convert the elapsed seconds into minute:second format
    // calculate the minutes and seconds from elapsed time
    var minute = Math.floor(lastElapsedTime / 60);
    var second = lastElapsedTime % 60;
    // add padding 0 if minute and second is less then 10
    if (minute < 10) minute = "0" + minute;
    if (second < 10) second = "0" + second;

    // display the last elapsed time in game over popup
    $(".last-score").html(minute+":"+second);

    // save the score into local storage
    localStorage.setItem
    ("last-elapsed-time", matchingGame.elapsedTime);

    // show the game over popup
    $("#popup").removeClass("hide");
    }

  4. It is now time to save all files and test the game in the browser. When you finish the game for the first time, the last score should be 00:00. Then, try to finish the game for the second time. The game over pop up will show the elapsed time you played the last time. The following screenshot shows the game over screen with the current and last score:

    HTML5 Games Development Using Local Storage

What just happened?

We just built a basic scoring system that compares a player’s score with his/her last score.

Storing and loading data with local storage

We can store data by using the setItem function from the localStorage object. The following table shows the usage of the function:

localStorage.setItem(key, value);

HTML5 Games Development Using Local Storage

In our example, we save the game elapsed time as the score with the following code by using the key last-elapsed-item:

localStorage.setItem("last-elapsed-time", matchingGame.
elapsedTime);

Complementary to setItem, we get the stored data by using the getItem function in the following way:

localStorage.getItem(key);

The function returns the stored value of the given key. It returns null when trying to get a non-existent key. This can be used to check whether we have stored any data for a specific key.

The local storage saves the string value

The local storage stores data in a key-value pair. The key and value are both strings. If we save numbers, Boolean, or any type other than string, then it will convert the value into a string while saving.

Usually, problems occur when we load a saved value from the local storage. The loaded value is a string regardless of the type we are saving. We need to explicitly parse the value into the correct type before using it.

For example, if we save a floating number into the local storage, we need to use the parseFloat function when loading it. The following code snippet shows how we can use parseFloat to retrieve a stored floating number:

var score = 13.234;

localStorage.setItem("game-score",score);
// result: stored "13.234".

var gameScore = localStorage.getItem("game-score");
// result: get "13.234" into gameScore;

gameScore = parseFloat(gameScore);
// result: 13.234 floating value

In the preceding code snippet, the manipulation may be incorrect if we forget to convert the gameScore from string to float. For instance, if we add the gameScore by 1 without the parseFloat function, the result will be 13.2341 instead of 14.234. So, be sure to convert the value from local storage to its correct type.

Size limitation of local storage
There is a size limitation on the data stored through localStorage for each domain. This size limitation may be slightly different in different browsers. Normally, the size limitation is 5 MB. If the limit is exceeded, then the browser throws a QUOTA_EXCEEDED_ERR exception when setting a key-value into localStorage.

Treating the local storage object as an associated array

Besides using the setItem and getItem functions, we can treat the localStorage object as an associated array and access the stored entries by using square brackets.

For instance, we can replace the following code with the latter version:

Using the setItem and getItem:

localStorage.setItem("last-elapsed-time", elapsedTime);
var lastElapsedTime = localStorage.getItem("last-elapsed-time");

Access localStorage as an array as follows:

localStorage["last-elapsed-time"] = elapsedTime;
var lastElapsedTime = localStorage["last-elapsed-time"];

LEAVE A REPLY

Please enter your comment!
Please enter your name here