整體思路
用面向?qū)ο蟮乃悸穼懸粋€貪吃蛇游戲,首先需要找到游戲中的所有對象。在每一個游戲的實現(xiàn)中都會有一個游戲引擎對象,我們定義為gameBox,除此之外該游戲還包括了蛇(snake),食物(food)兩個對象。找到對象后再去分析對象所具有的屬性和方法,并通過代碼去實現(xiàn)它。
實現(xiàn)過程
1、游戲引擎對象的實現(xiàn)。
由于在每個游戲中,引擎對象一般都只有一個,所以我們可以用對象字面量的形式來定義,具體代碼如下:
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);
}
整個游戲的環(huán)境我們用一個表格來實現(xiàn),最原始的 游戲引擎對象包括表格的行數(shù)(rows)、列數(shù)(cols)以及保存所有td的數(shù)組(allTds)三個屬性,和一個將環(huán)境添加到頁面的方法(start)。
2、食物對象的實現(xiàn)。
食物除了具有自身大小,顏色,位置等屬性外,還具有顯示,改變位置等方法,由于在游戲中可能不止出現(xiàn)一個食物,所以我們采用構(gòu)造函數(shù)的方式來創(chuàng)建食物對象。
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來保存食物的位置,然后當(dāng)達(dá)到一定要求時改變食物的位置,食物的位置是隨機(jī)的,所以需要創(chuàng)建兩個隨機(jī)數(shù),作為食物的位置。
3、蛇對象的實現(xiàn)
和食物一樣,蛇在游戲中可能也不止一條,所以我們也采用構(gòu)造函數(shù)的方式來定義對象。
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屬性保存蛇的運(yùn)動方向render方法將蛇顯示在游戲環(huán)境中。