乌龟捉鸡

<html>
	<head>
		<script language = "javascript" type = "text/javascript">
			//响应用户点击按钮,或者是按下键盘
			function move(eobj){
				//得到乌龟
				var wugui_height = 56;
				var wugui_width = 79;
				//得到公鸡
				var cock_height = 61;
				var cock_width = 64;
				
				var wugui = document.getElementById("tortoise");
				  //响应键盘 window.event可以判断用户是通过按键盘来控制乌龟
				if(window.event){
					key = eobj.keyCode;
				}
				  //得到乌龟当前的top 和 left
				var wugui_top = wugui.style.top;
				var wugui_left = wugui.style.left;
				//window.alert(wugui_left);
					  //去掉px
				wugui_top = parseInt(wugui_top.substring(0,wugui_top.indexOf("p")));
				wugui_left = parseInt(wugui_left.substring(0,wugui_left.indexOf("p")));
					//得到cock的top 和 left
				var cock = document.getElementById("cock");
				var cock_top = cock.style.top;
				var cock_left = cock.style.left;
				
				cock_top = parseInt(cock_top.substr(0,cock_top.length-2));
			  cock_left = parseInt(cock_left.substr(0,cock_left.length-2)); 
				
				//得到用户点击按钮的value
				var val = eobj.value;
				if(val == "向下走" || key == 83){
					wugui.style.top = (wugui_top+10)+"px";
					wugui_top = wugui_top + 10;
				}else if(val == "向右走" || key == 68){
					wugui.style.left = (wugui_left+10)+"px";
					wugui_left = wugui_left + 10;
				}else if(val == "向左走" || key == 83){
					wugui.style.left = (wugui_left-10)+"px";
					wugui_left = wugui_left - 10;
				}else if(val == "向上走" || key == 87){
					wugui.style.top = (wugui_top-10)+"px";
					wugui_top = wugui_top - 10;
				}
				//判断是否相撞
				var y = Math.abs(cock_top - wugui_top);
				var x = Math.abs(cock_left - wugui_left);
				 //标记,用于记录是否有可能相撞
				var xx = 0;
				var yy = 0;
				//在纵向上
				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 == 1 && yy == 1){	
					xx = 0;
					yy = 0;
					window.alert("已抓到!");
					//撞到后,让乌龟重新回到原来的位置
					wugui.style.top = 120 + "px";
					wugui.style.left = 100 + "px";
				}
			}
		</script>
	</head>
	<body onkeydown = "return move(event)">
		<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 id = "tortoise" style = "position:absolute;top:120px;left:100px">
			<img src = "tortoise.png" title = "乌龟"/>
		</div>
		<div id = "cock" style = "position:absolute;top:200px;left:200px">
			<img src = "cock.png" title = "公鸡"/>	
		</div>
	</body>	
</html>

展开阅读全文

没有更多推荐了,返回首页