We are close to completing our JavaScript game. The only thing missing is the JavaScript code that moves the blocks and allows the game to be played. Since each block has only one direction it can move (into the empty space), there's no need for a Drag & Drop movement. Instead they move when they're clicked on.
The script makes an Array that will keep the position of the empty block, which starts in sixteenth place.
AName = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
Then, each time the user clicks on a block, the function "pop" is called.
function pop(val) {
for (a=0; a<AName.length; a++) {
if (AName[a] == val) {
Cell = a;
}}
if (AName[Cell-1] == 15 || AName[Cell+1] == 15 || AName[Cell+4] == 15 || AName[Cell-4] == 15 ) {
The last line checks if the block that the user clicks on is before or after the fifteenth block, or if it is four blocks away, which means it is either above or below the empty block. Then it changes the position of the clicked block with the position of the empty one. Finally it changes the position of the fifteenth block inside the array, so the next time the user clicks on a block the script can check it.
var NewDiv = eval("document.all.Holder"+AName[Cell]);
var NewTop = NewDiv.style.top;
var NewLeft = NewDiv.style.left;
var OldDiv = eval("document.all.Holder"+AName[OldNum]);
var OldTop = OldDiv.style.top;
var OldLeft = OldDiv.style.left;
OldDiv.style.left = NewLeft;
OldDiv.style.top = NewTop;
NewDiv.style.top = OldTop;
NewDiv.style.left = OldLeft;
var save = AName[OldNum];
AName[OldNum] = AName[Cell];
AName[Cell] = save;
OldTop = NewTop = OldLeft = NewLeft = OldNum = null;
Finally, here the full script source code for you to read and run. Watch out for extra linebreaks introduced by the constraints of this Web page.
<script language="JavaScript1.2">
// script by guy laor - all rights reserved 2000
var cells = 16;
var rows = 4;
var lines = 4;
var Ihight, Iwidth, cellH, cellW;
HoldDiv = new Array;
InnerDiv = new Array;
RandNum = new Array;
RandNum.length =0;
var Itop = Ileft = 100;
var Ctop = Cleft = 0;
function init(valueimg)
{
if (document.layers) {
alert("No Netscape users please! Try Internet Explorer for this page.");
return;
}
BaseImg = new Image;
IMAGE = valueimg;
BaseImg.src = valueimg; //"birth_of_venus.jpg";
Ihight = BaseImg.height;
Iwidth = BaseImg.width;