Image 15-Puzzle mechanics

Globals, mouse, and tile object

We'll start by creating some global variables. These will be used throughout the script. The first of these will be ctx which will provide a reference to the Canvas elements 2D drawing context, and tileW, tileH, which will specify the width and height of each tile the images are divided into in pixels. These Canvas dimensions should be divisible by these values with no remainder.

var ctx = null;
var tileW = 125, tileH = 100;

We also need some globals to keep track of the images we'll be using for these puzzles:

var imageURLs	= ["img1.jpg", "img2.jpg", "img3.jpg"];
var images	= [];
var imageTiles	= [];
var imageBest	= [];
var imageIndex	= 0;

The first of these, imageURLs is an array of paths or absolute URLs of the images our game will use. We can use as many as we want - once the player completes one puzzle they'll be moved to the next. Images should have the same dimensions as the Canvas element.

The second variable, images, is an array of the Image objects as we begin loading them from the specified URLs. imageTiles will be an array of Tile objects (we'll create this class later) that make up the current image puzzle, and imageBest is an array of the best completion scores (the lowest number of moves) to complete each image puzzle.

Additionally, imageIndex is the array index of the image the player is currently puzzling over - we'll start at 0, the first image in the list.

Our other globals are as follows:

var freePos	= [0,0];
var loadCount	= imageURLs.length;
var movesTaken	= 0;

Where freePos is the x, y grid position where the "hole" or missing image tile is (to allow moving around tiles), loadCount is the number of images we need to load before the game can begin (to start with, this is all the images, so we just use the length of the imageURLs array), and movesTaken is the number of moves taken so far to solve the current puzzle.

Mouse status

We'll be using mouse clicks to move puzzle segments, so we'll keep track of the with an object called mouseState:

var mouseState = {
	click	: null

The click property records the position of the last mouse click event on the Canvas in the form of an array ([x, y]), or null if no new click event needs to be processed.

Tile Object

We'll also create a tile object for keeping keeping track of each section of the image.

function Tile()
	this.imgPos	= [0, 0];
	this.canvasPos	= [0, 0];

The Tile object has two properties: imgPos, which is the x, y offset of this tile segment on the source image (the grid position, not the pixel position; these values must be multiplied by tileW and tileH to get the pixel position); the other property, canvasPos, is the grid position of this segment on the Canvas element or game screen. Again, to get the pixel position these values must be multiplied by tileW, tileH.

Page loaded in 0.01 second(s).