日期:2014-05-16  浏览次数:20538 次

一个很精致(个人是这么认为的,尽管没有界面)的JavaScript贪吃蛇游戏
一个很精致(个人是这么认为的,尽管没有界面)的JavaScript贪吃蛇游戏,支持ie8, firefox3.6,代码(可能很冗余)如下:
HTML code
 <!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>

<meta http-equiv="content-type" content="text/html; charset=gbk" />

<title>Snake </title>

<style type="text/css">
<!--

#prompt {

margin: auto;

width: 402px;
font-size: 12px;
color: green;

background-color: pink;

}
#prompt input {
font-size: 12px;
background-color: #555555;
cursor: pointer;
color: orange;
}

#snake {

border: 1px solid orange;

margin: auto;

position: relative;

width: 400px;

height: 300px;

}

#snake span {

float: left;

width: 8px;

height: 8px;

border: 1px solid #feffef;

background-color: #ffeeff;

}
#score {
color: blue;
float: right;
}
#state {
color: red;
}
#config {
width: 402px;
font-size: 12px;
background-color: lightblue;
margin: auto;
}
-->

</style>

<script type="text/javascript">

<!--

function $( id ) { // simplfied function document.getElmentById(string id)

return document.getElementById( id );

}
function change(id_suffix, color) {
$("s" + id_suffix).style.backgroundColor = color;
}

function get_random( maxnumber ) { // get a random number in [0, maxnumber)

return Math.floor( maxnumber*Math.random() );

}


// the snake's head's, body's, next point's, and other points' color

var headcolor="blue", bodycolor="green", nextcolor="red", bgcolor="#ffeeff";

// the snake's height, width, body, the flag if the snake can go through the wall, the next point's position

var line, row, snakebody, iscycled, nextpoint;

// the snake's moving speed, interval ID, direction, the flag if game is over, the flag if game is paused

var speed=500, ID=null, direction=100, gameover=false, ispaused=false, called=false;


function initialize_snake (l, r, ic) { // initialize the game before the game starts
if (arguments.length == 3) {

line = l;
row = r;
iscycled = ic;
}

snakebody = new Array(1); // the whole snake body

snakebody[0] = 0; // the head(snakebody[snakebody.length-1]) of snake is initialized to [0,0]

nextpoint = get_random(line*row-1)+1; // assign the next point's position a random position(different from head[0,0])

}

function create_map() {
var s = "", i, j;

for (i=0; i < line; i++) {

s += " <div>";

for (j=0; j < row; j++) {

if (i == 0 && j == 0) {

s += ' <span style="background-color:blue;" id="s' + (row*i + j) + '">&nbsp; <\/span>';

} else {

s += ' <span id="s' + (row*i