设置游戏细节
在 Game
类的原型方法中设置游戏细节:
// Game 类的原型方法,控制具体的游戏逻辑,确保重置 'this' 引用
Game.prototype = {
processClick: function (w, h) {
this.gb.processClick(w, h);
this.updateCounts();
if (this.gb.isGameWin()) {
this.gameEnd();
}
},
// 开始游戏
beginGame: function () {
this.setupLevel();
},
// 游戏结束
gameEnd: function () {
this.level++;
this.resetGame();
},
// 重置游戏,使用 bind 重定向 'this'
resetGame: function () {
$("#levelDescriptor").html("Enter Level " + this.level);
setTimeout(
function () {
this.setupLevel(); // 当 'this' 未重置时,它指向 window 对象
}.bind(this),
500
); // 使用 bind 将 'this' 从 window 重定向到实例
},
// 设置难度级别
setupLevel: function () {
this.gb = new GameBoard(this.level, this.level);
$(".board").html(""); // 清除游戏棋盘
this.gb.populate(); // 将所有方块重置为橙色
this.gb.renderBoard(); // 渲染游戏棋盘并创建方块
this.sh.setGridSize(this.level); // 控制游戏区域中方块的大小
this.updateCounts(); // 更新当前关卡显示
this.applyBindings(); // 翻转点击方块周围的方块颜色
},
// 更新当前关卡显示
updateCounts: function () {
$(".currLevel").html("Current Level: <b>" + this.level + "</b>");
},
applyBindings: function () {
var that = this; // 在 DOM 事件回调之前将 'this' 保存为变量以便于引用
$(".gamesquare").click(function () {
// 获取点击方块的位置
var cname = $(this).attr("class").split(" ")[1];
var coord = cname.substring(5).split("q");
var height = parseInt(coord[1]);
var width = parseInt(coord[0]);
that.processClick(width, height);
});
},
onNewGameClick: function () {
this.level = 1;
this.setupLevel();
}
};
这段代码通过添加原型方法扩展了 Game
构造函数的功能。这些方法定义了主要的游戏逻辑和交互。