DHTML Jigsaw Puzzle: NN4; Automatic Solve | WebReference

DHTML Jigsaw Puzzle: NN4; Automatic Solve

Logo

The DHTML Lab Jigsaw Puzzle, Part III: NN4
solving the puzzle automatically


Automatic Solve

When the user presses the Solve button, the solve() function is called to automatically move all unsolved puzzle pieces to their correct position.

    function solve(isFullSolve) { if (!isBroken) { return }; tempEl = eval("PIECE" + pieceToSolve); if (tempEl.draggable){ if (tempEl != activeEl ) { tempEl.moveAbove(activeEl); activeEl = tempEl; } flashTimer = setInterval("visToggle(" + isFullSolve + ")",100); } else { pieceToSolve++; solve(isFullSolve) }; }

The single argument of solve() is isFullSolve. If the Solve button is pressed, this argument is true, calling for a full solve. The Hint button also calls solve() but with a false value for the argument, telling the function to only solve one piece.

If the puzzle is not broken, there is nothing to solve, so the function returns. The next piece in line to be solved is retrieved using pieceToSolve and its draggable property is checked. If it is false, it means the user manually solved this piece so pieceToSolve is incremented and solve() is called again. When a draggable piece is found, it is moved above the other pieces and visToggle() is called repeatedly.

Flashing

Whenever the user correctly positions a piece, a piece is solved automatically, or the full puzzle is solved, the visToggle() function is called to flash the piece or full image to alert the user to success.

    function visToggle(isFullSolve){ if (flashCount != flashTotal) { tempEl.visibility = (tempEl.visibility == "show") ? "hide" : "show"; flashCount++; } else { clearInterval(flashTimer); flashCount = 0; tempEl.visibility = 'show'; if (tempEl != elImage) { origPos() } if (isFullSolve) { pieceToSolve++; solve(true) } } }

When the flashTotal has been reached, the repeated calls to visToggle() are cancelled, the flash counter is re-initialized and the element is made visible. This possibly redundant statement is useful if an element was left invisible after an odd flashCount.

If the element being flashed is a piece and not the full image, origPos() is called to position it. Once positioned, and a full solve has been called for, solve() is called again.

Two functions remain to complete the puzzle solving discussion, origPos() and allDone().


Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: Nov. 27, 1997
Revised: Jan. 18, 1998

URL: http://www.webreference.com/dhtml/column10/puzzNSsolve.html