Creating the Memory Game

Checking for winning state

Whenever a pair of faces has been matched, we need to check if the level has been completed. We'll do this with the checkState function. This will store an allCorrect boolean flag, which starts with the value true.

function checkState()
{
	var allCorrect = true;

We can now loop over all of the faces in the grid. If we come across one that does not have the currentState correct, then the game isn't finished. We change the value of allCorrect to false and break out of this loop.

	for(var g in grid)
	{
		if(grid[g].currentState!='correct')
		{
			allCorrect = false;
			break;
		}
	}

If the level is completed, and allCorrect is still true after checking all the faces on the grid, we start by changing the current screen to the won screen.

	if(allCorrect)
	{
		gameState.screen = 'won';

If the time taken is less than the current difficulties bestTime, or the bestTime is 0 (this difficulty hasn't yet been won this session), then we have a new best time. Update the bestTime property and set the gameState.newBest flag to true:

		if(difficulties[gameState.mode].bestTime==0 ||
			gameTime < difficulties[gameState.mode].bestTime)
		{
			difficulties[gameState.mode].bestTime = gameTime;
			gameState.newBest = true;
		}

Finally, set the finishedTime global to the current gameTime and leave this if block and function:

		finishedTime = gameTime;
	}
}
Page loaded in 0.011 second(s).