jQuery(function () { // Game model object var field = new (function () { this.moves = 0; this.cells = [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ]; this.isFree = function (row, col) { return -1 < col && 4 > col && -1 < row && 4 > row && 16 == this.cells[row][col]; }; this.isSolved = function () { for (var i = 15; i > -1; i--) { if ((i + 1) != this.cells[(i - (i % 4)) / 4][i % 4]) { return false; } } return true; }; this.move = function (p) { var d = [[-1, 0], [1, 0], [0, -1], [0, 1]]; if (16 != this.cells[p.row][p.col]) { for (var k in d) { if (this.isFree(p.row + d[k][1], p.col + d[k][0])) { this.cells[p.row + d[k][1]][p.col + d[k][0]] = this.cells[p.row][p.col]; this.cells[p.row][p.col] = 16; p.col += d[k][0]; p.row += d[k][1]; return ++this.moves; } } } return false; }; this.reset = function () { var a, b, c, d, i, v = []; for (i = 0; i < 16; v.push(++i)); var t = [a = [-4, -3, 1], b = [1, 5, 4], c = [4, 3, -1], d = [-1, -5, -4]]; var ts = [[b],[b,c],[b,c],[c],[a,b],t,t,[c,d],[a,b],t,t,[c,d],[a],[a,d],[a,d],[d]]; var i, cSet, sT, fc = 15, d; for (i = 0; i < 150; i++) { sT = ts[fc][Math.round(Math.random() * (ts[fc].length - 1))]; d = (Math.round(Math.random())) ? [2,0] : [0,2]; v[fc] = v[sT[d[0]] + fc]; v[sT[d[0]] + fc] = v[sT[1] + fc]; v[sT[1] + fc] = v[sT[d[1]] + fc] fc += sT[d[1]]; } v[fc] = 16; for (i = 0; i < 16; i++) { this.cells[(i - (i % 4)) / 4][i % 4] = v[i]; } this.moves = 0; }; })(); // Constants var cSize = 44; var cellCss = {'background-color' : '#fff', 'color' : '#aaa', 'border-color' : '#aaa'}; var cellNCss = []; // jQuery part var lock = false, game15 = $('#game15').get(0), offset = {'left' : game15.offsetLeft + 75, 'top' : game15.offsetTop + 5}; $('#shuffle').click(function () { if (lock) return; field.reset(); $('#moves').html('0'); $('#game15-field').empty(); for (var col = 0; col < 4; col++) { for (var row = 0; row < 4; row++) { !field.isFree(row, col) && ($('#game15-field').get(0).appendChild( $("