// 砖类
var Brick = function(gamePanel) {
// 砖的dom元素
this.dom = null;
// 砖块所在的画布
this.gamePanel = gamePanel;
// 是否激活
this.isLive = true;
// 是否带有魔法棒
this.magic = null;
this.width = 28;
this.height = 28;
this.left = 0;
this.top = 0;
this.init();
}
Brick.prototype = {
// 初始化
init : function() {
this.dom = document.createElement("div");
this.dom.className = "brick";
},
// 为position: relative的Brick初始化位置
setPosition : function(x, y) {
this.left = x;
this.top = y;
},
// 为positon : relative的Brick初始化尺寸
setSize : function(width, height) {
this.width = width;
this.height = height;
},
// 初始化生成魔法棒
initMagic : function() {
var _this = this;
// 随机数
var random = parseInt(Math.random()*1000 + 1, 10);
var type = random % 5 == 0 ? "good" : random % 4 == 0 ? "bad" : "none";
// 新建一个魔法棒对象
var magic = new Magic(type);
this.magic = magic;
magic.initPosition(this);
// 将魔法棒添加进砖块中
this.gamePanel.appendChild(magic.dom);
magic.onEnd = function() {
_this.gamePanel.removeChild(magic.dom);
};
magic.animation(this.gamePanel.clientHeight);
},
// 击中后的动作
onEnd : function() {
this.isLive = false;
this.dom.className = "hideBrick";
this.initMagic();
}
}
魔法棒类代码即magic.js源文件实现如下:
复制代码 代码如下:
// 魔法棒类
var Magic = function(type) {
// Magic的dom元素
this.dom = null;
// Magic的dom信息
this.left = 0;
this.top = 0;
this.width = 0;
this.height = 0;
this.type = type;
this.init();
}
Magic.prototype = {
// 魔法棒类型
magicType : {
"good" : "magic",
"bad" : "shortMagic",
"none" : ""
},
// 每次移动位移
movepy : 3,
// 移动速度
movespeed : 20,
// 初始化魔法棒
init : function() {
this.dom = document.createElement("div");
this.dom.className = this.magicType[this.type];
//this.dom.style.display = "none";
this.width = parseInt(this.dom.style.width, 10);
this.height = parseInt(this.dom.style.height, 10);
},
// 魔法棒初始化位置
initPosition : function(brick) {
this.left = brick.left;
this.top = brick.top;
this.dom.style.left = this.left + "px";
this.dom.style.top = this.top + "px";
},
// 更新位置
update : function() {
this.dom.style.left = this.left + "px";
this.dom.style.top = this.top + "px";
},
// 魔法棒动画,height为游戏背景高度
animation : function(height) {
if (this.type == "none") {
return;
}
var _this = this;
// 向下移动函数
var downMove = function() {
_this.top = _this.top + _this.movepy;
_this.update();
// 判断魔法棒下移是否越界,是否击中stick
if (_this.top < height && !_this.isBeatStick()) {
setTimeout(downMove, _this.movespeed);
} else {
// 动画结束触发事件
_this.onEnd();
}
};
downMove();
},
// 动画结束触发事件,外部覆盖
onEnd : function() {},
// 魔法棒是否击中挡板以及击中后处理事件,外部覆盖
isBeatStick : function() {}
}
挡板类代码即stick.js源文件如下:
复制代码 代码如下: