<pre></pre><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><-0----贪食蛇---<</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
.main{
width:690px;
margin:0 auto;
}
#box{
margin:0 auto;
border:1px solid green;
width:681px;
height:340px;
position:relative;
}
#bigin{
margin:0 auto;
margin:10px;
padding:5px;
}
.snake{
width:10px;
height:10px;
overflow:hidden;
background-color:black;
position:absolute;
}
.food{
width:10px;
height:10px;
overflow:hidden;
background-color:red;
position:absolute;
}
</style>
<script text="text/javascript" language="javascript">
var Sx=340,Sy=170;//蛇首部
var Fx,Fy;//食物
var Gox=10, Goy=0; //移动方向
var isOver = false;
var AllDiv;
var AllSpan;
function $(id){
return document.getElementById(id);
}
window.onload = function(){
creatSnake(Sx,Sy);
creatFood();
AllDiv = $("box").all.tags("DIV");
AllSpan = $("box").all.tags("Span");
//alert(AllDiv.length);
$("bigin").attachEvent('onclick',function(){
//alert('asdf');
play();
});
}
function play(){
if(isOver){
clearTimeout(TimeHandle);
}else{
run();
TimeHandle = setTimeout('play()',60);
}
}
function run(){
var NSx = Sx+Gox;
var NSy = Sy+Goy;
isOver = isGameOver(NSx,NSy);
if(isOver){return;}
if(NSx == Fx && NSy == Fy){
creatFood();
}else{
AllDiv[0].removeNode(true);
}
creatSnake(NSx,NSy);
}
function keydown(){
key=event.keyCode;
switch(key){
case 37:move(-1,0);break;//左
case 38:move(0,-1);break;//上
case 39:move(1,0);break;//右
case 40:move(0,1);break;//下
}
}
function move(x,y){
Gox = x*10;
Goy = y*10;
}
function creatSnake(x,y){
$("box").innerHTML +="<div class=/"snake/" style=/"top:"+y+";left:"+x+"/"></div>";
Sx = x;
Sy = y;
}
function creatFood(){
if(AllSpan != null){
AllSpan[0].removeNode(true);
}
Fx = Math.round(Math.random()*33)*20;
Fy = Math.round(Math.random()*16)*20;
$("box").innerHTML +="<span class=/"food/" style=/"top:"+Fy+";left:"+Fx+"/"></span>";
}
function checkfood(x,y){
return true;
}
function isGameOver(x,y){
if(x<0 || x>=680 || y>=340 ||y<0){
return true;
}else{
return false;
}
}
</script>
</head>
<body οnkeydοwn="keydown()">
<div class="main">
<div id="box"></div>
<input type="button" id="bigin" value="开始游戏">
</div>
</body>
</html>
用js写的贪食蛇小游戏
最新推荐文章于 2022-11-14 16:15:29 发布