找對象
(1)蛇
屬性: 長度丢间、顏色、位置驹针、頭烘挫、移動方向
方法: 吃、移動柬甥、長大
(2)食物
屬性: 大小饮六、顏色、位置
方法: 改變位置
(3)游戲引擎
屬性: 場景苛蒲、蛇卤橄、食物
方法: 初始化、鍵盤控制臂外、啟動游戲窟扑、停止游戲
實現(xiàn)對象
游戲引擎
采用 字面量的形式 創(chuàng)建對象。 因為游戲引擎只有1個漏健,采用這種方式會更合適些嚎货。代碼如下:
定義 游戲引擎 對象
var gGamepower = {
rows : 10,//行數(shù)
cols : 15,//列數(shù)
Alltd: [],//儲存所有td
food : null,//食物
snake: null,//蛇
timer : null,//定時器
//清空環(huán)境
clear: function () {
for (var i = 0;i<this.Alltd.length ;i++ )
{
for (j=0;j<this.Alltd[i].length ;j++ )
{
this.Alltd[i][j].className = ""
}
}
},
//游戲開始
start : function () {
//初始化游戲
var oTable = document.createElement("table")
for (i=0;i<gGamepower.rows ;i++ )
{ //Y
var oTr = document.createElement("tr")
var arr = []
for (j=0;j<gGamepower.cols ;j++ )
{ //X
var oTd = document.createElement("td")
oTr.appendChild(oTd)
arr.push(oTd)
}
oTable.appendChild(oTr)
this.Alltd.push(arr)
}
document.body.appendChild(oTable)
this.food = new Food();//顯示食物
this.snake = new Snake();//顯示蛇
//this.snake.fresh();
//定時器
gGamepower.timer=setInterval(function(){
gGamepower.clear()
gGamepower.snake.move()
gGamepower.food.show()
},500)
//鍵盤控制
this.keyContorl();
},
//定義鍵盤控制
keyContorl : function () {
window.onkeydown = function (e){
var a = e.keyCode;
if (a==37)
{//左
if (gGamepower.snake.direct == "left")
{
return;
}
gGamepower.snake.direct = "left"
}
else if (a==38)
{//上
if (gGamepower.snake.direct == "up")
{
return;
}
gGamepower.snake.direct = "up"
}
else if (a==39)
{//右
if (gGamepower.snake.direct == "right")
{
return;
}
gGamepower.snake.direct = "right"
}
else if (a==40)
{//下
if (gGamepower.snake.direct = "down")
{
return;
}
gGamepower.snake.direct = "down"
}
}
}
}
食物
function Food () {
//坐標
this.x = 0;
this.y = 0;
this.change()
}
//食物顯示
Food.prototype.show = function () {
gGamepower.Alltd[this.y][this.x].className = "food"
}
//隨機改變食物位置
Food.prototype.change = function () {
this.x = parseInt(Math.random()*gGamepower.cols);
this.y = parseInt(Math.random()*gGamepower.rows);
this.show();
}
蛇
因為蛇可能需要手動創(chuàng)建,可能有多條蛇蔫浆,所以 采用 構造函數(shù)的方式 更合適些厂抖。
(擴展) 蛇的顏色、蛇的大小克懊、蛇的初始位置 都可以改忱辅,也可以繼承的方式來實現(xiàn)不同的蛇
function Snake () {
this.arr = [
{x: 5, y: 2},
{x: 4, y: 2},
{x: 3, y: 2},
{x: 2, y: 2},
{x: 1, y: 2}
]
this.direct = "right"
}
Snake.prototype.fresh = function () {
for (i=0;i<this.arr.length ;i++ )
{
var x = this.arr[i].x
var y = this.arr[i].y
gGamepower.Alltd[y][x].className = "snake"
}
}
Snake.prototype.move = function () {
var x = this.arr[0].x
var y = this.arr[0].y
if (this.direct == "right")
{
x++
}
else if (this.direct == "down")
{
y++
}
else if (this.direct == "up")
{
y--;
}
else if (this.direct == "left")
{
x--;
}
if (x>=gGamepower.cols||y>=gGamepower.rows||x<0||y<0)
{
clearInterval(gGamepower.timer)
alert("GG~");
return ;
}
if (x == gGamepower.food.x && y == gGamepower.food.y)
{
this.arr.unshift({x: x, y: y});
gGamepower.food.change();
this.fresh();
return ;
}
this.arr.unshift({x:x,y:y})
this.arr.pop()
this.fresh()
}
總結
面向對象又更深的理解
*Alltd里面有兩個數(shù)組(數(shù)組里面包含數(shù)組)
需要再多練習