发布时间:2026/7/28 0:34:02
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

相关新闻

2026/7/28 0:34:02

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

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

2026/7/28 1:49:09

从继电器到智能灯控:技术架构、自动化场景与实战指南

如果你在智能家居领域工作,或者自己动手做过一些项目,可能遇到过这样的场景:朋友听说你懂技术,满怀期待地问:"能不能帮我做个智能灯控系统?" 结果你拿出一个继电器模块,接上台灯&…

2026/7/28 1:49:09

AI智能体手机与AI OS:系统级入口内置Agent能力

从应用层到系统层:AI Agent的下一站过去一年,大语言模型从云端走向终端,AI Agent的概念也从实验室走进消费电子领域。手机厂商不再满足于仅在应用层集成对话助手,而是将Agent能力下沉至操作系统底层。这一趋势标志着人机交互范式的…

2026/7/28 1:44:09

从零理解强化学习:核心概念、算法演进与PPO、DQN等实战入门

最近两年,AI领域的热点似乎总在快速切换,从大语言模型到多模态,再到如今的“具身智能”。很多刚接触这个领域的朋友,看着这些新名词,常常会陷入一种困惑:这些听起来高大上的概念,到底该怎么入手…

2026/7/27 9:04:58

PDF合并与动态水印的工程化方案:2026国内免费工具实测对比

一、背景与测试方案 在实际项目交付中,PDF文件合并与版权保护水印的叠加是一个高频但容易被低估的技术需求。典型的处理链路涉及:多源PDF的文件流合并、页面级水印渲染(含透明度混合与图层叠加)、输出文件体积控制。看似简单的操作…

2026/7/28 0:03:34

学术论文研究创新点梳理与核心价值提炼指南

本科毕业论文是大学四年最大的坎。开题报告憋一周写不出三页,找文献翻遍十几个网站还是缺关键资料,写正文卡壳半天憋不出一句话,降重改到凌晨三点结果逻辑全乱,答辩前一天PPT还没做完。别慌,亲测这四个工具能让你少熬半…

2026/7/28 0:03:34

开发商售楼处数字化升级怎么做?

房企的数字化转型投入正在快速增长,据行业数据显示,2025年房企数字化投入规模已突破800亿元,年复合增长率达35%。售楼处的数字化升级不是单一环节的改造,而是从“获客-展示-成交-服务”全链路的系统升级。数字化升级四步法第一步&…

2026/7/28 0:03:34

模型不再值钱之后,AI 编程工具在争什么

2026 年 7 月,AI 编程工具赛道发生了一个标志性转折:模型本身不再值钱了。当 Kimi K3 开源模型在编程基准上击败 GPT 和 Claude,当 GitHub Copilot 第一次把开源模型纳入选择器,当 OpenAI 把 Codex 并入 ChatGPT 做成三合一超级应…

2026/7/27 3:13:33

3个高效策略:快速掌握Axure中文界面配置

3个高效策略:快速掌握Axure中文界面配置 【免费下载链接】axure-cn Chinese language file for Axure RP. Axure RP 简体中文语言包。支持 Axure 11、10、9。不定期更新。 项目地址: https://gitcode.com/gh_mirrors/ax/axure-cn 还在为Axure RP的英文界面感…