内容
贪吃蛇游戏包含:1.游戏引擎,2.蛇,3.食物。
基本操作
蛇会自动走,键盘可控制方向(上下左右),碰到边界或者蛇的身体都会结束游戏,努力吃食物长大。
代码
var gGameBox = {
rows: 30,
cols: 30,
allTd: [],
food:null,
snake:null,
timer:null,
clear:function(){
for (var i=0;i<gGameBox.allTd.length ;i++ )
{
for (var j=0;j<gGameBox.allTd[i].length ; j++)
{
gGameBox.allTd[i][j].className = ""
}
}
},
keyControl:function(){
window.onkeydown = function(e){
var v = e.keyCode;
if (v == 37)
{
if (gGameBox.snake.direct=="right")
{
return ;
}
gGameBox.snake.direct ="left"
}
if (v == 39)
{
if (gGameBox.snake.direct=="left")
{
return ;
}
gGameBox.snake.direct ="right"
}
if (v == 38)
{
if (gGameBox.snake.direct=="down")
{
return ;
}
gGameBox.snake.direct ="up"
}
if (v == 40)
{
if (gGameBox.snake.direct=="up")
{
return ;
}
gGameBox.snake.direct ="down"
}
}
},
start: function(){
gGameBox.init();
this.food = new RandomFood()
this.snake = new Snake()
this.keyControl()
gGameBox.timer = setInterval(function(){
gGameBox.clear();
gGameBox.snake.move();
gGameBox.food.show();
},200)
},
init: function(){
var oTable = document.createElement("table")
for (var i=0;i<this.rows ; i++)
{
var oTr = document.createElement('tr')
var arr = []
for (var j=0;j<this.cols ;j++ )
{
var oTd = document.createElement('td')
oTr.appendChild(oTd)
arr.push(oTd)
}
gGameBox.allTd.push(arr)
oTable.appendChild(oTr)
}
document.body.appendChild(oTable)
}
}
function RandomFood(){
this.x = 0
this.y = 0
this.change()
}
RandomFood.prototype.show = function(){
gGameBox.allTd[this.y][this.x].className= "food"
}
RandomFood.prototype.change = function(){
this.x = parseInt(Math.random()*gGameBox.rows)
this.y = parseInt(Math.random()*gGameBox.cols)
if (gGameBox.allTd[this.y][this.x].className == "snake")
{
this.change()
}
this.show()
}
function Snake(){
this.bd = [
{n:4,m:0},
{n:3,m:0},
{n:2,m:0},
{n:1,m:0},
{n:0,m:0},
];
this.direct = "right";
this.fresh()
}
Snake.prototype.fresh = function(){
for (var i=0;i<this.bd.length ;i++ )
{
var n = this.bd[i].n
var m = this.bd[i].m
gGameBox.allTd[m][n].className = "snake"
}
}
Snake.prototype.move = function(){
var n = this.bd[0].n
var m = this.bd[0].m
if (this.direct=="right")
{
n++;
}else if (this.direct=="left")
{
n--;
}
else if (this.direct=="down")
{
m++;
}
else if (this.direct=="up")
{
m--;
}
if (n>=gGameBox.cols||m>=gGameBox.rows||n<0||m<0)
{
clearInterval(gGameBox.timer)
alert("GAME OVER")
return ;
}
this.fresh()
if (n == gGameBox.food.x && m == gGameBox.food.y)
{
this.bd.unshift({n:gGameBox.food.x,m:gGameBox.food.y})
gGameBox.food.change()
this.fresh()
return
}
this.bd.unshift({n:n,m:m})
this.bd.pop()
}