整体思路
用面向对象的思路写一个贪吃蛇游戏,首先需要找到游戏中的所有对象。在每一个游戏的实现中都会有一个游戏引擎对象,我们定义为gameBox,除此之外该游戏还包括了蛇(snake),食物(food)两个对象。找到对象后再去分析对象所具有的属性和方法,并通过代码去实现它。
实现过程
1、游戏引擎对象的实现。
由于在每个游戏中,引擎对象一般都只有一个,所以我们可以用对象字面量的形式来定义,具体代码如下:
var gameBox = {
rows: 20,
cols: 20,
allTds: [],
start: function(){
var oTable = document.createElement('table');
for (var i=0; i<this.cols; i++)
{
var aTr = document.createElement('tr');
var arr = [];
for (var j=0; j<this.cols; j++)
{
var aTd = document.createElement('td');
aTr.appendChild(aTd);
arr.push(aTd);
}
this.allTds.push(arr);
oTable.appendChild(aTr);
}
document.body.appendChild(oTable);
}
整个游戏的环境我们用一个表格来实现,最原始的 游戏引擎对象包括表格的行数(rows)、列数(cols)以及保存所有td的数组(allTds)三个属性,和一个将环境添加到页面的方法(start)。
2、食物对象的实现。
食物除了具有自身大小,颜色,位置等属性外,还具有显示,改变位置等方法,由于在游戏中可能不止出现一个食物,所以我们采用构造函数的方式来创建食物对象。
function Food(){
this.x = 0;
this.y = 0;
}
Food.prototype.change = function(){
this.x = parseInt(Math.random()*gameBox.cols);
this.y = parseInt(Math.random()*gameBox.rows);
this.show();
}
Food.prototype.show = function(){
gameBox.allTds[this.y][this.x].className = 'food';
}
定义两个x,y属性i来保存食物的位置,然后当达到一定要求时改变食物的位置,食物的位置是随机的,所以需要创建两个随机数,作为食物的位置。
3、蛇对象的实现
和食物一样,蛇在游戏中可能也不止一条,所以我们也采用构造函数的方式来定义对象。
function Snake(){
this.nodes = [
{x:5,y:1},
{x:4,y:1},
{x:3,y:1},
{x:2,y:1},
{x:1,y:1}
];
this.directer = 'down';
}
Snake.prototype.render = function(){
for (var i=0; i<this.nodes.length; i++)
{
var x = this.nodes[i].x;
var y = this.nodes[i].y;
gameBox.allTds[y][x].className = 'snake';
}
}
Snake.prototype.move = function(){
var x = this.nodes[0].x;
var y = this.nodes[0].y
if (this.directer == "right")
{
x++;
}
if(this.directer == "left")
{
x--;
}
if (this.directer == "up")
{
y--;
}
if (this.directer == "down")
{
y++;
}
if (x>=gameBox.cols || y>=gameBox.rows || x<0 || y<0)
{
alert("Game Over!!");
clearInterval(gameBox.timer)
return ;
}
this.nodes.unshift({x:x,y:y});
this.nodes.pop({x:x,y:y});
if (x == gameBox.food.x && y == gameBox.food.y)
{
this.nodes.unshift({x:x,y:y});
gameBox.food.change();
}
this.render();
}
在蛇对象中定义一个nodes属性来保存蛇,directer属性保存蛇的运动方向render方法将蛇显示在游戏环境中。