<!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中运行,如果大家看了觉得有什么可以改进的地方一定要留言啊。