代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>乌龟游戏</title>
<script type="text/javascript">
function move(obj){
//乌龟图片高度
var wuGui_height = 67;
//乌龟图片宽度
var wuGui_width = 94;
//公鸡图片高度
var cock_height = 73;
//公鸡图片宽度
var cock_width = 76;
var wuGui = document.getElementById("wugui");
var wuGui_left = parseInt(wuGui.style.left.substring(0,wuGui.style.left.indexOf("p")));
var wuGui_top = parseInt(wuGui.style.top.substring(0,wuGui.style.top.indexOf("p")));
var input = document.getElementsByTagName("input");
var cock = document.getElementById("cock");
var cock_left = parseInt(cock.style.left.substring(0,cock.style.left.indexOf("p")));
var cock_top = parseInt(cock.style.top.substring(0,cock.style.top.indexOf("p")));
//乌龟和公鸡左上角的距离(纵向距离)
var y = Math.abs(wuGui_top - cock_top);
//乌龟和公鸡左上角的距离(横向距离)
var x = Math.abs(wuGui_left - cock_left);
//默认不重叠
yy = 0;
xx = 0;
if(obj.value == "向上走"){
wuGui_top -= 10;
wuGui.style.top = wuGui_top + "px";
}
if(obj.value == "向左走"){
wuGui_left -= 10;
wuGui.style.left = wuGui_left + "px";
}
if(obj.value == "向右走"){
wuGui_left += 10;
wuGui.style.left = wuGui_left + "px";
}
if(obj.value == "向下走"){
wuGui_top += 10;
wuGui.style.top = wuGui_top + "px";
}
//碰撞
if(wuGui_top < cock_top){
if( y < wuGui_height){
yy = 1;
}
}else {
if (y < cock_height){
yy = 1;
}
}
if(wuGui_left < cock_left){
if( x < wuGui_width){
xx = 1;
}
}else {
if (x < cock_width){
xx = 1;
}
}
if(xx && yy){
alert("乌龟吃了鸡!");
wuGui.style.top = "100px";
wuGui.style.top = "120px";
}
}
window.onload = function () {
}
</script>
</head>
<body>
<table border="1">
<tr>
<td></td>
<td><input type="button" value="向上走" onclick="move(this)"/></td>
<td></td>
</tr>
<tr>
<td><input type="button" value="向左走" onclick="move(this)"/></td>
<td></td>
<td><input type="button" value="向右走" onclick="move(this)"/></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="向下走" onclick="move(this)"/></td>
<td></td>
</tr>
</table>
<!--把乌龟放在一个div-->
<div id="wugui" style="position: absolute ;left:100px;top:120px;">
<img src="1.bmp" border="1" alt=""/>
</div>
<!--公鸡图片div-->
<div id="cock" style="position:absolute;left:200px;top:200px;">
<img src="2.bmp" border="1" alt=""/>
</div>
</body>
</html>