前言
在「猫猫大作战」中,游戏重置在「重新开始」和「返回主菜单」时触发。重置需要清理棋盘、归零得分、停止定时器、恢复初始状态。一个干净的重置实现能避免状态残留导致的 Bug。
一、引擎重置
exportclassGameEngine{reset():void{this.board=Array.from({length:GameConfig.BOARD_HEIGHT},()=>Array(GameConfig.BOARD_WIDTH).fill(null));this.score=0;this.combo={count:0,multiplier:1,lastMergeTime:0};this.pendingMerges=[];this.nextCatLevel=CatLevel.SMALL;}}二、页面重置
restartGame(){// 1. 清理定时器this.clearTimers();// 2. 重置引擎this.gameEngine.reset();// 3. 重置 UI 状态this.score=0;this.combo={count:0,multiplier:1,lastMergeTime:0};this.cats=[];this.gameTime=0;this.isNewHigh=false;this.overlayOpacity=0;// 4. 切换到游戏状态this.gameState=GameState.PLAYING;// 5. 启动定时器this.startTimers();}backToMenu(){this.clearTimers();this.gameEngine.reset();this.gameState=GameState.IDLE;}三、重置检查清单
| 项 | 操作 | 验证 |
|---|---|---|
| 棋盘 | 全部填 null | 全空 |
| 得分 | 归零 | score === 0 |
| 连击 | 重置 | count=0, multiplier=1 |
| 定时器 | 清除全部 | 无残留 setInterval |
| 猫咪列表 | 清空 | cats.length === 0 |
| 游戏时间 | 归零 | gameTime === 0 |
四、防止双重重置
privateisResetting:boolean=false;restartGame(){if(this.isResetting)return;// 防止重复点击this.isResetting=true;// ... 重置逻辑this.isResetting=false;}五、最佳实践
- 引擎和 UI 分别重置:引擎只重置数据,UI 层额外清理状态
- 定时器清理优先:重置前先清理定时器,防止重置过程中触发回调
- 防止重复重置:用标志位控制
- 重置后验证:可选调用
isGameOver()验证已恢复
总结
游戏重置需要清理棋盘、归零得分、停止定时器。核心要点:reset()引擎重置、restartGame()完整重置流程、 定时器清理防残留、 标志位防重复。
如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!
相关资源:
- GameEngine 源码
- 第 132 篇:game-over
- 第 134 篇:preferences
- 第 135 篇:rdb