DHTML Jigsaw Puzzle: Cross-Browser; Solving | WebReference

# DHTML Jigsaw Puzzle: Cross-Browser; Solving

## The DHTML Lab Jigsaw Puzzle, Part IV: Cross-Browsersolving and setting the grid

Our random number generator, that creates x-y coordinates for piece positioning, remains exactly the same:

```function getRandNums(from,to){
temp = parseInt((Math.random() * (to-from)) + (from));
while (isNaN(temp)) {
temp = parseInt((Math.random() * (to - from)) + (from))
}
return temp
}Setting the Grid
Our setGrid() function is, again, a combination of the browser-specific codes, with no new statements.
function setGrid() {
gridWidth = (9/puzzAcross) * puzzWidth;
gridHeight = (9/puzzDown) * puzzHeight;
if (IE4) {
elImGrid.style.width = gridWidth;
elImGrid.style.height = gridHeight;
elGrid.style.clip = "rect(0 " + puzzWidth + sp + puzzHeight + " 0)";
}
else {
elGrid.document.write("<IMG NAME='imGrid' SRC='grid.gif' WIDTH=" + gridWidth + " HEIGHT=" + gridHeight + ">");
elGrid.document.close();
elGrid.clip.right = puzzWidth;
elGrid.clip.bottom = puzzHeight;
}
gridBut.value = "Grid ON";
if (isBroken) { elGrid.showIt(true) }
}Solving
Recall that in our HTML, we changed the function called by the Solve and Hint buttons to preSolve(), to avoid the double auto-solve problem. preSolve() filters any solve calls, disallowing solves, if:
the puzzle is already being auto-solved, or
the puzzle is not broken, or
a new puzzle is called for
function preSolve(isFullSolve) {
if (isSolving || !isBroken || isNewPuzz) { return };
solve(isFullSolve);
}If a solve should be allowed, preSolve() calls our old solve function.
solve() is a simple a combination of the two browser codes, with one important addition. If a full auto-solve is called for, that is, if isFullSolve is true, isSolving is set to true, allowing filtering of any further user presses of Solve:
function solve(isFullSolve) {
if (pieceToSolve > puzzPieces) { pieceToSolve = 1; return }

isSolving = (isFullSolve) ? 1 : 0;
tempEl = eval("PIECE" + pieceToSolve);
if (tempEl.draggable){
if (tempEl != activeEl ) {
if (IE4) {tempEl.style.zIndex = activeEl.style.zIndex + 1}
else {tempEl.moveAbove(activeEl)}
activeEl = tempEl;
}
flashTimer = setInterval("visToggle(" + isFullSolve + ")",100);
}
else { pieceToSolve++; solve(isFullSolve) };
}Finally, let's look at the remaining miscellaneous functions of our main script.

Produced by Peter Belesis and