Image 15-Puzzle mechanics

Main game loop

Our drawGame method will handle drawing to the Canvas, as well as updating the game where needed. First of all though, we'll perform a couple of checks. If the ctx global is null, we'll simply quit the function and the script will not be doing any further processing - this is to handle failed image loading.

We'll also check if all of the images have loaded. If not, we'll tell the browser to check back with us when it's ready for us to draw to the Canvas again, and then leave the function as there's nothing more we currently want to do in this case:

function drawGame()
	if(ctx==null) { return; }
	if(loadCount>0) { requestAnimationFrame(drawGame); return; }

Next we'll call the updateGame method to process any click events, and the set the fill colour to plain white and clear the whole Canvas by drawing a rectangle at 0, 0 (the top left of the Canvas) that has the same width and height as the Canvas element:

	ctx.fillStyle = "#ffffff";
	ctx.fillRect(0, 0, 400, 300);

We'll then loop over all of the imageTiles, and draw the corresponding section of the current image from the imgPos property of the Tile at its current position on the Canvas, canvasPos with the dimensions tileW, tileH:

	for(var i in imageTiles)
			imageTiles[i].imgPos[0] * tileW,
			imageTiles[i].imgPos[1] * tileH,
			tileW, tileH,
			imageTiles[i].canvasPos[0] * tileW,
			imageTiles[i].canvasPos[1] * tileH,
			tileW, tileH);

We'll then set the stroke colour to black, and stroke and fill some text in the top-left corner to show the number of moves currently taken to complete this puzzle:

	ctx.strokeStyle = "#000000";
	ctx.strokeText("Moves: " + movesTaken, 10, 20);
	ctx.fillText("Moves: " + movesTaken, 10, 20);

If there's also a current best score for this image, we'll show that also just below this text:

		ctx.strokeText("Best: " + imageBest[imageIndex], 10, 30);
		ctx.fillText("Best: " + imageBest[imageIndex], 10, 30);

Once this is done, we'll let the browser know to call this drawGame method again when it's ready for us to next update the Canvas, and close the function.

Page loaded in 0.113 second(s).