• Develop a memory card game using HTML5, CSS3 and JavaScript

    Published on April 10, 2012

    Adding a high scores table

    Well, T-Bob asked about this feature. I’ve spent some time on doing this and I have the feeling that the achieved result meets expectations.

    If you want to store any manipulated data you can do it using a database application or you can write data on a file. I’ve chosen the last method because it requires minimum intervention and configuration.

    The idea is to give to a player, after the game is finished, the possibility to save the number of clicks he/she made. So, after the last pair of cards disappear a form is created with two input fields, one for his/her name and the other for an email address. The restriction for this step is the maximum string length which can be typed in, and is 15 chars for the name and 35 chars for the email address. After clicking the “OK” button the data is passed to a PHP script which will save it in a XML structure file, and the high scores table displayed on game’s page will be updated. Only the first 20 records will be shown.

    Files matchgame.js, index.html and style.css were affected and new files and folders were added.

    Function startGame() has the following piece of code added:

    Briefly, what is new: the data stored in file highscores.xml is served using AJAX and stored in an array in a JSON manner. The first impulse was to store data in an array like:

    but, with this approach was difficult to sort data based on criteria, so I had to change the way data is stored in the array with:

    In this way, using associative arrays, data can be sorted for any valid criteria.

    Displaying data on high scores table is achieved with:

    So, if no score yet, display a message, otherwise show the first (ascending) 20 values stored. Internet Explorer v8 (and maybe previous versions) doesn’t know to stop iterations if number of items in array is lesser than the max number of iterations, and an error is thrown. Practically the code is doing the same thing, but I just wanted to be more strictly and to emphasize these two situations.

    19 comments to "Develop a memory card game using HTML5, CSS3 and JavaScript"

    Share your thoughts on this article.

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">