|
这是一个基于浏览器的数字拼图游戏。你可以花些时间研究怎样利用jquery库创建javascript应用程序。这个小游戏由游戏数据及UI组成,它仅仅包含26行的代码及jquery库。
预览:
点击小方块移动。
游戏代码:
<style type="text/css">
#game15 {
width: 255px; height: 290px; border: 1px solid gray;
}
#game15-controls {
margin: 10px;
height: 25px;
}
#game15-field {
width: 240px;
height: 240px;
margin: 10px 0px 10px 10px;
}
.game-cell {
width: 55px;
height: 55px;
border: 1px solid gray;
text-align: center;
line-height: 55px;
color: #aaa;
font-family: arial;
font-weight: bold;
font-size: 30px;
background: white;
position: absolute;
overflow: hidden;
}
</style>
<script type="text/javascript">
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 i = 16, values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
while (i--) {
this.cells[(i - (i % 4)) / 4][i % 4] = (1
+ parseInt(values.splice(Math.floor(Math.random() * values.length), 1)));
}
this.moves = 0;
};
})();
// View with jQuery
var lock = false;
$('#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(
$("<div class='game-cell'>" + field.cells[row][col] + "</div>")
.css({ 'left' : col * 60 + 10, 'top' : row * 60 + 45})
.click(function () {
if (!lock && field.move(this._p)) {
lock = true;
$('#moves').html('' + field.moves);
$(this).animate(
{'left' : this._p.col * 60 + 10, 'top' : this._p.row * 60 + 45},
300, '', function () {
field.isSolved() && alert('You win!');
lock = false;
});
}
}).get(0))._p = {'row': row, 'col': col});
}
}
}).click();
});
</script>
<div id="game15">
<div id="game15-controls">
<button id="shuffle">Shuffle</button> Moves: <span id="moves"></span> <a href="
http://www.alexatnet.com/node/68">Alex @ Net</a>
</div>
<div id="game15-field"></div>
</div>
如果你喜欢这个游戏你可以通过以下代码将它加入到你的网站
<iframe frameborder="0" style="width: 280px; height: 300px;"
src="
http://www.hotajax.org/download/jquery/Fifteen puzzle.htm"></iframe>
转载自http://www.alexatnet.com/files/n68.Game.html
Newer news items:
Older news items:
|