自己做的贪吃蛇


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Snake</title>
<script>
var width=20;
var height=20;
document.write("<table bgcolor=white bordercolor=black align=center border=1 cellpadding=0 cellspacing=0><tr><td>");
for(i=0;i<width;i++){
for(j=0;j<height;j++){
document.write("<img src=BLANK.GIF width=15 height=15>");
}
document.write("<br>");
}
document.write("</td></tr></table>");

var sPosition=Math.floor(Math.random()*width*height);
document.images[sPosition].src="WORM.GIF";

var fPosition;
do{
fPosition=Math.floor(Math.random()*width*height);
}while(fPosition==sPosition)
document.images[fPosition].src="FOOD.GIF";

document.onkeydown=getDirect;
var direct;
var direction=-1;
function getDirect(){
direct=window.event.keyCode;
}

window.onload=go;
var when;
var speed=200;
function go(){
if(direct==37 && direction!=39){
if((sPosition)%20==0){
die();
}
else{
doIt(sPosition-1);
}
}
else if(direct==38 && direction!=40){
if((sPosition-20)<0){
die();
}
else{
doIt(sPosition-20);
}
}
else if(direct==39 && direction!=37){
if((sPosition+1)%20==0){
die();
}
else{
doIt(sPosition+1);
}
}
else if(direct==40 && direction!=38){
if(sPosition+20>399){
die();
}
else{
doIt(sPosition+20);
}
}
else{
direct=direction;
}
when = window.setTimeout("go();",speed);
}

var snake=new Array();
snake.push(sPosition);
function doIt(where){
direction=direct;

snake.push(where);
for(i=snake.length-1;i>0;i--){
snake[i]=snake[i-1];
}
snake[0]=where;

if(where==fPosition){
document.images[snake[0]].src="WORM.GIF";
do{
fPosition=Math.floor(Math.random()*width*height);
}while(document.images[fPosition].src.indexOf("WORM.GIF")>0)
document.images[fPosition].src="FOOD.GIF";
}else{
if(document.images[snake[0]].src.indexOf("WORM.GIF")>0){
die();
}else{
document.images[snake[0]].src="WORM.GIF";
document.images[snake[snake.length-1]].src="BLANK.GIF";
snake.pop();
}
}
sPosition=where;
}

function die(){
alert("You lost!");
speed-=400;
clearTimeout(when);
}
</script>
</head>
<body>
<div align=center style="color:#4682B4;font-size:30">
<br>按方向键操作方向。
<br>按F5键重新开始。
<br>按空格键暂停。
</div>
</body>
</html>


目前只能是在IE中运行,如果大家看了觉得有什么可以改进的地方一定要留言啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值