样式,元素都有了,剩下的就是元素一动画效果,和简单的操作。
直接上代码吧。
移动方块:
// 水平移动方块的位置
this.hMove = function (step) {
if (this.container.check(this.x - -step, this.y, this.shape)) {
this.x += step;
this.show();
}
}
// 垂直移动方块位置
this.vMove = function (step) {
if (this.container.check(this.x, this.y - -step, this.shape)) {
this.y += step;
this.show();
} else {
this.container.fixShape(this.x, this.y, this.shape);
this.container.findFull();
this.refresh();
}
}
// 旋转方块
this.rotate = function () {
var newShape = [this.shape[1], 3 - this.shape[0], this.shape[3], 3 - this.shape[2], this.shape[5], 3 - this.shape[4], this.shape[7], 3 - this.shape[6]];
if (this.container.check(this.x, this.y, newShape)) {
this.shape = newShape;
this.show();
}
}
this.refresh();
}
方块落下后的改变:
// 用灰色方块替换红色方块,并在容器中记录灰色方块的位置
this.fixShape = function (x, y, shape) {
var t = new Tetris("d", x, y, shape);
for (var i = 0; i < 8; i += 2) this[(shape[i + 1] - -y) * 100 - -(shape[i] - -x)] = t.divs[i / 2];
}
// 遍历整个容器,判断是否可以消除
this.findFull = function () {
var s = 0;
for (var m = 0; m < row; m++) {
var count = 0;
for (var n = 0; n < col; n++) if (this[m * 100 + n]) count++;
if (count == col) {
s++;
this.removeLine(m);
}
}
this.score -= -this.calScore(s);
}
this.calScore = function (s) {
if (s != 0) return s - -this.calScore(s - 1)
else return 0;
}
// 消除指定一行方块
this.removeLine = function (row) {
// 移除一行方块
for (var n = 0; n < col; n++) document.body.removeChild(this[row * 100 + n]);
// 把所消除行上面所有的方块下移一行
for (var i = row; i > 0; i--) {
for (var j = 0; j < col; j++) {
this[i * 100 - -j] = this[(i - 1) * 100 - -j]
//数组中 消除行上的所有元素逐行下移 (等同于在数组改变位置)
if (this[i * 100 - -j])
//如果此下标有元素 让其定位到要显示的位置
this[i * 100 - -j].style.top = i * size + "px";
}
}
}
其中有挺多还是没有完全搞懂,还需要时间去做。