Creating the Memory Game

Drawing the menu

We'll handle drawing of each screen with its own method. For the drawMenu method, we begin by setting the font style and colour to that which will be used to draw the name of each difficulties entry.

function drawMenu()
{
	ctx.textAlign = 'center';
	ctx.font = "bold 20pt sans-serif";
	ctx.fillStyle = "#000000";

We'll also store the vertical offset at which we'll begin drawing the menu difficulties in the y variable, and then loop through all available difficulties:

	var y = 100;
	
	for(var d in difficulties)
	{

We now determine if the mouse cursor is currently roughly hovering over this entry, and set the mouseOver boolean accordingly. We use the state of this variable to choose the colour for the difficulties name property.

		var mouseOver = (mouseState.y>=(y-20) && mouseState.y<=(y+10));
		
		if(mouseOver) { ctx.fillStyle = "#000099"; }

The menuBox property is updated to be roughly the vertical start and end dimensions of the current difficulty, and the text is drawn. After, the y variable is incremented by 80 ready to draw the next entry, and if the colour was changed due to the mouse being over this area, it is now changed back and the loop is closed.

		difficulties[d].menuBox = [y-20, y+10];
		ctx.fillText(difficulties[d].name, 150, y);
		y+= 80;
		
		if(mouseOver) { ctx.fillStyle = "#000000"; }
	}

Next, we set the y back, but add a little to place these lines of text below each difficulty name. We then change the font to that we wish to use for the sub-text (showing the best time) for each difficulty, and begin looping over the difficulties again:

	var y = 120;
	ctx.font = "italic 12pt sans-serif";
	for(var d in difficulties)
	{

If the difficulty has no bestTime yet (the value is still 0), we show this:

		if(difficulties[d].bestTime==0)
		{
			ctx.fillText("No best time", 150, y);
		}

Otherwise, we draw the current best time, formatted for the number of minutes, and the seconds to 2 decimal places:

		else
		{
			var t = difficulties[d].bestTime;
			var bestTime = "";
			if((t/1000)>=60)
			{
				bestTime = Math.floor((t/1000)/60) + ":";
				t = t % (60000);
			}
			bestTime+= Math.floor(t/1000) +
				"." + (t%1000);
			ctx.fillText("Best time   " + bestTime, 150, y);
		}

We now move the y down by 80 again, and close both the loop and the function.

		y+= 80;
	}
}
Page loaded in 0.01 second(s).