找对象
(1)蛇
属性: 长度、颜色、位置、头、移动方向
方法: 吃、移动、长大
(2)食物
属性: 大小、颜色、位置
方法: 改变位置
(3)游戏引擎
属性: 场景、蛇、食物
方法: 初始化、键盘控制、启动游戏、停止游戏
实现对象
游戏引擎
采用 字面量的形式 创建对象。 因为游戏引擎只有1个,采用这种方式会更合适些。代码如下:
定义 游戏引擎 对象
var gGamepower = {
rows : 10,//行数
cols : 15,//列数
Alltd: [],//储存所有td
food : null,//食物
snake: null,//蛇
timer : null,//定时器
//清空环境
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();
}
蛇
因为蛇可能需要手动创建,可能有多条蛇,所以 采用 构造函数的方式 更合适些。
(扩展) 蛇的颜色、蛇的大小、蛇的初始位置 都可以改,也可以继承的方式来实现不同的蛇
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里面有两个数组(数组里面包含数组)
需要再多练习