Friday, February 29, 2008

15 puzzle in javascript

http://www.geocities.jp/teruakigemma/nikoniko/puzzle.html
used prototype.js.

var puzzle;
var zeropos;

function swap_puzzle(x,flag) {
var tmp = puzzle[x];
puzzle[x] = puzzle[zeropos];
puzzle[zeropos] = tmp;
if (flag) {
$('cell' + zeropos).src = puzzle[zeropos] + '.png';
$('cell' + x).src = puzzle[x] + '.png';
if ($A($R(0,15)).all(function(x) {return x == puzzle[x]}))
$('main').appendChild(new Element('span').update('nicely done!'));
};
zeropos = x;
}

function shuffle() {
for (var i = 0; i < 5; i++) {
var a = [];
if (Math.floor(zeropos / 4) != 0) a.push(zeropos - 4);
if (Math.floor(zeropos / 4) != 3) a.push(zeropos + 4);
if (zeropos % 4 != 0) a.push(zeropos - 1);
if (zeropos % 4 != 3) a.push(zeropos + 1);
swap_puzzle(a[Math.floor(Math.random() * a.length)],false);
};
}

function click_cell(x) {
if(x == zeropos - 4) swap_puzzle(zeropos - 4, true);
if(x == zeropos + 4) swap_puzzle(zeropos + 4, true);
if(x == zeropos - 1) swap_puzzle(zeropos - 1, true);
if(x == zeropos + 1) swap_puzzle(zeropos + 1, true);
}

function main() {
puzzle = $A($R(0,15));
zeropos = 0;
shuffle();
var e = $('main');
while (e.firstChild) e.removeChild(e.firstChild);
$A($R(0,15)).inGroupsOf(4).each(function(x) {
x.each(function(y) {
var img = new Element('img',{id:'cell' + y,src:puzzle[y] + '.png',width:64,height:64});
img.observe('click',function () {click_cell(y)});
e.appendChild(img)});
e.appendChild(new Element('br'))});
}

window.onload = main;

1 comment:

mesin jahit said...

akan memilih mesin jahit multifungsi (portable) atau mesin jahit terbaru portable lurus. Mesin Jahit Portable Multifungsi yang memungkinkan Anda untuk dapat lebih berkreasi dalam menjahit, dilengkapi dengan 24 fungsi jahitan dan mudah http://mesinjahitjakarta.tripod.com Mesin Jahit Murah