spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column45


A DOM-Based Sliding Puzzle (7)

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

Scrambling the Picture

The rule of the sliding puzzle is that you start with a scrambled picture and you try to put the pieces in their correct positions, in a minimum number of moves. Here is the scrambling function:

function randomizePicture() {
  for(i = 0; i < 3000; i++) {
    newBlank = Math.round(Math.random() * (size - 1));
    if (!validClick(oldBlank, newBlank)) continue;
    divNode.childNodes[oldBlank].swapNode(divNode.childNodes[newBlank]);
    oldBlank = newBlank;
  }
}

This function relies on the validClick() function that we'll explain more in the next page. It accepts two parameters, oldBlank and newBlank, which are positions on the puzzle board. The validClick() function checks whether it is a valid move to swap the oldBlank position with the newBlank position.

We scramble the puzzle board by simulating many moves by a player. We chose 3000 as a number that will assure a total randomization of the board. We always keep track of the blank square position, oldBlank. Then, for each iteration we try a new position for the blank square:

newBlank = Math.round(Math.random() * (size - 1));

The new attempted position newBlank is a number between 0 and 11. We check then that swapping oldBlank with newBlank is valid:

if (!validClick(oldBlank, newBlank)) continue;

If it is not a valid switch, we immediately go to the next iteration with the continue keyword. If the swapping is valid, we swap the child nodes of divNode:

divNode.childNodes[oldBlank].swapNode(divNode.childNodes[newBlank]);

We explained swapping in Column 43. Notice that we swap whole nodes, with all their properties and children. For every successful swapping we need to update the current position of the blank square, oldBlank = newBlank.

http://www.internet.com

Produced by Yehuda Shiran and Tomer Shiran

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint


Created: August 2, 1999
Revised: August 2, 1999

URL: http://www.webreference.com/js/column45/scramble.html