HarmonyOS应用开发实战:猫猫大作战-秒级计时器周期、gameTime 递增与格式化、暂停不计时间、计时器与主循环的分工

发布时间:2026/7/28 0:33:35
HarmonyOS应用开发实战:猫猫大作战-秒级计时器周期、gameTime 递增与格式化、暂停不计时间、计时器与主循环的分工 前言上一篇我们搭好了 100ms 物理主循环——猫咪下落、合并、得分都靠它驱动。但游戏里还有个独立时钟从开局到结束的累计时间gameTime。这个时钟和主循环分离——主循环 100ms 更新物理计时器 1000ms 递增秒数两者职责不同。本篇以「猫猫大作战」timeTimer为锚点把秒级计时器周期、gameTime 递增与格式化、暂停不计时间、计时器与主循环的分工四大要点讲透。提示本系列不讲 ArkTS 基础语法与环境搭建假设你已跟完第 1–33 篇。本篇是阶段二第四篇。一、场景拆解游戏计时回顾「猫猫大作战」计时器第 33 篇// 来源entry/src/main/ets/pages/Index.ets startGame() this.timeTimer setInterval(() { if (this.gameState GameState.PLAYING) { this.gameTime; // ← 仅 PLAYING 时递增 } }, 1000); // ← 1000ms 1s 周期HUD 显示时间第 11 篇// 来源entry/src/main/ets/pages/Index.ets GameHUD() Text(this.formatTime(this.gameTime)) .fontSize(18) .fontWeight(FontWeight.Medium) .fontColor(#2C3E50)格式化函数// 来源entry/src/main/ets/pages/Index.ets formatTime(seconds: number): string { const min Math.floor(seconds / 60); const sec seconds % 60; return ${min.toString().padStart(2, 0)}:${sec.toString().padStart(2, 0)}; }核心问题为什么计时器是 1000ms 而不是 100msgameTime只在PLAYING时执行怎么实现「暂停不计时间」formatTime怎么把秒数转成mm:ss二、秒级计时器周期2.1 为什么是 1000ms周期gameTime 精度HUD 刷新频率适合100ms0.1 秒10 次/秒精密计时赛车1000ms1 秒1 次/秒回合游戏本项目2000ms2 秒0.5 次/秒慢节奏策略本项目选 1000ms 的原因显示精度只需秒——HUD 显示mm:ss小数位无意义。减少 State 改动——每秒改一次gameTime比每 100ms 改一次省 10 倍重渲染。节省 CPU——1000ms 触发一次回调开销极低。关键经验计时器精度匹配显示精度——HUD 只显示秒计时器就用 1000ms别为了「精度」用 100ms。2.2 计时器与主循环的分工// 主循环100ms 更新物理猫下落、合并、得分 this.gameLoopTimer setInterval(() { if (this.gameState ! GameState.PLAYING) return; this.cats this.gameEngine.updateCats(); this.score this.gameEngine.getScore(); this.combo this.gameEngine.getCombo(); if (this.gameEngine.isGameOver()) { this.endGame(); } }, 100); // 计时器1000ms 递增秒数独立时钟 this.timeTimer setInterval(() { if (this.gameState GameState.PLAYING) { this.gameTime; } }, 1000);职责对比定时器周期职责改的 StategameLoopTimer100ms物理更新cats、score、combo、nextCatLeveltimeTimer1000ms时间累计gameTimespawnTimer2000ms自动生成猫cats、nextCatLevel第 35 篇关键经验每个定时器单一职责——别把计时和物理混在一个 setInterval 里否则周期冲突100ms 物理还是 1000ms 物理。三、gameTime 递增与暂停3.1 暂停时不递增this.timeTimer setInterval(() { if (this.gameState GameState.PLAYING) { // ← 仅 PLAYING 时 this.gameTime; } }, 1000);执行流程gameState PLAYING→ 每 1000msgameTimeHUD 时间正常走。pauseGame()→gameState PAUSED→ 下次回调if不通过gameTime不变。resumeGame()→gameState PLAYING→ 下次回调if通过续期计时。实战经验「暂停不计时间」用 if 守卫比 clearInterval 重建更简洁——和主循环的暂停策略保持一致第 33 篇。3.2 结束时停止计时endGame() { this.gameState GameState.GAME_OVER; this.maxCombo this.gameEngine.getMaxCombo(); this.mergeCount this.gameEngine.getMergeCount(); this.highestLevel this.gameEngine.getHighestLevel(); if (this.score this.highScore) { this.highScore this.score; } this.clearTimers(); // ← clearInterval 三个定时器 }结束流程endGame()把gameState GAME_OVER。clearTimers()调用clearInterval(this.timeTimer)彻底停止计时器。gameTime保留最终值在 GameOverOverlay 显示「总用时」。关键经验结束用 clearInterval暂停用 if 守卫——结束要彻底清理不再恢复暂停要能续期。3.3 重新开始重置 gameTimestartGame() { this.clearTimers(); this.gameEngine.reset(); this.gameState GameState.PLAYING; this.score 0; this.cats []; this.gameTime 0; // ← 重置时间 this.combo { count: 0, multiplier: 1, lastMergeTime: 0 }; this.nextCatLevel this.gameEngine.getNextCatLevel(); /* ... 三个定时器 */ }重新开始流程clearTimers()清旧定时器。this.gameTime 0重置时间。重建三个定时器从 0 开始计时。四、formatTime 格式化4.1 秒数转 mm:ss// 来源entry/src/main/ets/pages/Index.ets formatTime(seconds: number): string { const min Math.floor(seconds / 60); // 分钟数 const sec seconds % 60; // 剩余秒数 return ${min.toString().padStart(2, 0)}:${sec.toString().padStart(2, 0)}; }拆解片段含义示例seconds 125Math.floor(seconds / 60)分钟数Math.floor(125 / 60) 2seconds % 60剩余秒数125 % 60 5toString().padStart(2, 0)补零到 2 位2.padStart(2, 0) 02拼接mm:ss02:054.2 padStart 补零5.padStart(2, 0) // → 05 12.padStart(2, 0) // → 12已够 2 位不补 .padStart(2, 0) // → 00API 说明String.prototype.padStart(targetLength, padString)——把字符串填充到targetLength长度不足部分用padString补。关键经验时间显示必补零——5:3看起来像5 分 3 秒05:03才标准。4.3 不同格式化方案// 方案 1mm:ss本项目 1 小时 formatTime(seconds: number): string { const min Math.floor(seconds / 60); const sec seconds % 60; return ${min.toString().padStart(2, 0)}:${sec.toString().padStart(2, 0)}; } // 方案 2hh:mm:ss≥ 1 小时 formatTimeLong(seconds: number): string { const hr Math.floor(seconds / 3600); const min Math.floor((seconds % 3600) / 60); const sec seconds % 60; return ${hr.toString().padStart(2, 0)}:${min.toString().padStart(2, 0)}:${sec.toString().padStart(2, 0)}; } // 方案 3纯秒数短局游戏 formatTimeSimple(seconds: number): string { return ${seconds}s; }方案显示适合mm:ss02:05本项目 1 小时hh:mm:ss01:02:05长时间挂机纯秒数125s短局 60 秒实战经验消除类游戏一局通常 2-10 分钟用mm:ss最合适。五、计时器与 UI 的协同5.1 HUD 显示时间Builder GameHUD() { Row() { Column() { Text(得分).fontSize(11).fontColor(#95A5A6) Text(this.score.toString()) .fontSize(22).fontWeight(FontWeight.Bold).fontColor(#2C3E50) }.alignItems(HorizontalAlign.Start) Spacer() if (this.combo.count 1) { Row() { Text( x${this.combo.multiplier}) .fontSize(18).fontWeight(FontWeight.Bold).fontColor(#E74C3C) } .padding({ left: 12, right: 12, top: 4, bottom: 4 }) .backgroundColor(rgba(231, 76, 60, 0.1)) .borderRadius(16) } Spacer() // 时间栏本篇重点 Column() { Text(时间).fontSize(11).fontColor(#95A5A6) Text(this.formatTime(this.gameTime)) // ← 读 State gameTime .fontSize(18).fontWeight(FontWeight.Medium).fontColor(#2C3E50) }.alignItems(HorizontalAlign.End) } .width(100%).padding({ left: 20, right: 20, top: 12, bottom: 8 }) }依赖关系时间栏Text依赖State gameTime每秒gameTime触发重渲染。5.2 GameOverOverlay 显示总用时Builder GameOverOverlay() { Column() { /* ... 标题、得分 ... */ // 统计数据含时间 Row() { this.StatItem(时间, this.formatTime(this.gameTime)) // ← 显示总用时 this.StatItem(合并, ${this.mergeCount}次) this.StatItem(最高连击, x${this.maxCombo}) } .width(100%) .justifyContent(FlexAlign.SpaceEvenly) .margin({ bottom: 8 }) /* ... */ } }关键经验gameTime在结束时保留最终值GameOverOverlay 复用formatTime显示总用时——一份格式化函数两处用。六、踩坑提示6.1 计时器周期写成 100ms// ❌ 错误100ms 周期gameTime 飞涨 this.timeTimer setInterval(() { this.gameTime; }, 100); // 每 100ms 11 秒 10显示飞涨 // ✅ 正确1000ms 周期 this.timeTimer setInterval(() { if (this.gameState GameState.PLAYING) { this.gameTime; } }, 1000);6.2 忘记 if 守卫暂停时还在计时// ❌ 错误没 if 守卫暂停时 gameTime 还在涨 this.timeTimer setInterval(() { this.gameTime; // 即使 PAUSED 也 1 }, 1000); // ✅ 正确if 守卫仅 PLAYING 时递增 this.timeTimer setInterval(() { if (this.gameState GameState.PLAYING) { this.gameTime; } }, 1000);6.3 忘记 startGame 重置 gameTime// ❌ 错误重开没重置时间延续上一局 startGame() { this.clearTimers(); this.gameState GameState.PLAYING; this.score 0; // 忘了 this.gameTime 0 this.timeTimer setInterval(() { this.gameTime; }, 1000); } // 第二局从第一局的结束时间继续计 // ✅ 正确重置 gameTime startGame() { this.clearTimers(); this.gameState GameState.PLAYING; this.score 0; this.gameTime 0; // 重置 this.timeTimer setInterval(() { /* ... */ }, 1000); }6.4 padStart 浏览器兼容// ArkTS/iOS/Android 都支持 padStart但老版本可能不支持 5.padStart(2, 0) // 现代环境 OK // 兼容写法手动补零 const pad (n: number): string n 10 ? 0${n} : ${n}; return ${pad(min)}:${pad(sec)};七、调试技巧console.info打 gameTime计时器回调里 log追每秒递增。暂停计时间排查暂停后看 log 是否停没停说明忘加 if 守卫。时间不重置排查重开后看 gameTime 是否从 0 开始没归零说明忘加this.gameTime 0。格式化错误排查临时加console.info(this.formatTime(this.gameTime))看输出是否正确。八、性能与最佳实践计时器精度匹配显示精度——HUD 显示秒就用 1000ms 周期。计时与物理分离——别混在一个 setInterval周期冲突。暂停用 if 守卫结束用 clearInterval——暂停要续期结束要清理。startGame 重置 gameTime——避免延续上局时间。formatTime 用 padStart 补零——5:3改05:03才标准。formatTime 复用——HUD 和 GameOverOverlay 共用一份。总结本篇我们从计时器切入掌握了秒级 1000ms 周期的选择依据、暂停用 if 守卫不递增、formatTime 秒数转 mm:ss、计时器与主循环的分工四大要点并给出了完整计时器代码。核心要点精度匹配显示暂停用 if 守卫结束用 clearInterval重开重置 gameTime。下一篇我们将拆解 spawnTimer——猫咪自动生成调度。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源「猫猫大作战」项目源码本仓库entry/src/main/ets/pages/Index.etssetInterval/clearInterval 官方文档Math.floor/Math.round 数学 API 参考String.padStart 字符串 API 参考开源鸿蒙跨平台社区HarmonyOS 开发者官方文档首页系列索引本仓库articles/INDEX.md