Creating the Memory Game

Memory game mechanics

Do you remember the Memory game? It's a simple game that is easy with small grid sizes, but increases substantially in difficulty with larger grids. If your short term memory is anything like mine, it becomes a click fest as opposed to any feat of skill... but let's remind ourselves of how the game works:

  1. A grid of hidden squares is laid out. The grid is filled with randomly placed (currently hidden) images, each of which has a matching partner elsewhere on the board.
  2. The player selects a place on the grid, and the image is made visible.
  3. The player selects another place on the grid, and if the images match both are left permanently revealed. If not, after a short delay both are hidden again.
  4. Steps 2 & 3 are repeated until the whole grid is uncovered. Scoring is done by time taken or number of failed attempts to match a pair.
Memory Game example

Really simple, right? Let's look at how our pseudocode will make this work. We begin by creating our grid:

[grid] = Grid of tiles size = (width x height)

while([grid] is not full):
	insert [image] into random free place in [grid]
	insert [matching image] into random free place in [grid]
	set [image], [matching image] to hidden

The product of width x height must be even! 7x7 will not work - 6x7 is fine!

Next, we'll do a bit of processing for the game loop itself:

[previous image] = nothing

while(all [images] in [grid] are not visible):

	if([click] on [hidden image]]):
		make [hidden image] visible
		
		if([previous image] == nothing):
			[previous image] = [hidden image]
			
		else if([previous image] matches [hidden image]):
			mark [previous image], [hidden image] visible
			
		else:
			(short delay): hide [previous image], [hidden image]
			[previous image] = nothing

There's a bit more to it than that, but this should give you a good idea. Continue on to see how we'll build this game in Javascript...

Page loaded in 0.014 second(s).