Creating the Memory Game

Global objects and Settings

We'll also need some global objects. The first of these, gameState, we'll use to keep track of the current screen to display, the game difficulty mode, and a boolean flag that states whether or not we've achieved a new best score for the current difficulty.

var gameState = {
	screen	: 'menu',
	mode	: 'easy',
	newBest	: false

We also want to keep track of the mouseState; we'll record the x and y position of the cursor on the Canvas, and whether or not there has been a click on the Canvas that needs processing. If no mouse click has occured we'll just store null, otherwise we'll store an array with the [x, y] position of the event.

var mouseState = {
	x	: 0,
	y	: 0,
	click	: null


Our spriteSheet object stores information about the image we'll be taking our game sprites from. We'll store the src, which is the path to the image we'll be using for our sprites, the sprite width and height (spriteW, spriteH respectively) in pixels, and the number of cols and rows (columns and rows) our sprites cover on the image.

var spriteSheet = {
	src		: "sprites.png",
	spriteW		: 28,
	spriteH		: 28,
	cols		: 10,
	rows		: 6


Finally, we'll create a map of difficulties of game play. For each difficulty we'll specify the name of the difficulty level, the bestTime the player has achieved this session, in milliseconds (which will be 0 for each entry until they've actually played!), the width and height of the grid for each difficulty (this is the number of rows and columns that'll be filled with image pairs), and finally menuBox, which simply has the value [0, 0], as this will be calculated when the menu screen is drawn, and is the hitbox of the difficulty on the menu screen.

var difficulties = {
	easy	: {
		name		: "Easy",
		bestTime	: 0,
		width		: 4,
		height		: 4,
		menuBox		: [0,0]
	medium : {
		name		: "Medium",
		bestTime	: 0,
		width		: 6,
		height		: 6,
		menuBox		: [0,0]
	hard	: {
		name		: "Hard",
		bestTime	: 0,
		width		: 8,
		height		: 7,
		menuBox		: [0,0]

An important note here: besides the fact the product of width x height must be even, the product, divided by 2 ((width x height) / 2) must be less than or equal to the number of available sprites (spriteSheet.cols x spriteSheet.rows). Otherwise, we don't have enough images to occupy the whole grid and the game cannot work!

Page loaded in 0.01 second(s).