Creating the Memory Game

Global variables

We'll assume you have a reasonable understanding of Javascript / OOP for this tutorial!

Now, in our Javascript file we'll create (memory-game.js), we'll start by creating some global variables to provide references and keep track of the game state. First off, drawing context and sprites:

var ctx = null;

var sprites = null, spritesLoaded = false;

Our ctx variable will store a reference to the 2D drawing context of our Canvas element, sprites will store the image which contains our game sprites, and spritesLoaded is a boolean flag that states whether or not our sprite image has been loaded yet.

var gameTime = 0, lastFrameTime = 0;
var currentSecond = 0, frameCount = 0, framesLastSecond = 0;

gameTime is the time that has currently elapsed (from the time a new game is started) in milliseconds, and lastFrameTime is the time, in milliseconds, the games draw function was last called.

The other variables, currentSecond, frameCount and framesLastSecond are for keeping track of the games frame rate for information and debugging.

Our other time related variable, finishedTime, is the time (in milliseconds) it took to complete the last completed game:

var finishedTime = 0;

We also want a couple of positioning variables, offsetX and offsetY - we'll use these to store where we've calculated the grid should be drawn on the Canvas, calculated dynamically at the start of each game based on the grid dimensions, the image dimensions, and the Canvas width/height:

var offsetX = 0;
var offsetY = 100;

Now for our grid related globals:

var grid = [];
var visibleFace = null;
var activeFaces = [];

grid is the actual array that will store all of the faces we'll be using as our images for this game, and their current state (visible, invisible, etc). visibleFace is the current face that has been selected by the player, but that they have not yet selected another face to match it to. In our pseudocode example on the first page of this article, it is the [previous image] variable.

Finally, activeFaces stores any of the faces on the grid which are in some way animated; in our code, this will store faces that are waiting for a short timeout before being hidden, after the Player has tried to match them to a none matching partner.

Page loaded in 0.011 second(s).