使用 JQuery 的 BrainVita 游戏
使用 JQuery 功能实现 BrainVita 游戏
引言
如何玩这个游戏?

你横向或纵向跳过一个棋子到空位。一个棋子一次只能跳过一个棋子。其他移动被认为无效。被“跳过”的棋子从棋盘上移除。你的目标是留下最少的棋子在棋盘上。也就是说,最终棋盘上只剩下一个棋子。
你这样移动
- 拖动标记为 '1' 的棋子
- 检查标记为 '3' 的空位
- 清空标记为 '2' 的棋子
基本上,棋子 '1' 跳过了棋子 '2' 并移动到 '3'。棋子 '2' 从棋盘上移除,空位 '3' 被从位置 '1' 移动过来的棋子占据。
背景
JQuery 拥有丰富的 JavaScript 库。JQuery 的一大优势在于其跨浏览器兼容性、动画效果、丰富的 UI 交互、拖放功能等。利用这些特性,我们可以构建一个名为 BrainVita 的小游戏。 掌握 JQuery 的基本知识对于阅读本文至关重要。 Google APIs 从 Google 网站加载,因此用户需要连接到互联网才能使游戏正常工作。
Using the Code
创建一个 HTML 页面,并放置布局以创建游戏棋盘。
<table border="0" cellpadding="1" cellspacing="1" style="border: solid 1px green">
<tr>
<td align="center"><button id="reset">Reset Board</button><br />
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<div id="Brainvita"></div>
</td>
</tr>
</table>
定义表格布局进行格式化。
定义一个名为 "reset
" 的按钮,帮助我们重置 BrainVita 游戏棋盘。
定义 div
标签,id 为 "BrainVita
",作为稍后使用 JavaScript 函数绘制游戏棋盘的占位符。
通过通用的 API 加载函数加载 JQuery
API
<!--load the Google api loader-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!--load the specific api required-->
<script type="text/javascript">
google.load('jquery', '1.3.2');
google.load('jqueryui', '1.7.2');
</script>
设置按钮 "reset
" 的点击事件处理程序,并在页面加载时绘制棋盘。
/// Click event handler for the Reset Board button
$(document).ready(function()
{
// attach the click event handler for the
// reset board button
$('#reset').click(function ()
{
// redraw the board
DrawBoard();
//$('#messages').text('Resetting the board..Complete!');
});
// Load the board on load of the window
DrawBoard();
});
$(document).ready(function())
在 Javascript 中表现为 window.onLoad
函数。
$('#reset').click(function ())
将点击事件处理程序附加到名为 "reset
" 的按钮。 DrawBoard()
函数准备 BrainVita 游戏棋盘,以便在页面加载时开始游戏。
DrawBoard()
函数执行以下操作。准备游戏棋盘。注意:将 Red.png 图像文件放在与 HTML 文件相同的目录中。
// empty the div element first
$('#Brainvita').empty();
// Build the Board
var gameBoard = "<table border='0' cellspacing='3' cellpadding='2'>";
for(var rows = 0; rows < 7; rows++)
{
gameBoard+= "<tr>";
for(var cols = 0; cols < 7; cols++)
{
var imgId = " id = 'i" + rows + cols + "' ";
var divId = " id = 'd" + rows + cols + "' ";
var altValue = " alt = 'i" + rows + cols + "' ";
if(rows < 3 && cols > 1 && cols < 5)
{
gameBoard+= GetImageMarble(divId, imgId, altValue);
}
else if(rows > 1 && rows < 5)
{
// the center marble
if(rows == 3 && cols == 3)
{
gameBoard+= GetEmptyMarble(divId);
}
else
{
gameBoard+= GetImageMarble(divId, imgId, altValue);
}
}
else if(rows > 4 && cols > 1 && cols < 5)
{
gameBoard+= GetImageMarble(divId, imgId, altValue);
}
else
{
// other non usable marble slots on the board
gameBoard+= "<td></td>";
}
}
gameBoard+= "</tr>";
}
gameBoard += "</table>";
// attach the newly created table
// to the Brainvita div tag
$('#Brainvita').html(gameBoard);
现在,为 id 以 "I
" 开头的图像标签附加可拖动事件处理程序。请注意,revert 属性表示如果无效,则返回到正在拖动对象的原始位置。
// now build the drag and drop system
$("img[id^='i']").draggable({ containment: '#Brainvita',
revert: 'invalid',
tolerance: 'fit'});
现在,为所有 id 以 "d
" 开头的 div
标签附加可释放事件处理程序。这包含确定移动是否有效的逻辑。
可释放事件处理程序中需要注意的重要属性是
accept
属性告诉函数何时可接受可释放对象,或不可接受。如果移动有效,则函数返回true
,否则返回false
。这将导致拖动的棋子返回到起始位置。drop
属性告诉函数在接受可拖动对象后要执行哪些操作。
$("div[id^='d']").droppable({
accept: function(event) {
var returnFlag = false;
if(event[0].nodeName == "IMG")
{
var destId = this.id;
var srcId = event[0].id;
var destNo = parseInt(destId.substring(1,3));
var srcNo = parseInt(srcId.substring(1,3));
var result = Math.abs(destNo - srcNo);
var removeNo = 0;
// check if the destination div tag is empty
// if empty then invalid move
if($(this).length == 1 && result != 0)
{
switch(result)
{
case 2:
// horizontal move
removeNo = ((destNo - srcNo) > 0) ?
destNo - 1 : destNo + 1;
break;
case 20:
// vertical move
removeNo = ((destNo - srcNo) > 0) ?
destNo - 10 : destNo + 10;
break;
}
if((result == 2 || result == 20) && removeNo != 0)
{
// valid move remove the middle marble
var elementToBeRemoved = (removeNo < 10) ? "0" +
removeNo : removeNo;
// make sure the inbetween item has an img item
if($("#i" + elementToBeRemoved).length == 1 &&
$("#i" + ((destNo < 10) ? "0" + destNo : destNo)).length == 0)
{
// valid move
returnFlag = true;
}
// log the trace
//$("#Trace").append("<BR>Accept Event destId=" +
//destId + " srcId=" + srcId + " destNo=" + destNo +
//" removeNo=" + removeNo + " returnFlag=" + returnFlag);
}
}
}
return returnFlag;
},
hoverClass: 'board-state-Active',
drop: function(event, ui) {
var destId = this.id;
var srcId = ui.helper.context.id; //event.srcElement.id;
var destNo = parseInt(destId.substring(1,3), 10);
var srcNo = parseInt(srcId.substring(1,3, 10));
var result = Math.abs(destNo - srcNo);
var removeNo = 0;
// check if the destination div tag is empty
if($(this).length == 1 && result != 0)
{
switch(result)
{
case 2:
removeNo = ((destNo - srcNo) > 0) ? destNo - 1 : destNo + 1;
break;
case 20:
removeNo = ((destNo - srcNo) > 0) ? destNo - 10 : destNo + 10;
break;
}
// Check to see if the move is valid
if((result == 2 || result == 20) && removeNo != 0)
{
// swap the id and alt value so as to recognize next time
ui.helper.context.id = "i" + ((destNo < 10) ? "0" +
destNo : destNo);
ui.helper.context.alt = ui.helper.context.id;
// frame the element to be removed id
var elementToBeRemoved = (removeNo < 10) ? "0" +
removeNo : removeNo;
// remove the inbetween item has an img item
if($("#d" + elementToBeRemoved).length == 1)
{
// remove the inbetween item
$("#i" + elementToBeRemoved).remove();
// empty the div tag
$("#d" + elementToBeRemoved).empty();
// log the trace
//$("#Trace").append("<BR>Drop Event: destId=" +
//destId + " srcId=" + srcId + " destNo=" + destNo +
//" removeNo=" + removeNo);
} // end if
} // if((result == 2 || result == 20) && removeNo != 0)
} // if($(this).length == 1 && result != 0)
} // end of function
}
其他 JavaScript 辅助函数如下
/// Gets a table column with a marble in it
function GetImageMarble(divId, imgId, altValue)
{
var imgTag = "<td align='center' valign='middle'><div ";
imgTag = imgTag + divId;
imgTag = imgTag + "><img ";
imgTag = imgTag + altValue + imgId;
imgTag = imgTag + " src='";
imgTag = imgTag + "Red.PNG'";
imgTag = imgTag + " class=\"marble\"></div></td>";
return imgTag;
}
/// Gets an empty table column
function GetEmptyMarble(divId)
{
return "<td><div " + divId + "></div></td>";
}
在 HTML 页面的 Head
标签之间添加这些样式
<style type="text/css">
.marble { width: 48px; height: 48px; border: 0px;position:inherit; top:0px; left:0px}
.marbleHover { width: 40px;height:40px; border:2px; border-color:red}
.divclass {border: 1px solid blue; width: 50px;height:50px; text-align:center;}
.board-state-Hover {border: 2px solid red; width: 50px;height:50px;}
.board-state-Active {border: 1px solid green; width: 50px;height:50px;}
</style>
关注点
作为 JQuery 的新手,我想编写我最喜欢的游戏来理解 JQuery 的拖放功能。该 API 提供了一种非常简单和新的编写 JavaScript 代码的方式,它非常容易理解和学习。在 www.jquery.com 上也有很好的文档。