定义 游戏引擎 对象
···var gGameBox = {
rows: 20, 行数
cols: 20, /列数
allTds: [], 存储所有的td元素对象
food: null, 食物对象
snake: null, 蛇对象
timer: null, 定时器···
方法: 清空环境
··· clear: function() {
for (var i = 0; i < gGameBox.allTds.length; i++) {
for (var j = 0; j < gGameBox.allTds[i].length; j++) {
gGameBox.allTds[i][j].className = "";
}
}
},
···
方法:支持键盘控制
··· keyControl: function() {
// onkeydown
window.onkeydown = function(e) {
var c = e.keyCode;
if (c == 37)
{
if (gGameBox.snake.direct == "right")
{
return ;
}
gGameBox.snake.direct = "left";
}
else if (c == 38)
{
if (gGameBox.snake.direct == "down")
{
return ;
}
gGameBox.snake.direct = "up";
}
else if (c == 39)
{
if (gGameBox.snake.direct == "left")
{
return ;
}
gGameBox.snake.direct = "right";
}
else if (c == 40)
{
if (gGameBox.snake.direct == "up")
{
return ;
}
gGameBox.snake.direct = "down";
}
}
},
start: function() {
gGameBox.init(); // 游戏初始化
gGameBox.food = new Food(); // 创建食物
gGameBox.snake = new Snake(); // 创建蛇
gGameBox.keyControl();
gGameBox.timer = setInterval(function() {
gGameBox.clear();
gGameBox.snake.move();
gGameBox.food.show();
}, 500);
//gGameBox.snake.fresh();
},
···
## 初始化
···init: function() {
var oTable = document.createElement("table");
for (var i = 0; i < gGameBox.rows; i++)
{
r oTr = document.createElement("tr");
var arr = [];
for (var j = 0; j < gGameBox.cols; j++) {
var oTd = document.createElement("td");
arr.push(oTd);
}
gGameBox.allTds.push(arr);
oTable.appendChild(oTr);
}
document.body.appendChild(oTable);
}
};···