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

相关新闻

不懂乐理也能创作商用歌曲?MELO 音乐生成实战:手把手教你打造版权自有神曲

不懂乐理也能创作商用歌曲?MELO 音乐生成实战:手把手教你打造版权自有神曲

前言:在这个时代,创意是唯一的门槛 如果我告诉你,现在创作一首发行级音质、包含人声演唱、编曲完整、且完整版权完全属于你的歌曲,只需要你会打字、会拍照、甚至会随口哼一段调调,你相信吗? 不需要你买昂…

2026/11/8 22:39:12 阅读更多 →
Mission Planner:从飞行控制到任务执行的3种实用解决方案

Mission Planner:从飞行控制到任务执行的3种实用解决方案

Mission Planner:从飞行控制到任务执行的3种实用解决方案 【免费下载链接】MissionPlanner Mission Planner Ground Control Station for ArduPilot (c# .net) 项目地址: https://gitcode.com/gh_mirrors/mi/MissionPlanner 当无人机操作从简单的遥控飞行升级…

2026/11/9 20:23:51 阅读更多 →
Audio Slicer终极指南:如何用智能静音检测实现400倍音频处理效率

Audio Slicer终极指南:如何用智能静音检测实现400倍音频处理效率

Audio Slicer终极指南:如何用智能静音检测实现400倍音频处理效率 【免费下载链接】audio-slicer A simple GUI application that slices audio with silence detection 项目地址: https://gitcode.com/gh_mirrors/aud/audio-slicer 还在为手动剪辑音频的繁琐…

2026/11/8 13:23:36 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/12 5:00:00 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/12 5:13:20 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/12 5:13:20 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/12 18:22:26 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/12 18:22:25 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/12 5:13:20 阅读更多 →

日新闻

周新闻

月新闻