【鸿蒙入门】零基础也能做:猜数字小游戏教程(附完整代码)

【鸿蒙入门】零基础也能做:猜数字小游戏教程(附完整代码) 【鸿蒙入门】零基础也能做猜数字小游戏教程附完整代码还在愁鸿蒙开发怎么入门来跟着这篇教程手把手带你做一个猜数字游戏包教包会写在前面HarmonyOS NEXT 是华为的新系统ArkTS 是它的开发语言。今天我们用最简单的方式带你完成第一个小游戏。先看我们要做什么系统随机出个 1-100 的数字你猜系统告诉你是大了还是小了猜中显示次数可以再来一局很简单吧开始一、创建项目1.1 用 DevEco Studio 创建打开 DevEco Studio选择 “Empty Ability”项目名填 “MyApplication”一路 Next1.2 项目结构MyApplication/ └── entry/src/main/ets/pages/ └── Index.ets # 主界面我们就改这个二、什么是状态管理鸿蒙的 UI 是「响应式」的意思就是数据变了界面自动更新。看这段代码StatedisplayTime:string25:00Text(this.displayTime)// 显示 25:00当我们改变displayTime的值界面上的文字会自动变化不需要手动刷新。记住用State包着的变量变了 UI 就会跟着变。三、开始写代码3.1 定义状态变量EntryComponentstruct Index{StatetargetNumber:number0// 答案1-100StateuserInput:string// 输入框内容Stateattempts:number0// 猜了几次StatehintText:string输入 1-100 之间的数字StatehintColor:string#888888StateisGameOver:booleanfalse// 游戏结束没StateguessHistory:GuessRecord[][]// 猜测历史StateshowCelebration:booleanfalse// 显示庆祝动画}解释一下targetNumber系统随机生成的答案玩家看不到userInput绑定输入框玩家输入什么就是什么attempts猜了几次每次提交加 1isGameOver猜中后变成 true禁用输入3.2 定义历史记录类型interfaceGuessRecord{guess:number// 猜的数result:string// 结果正确/大了/小了resultColor:string// 颜色}放在文件开头struct Index之前。四、核心逻辑4.1 新游戏newGame():void{// 随机生成 1-100 的数this.targetNumberMath.floor(Math.random()*100)1// 重置所有状态this.userInputthis.attempts0this.hintText输入 1-100 之间的数字this.hintColor#888888this.isGameOverfalsethis.guessHistory[]this.showCelebrationfalse}怎么随机Math.random()生成 0-1 的小数Math.random() * 100得到 0-99 的小数Math.floor()向下取整得到 0-99 的整数1后变成 1-1004.2 提交猜测submitGuess():void{constguessparseInt(this.userInput)// 先检查输入对不对if(isNaN(guess)||guess1||guess100){this.hintText⚠️ 请输入 1-100 的整数this.hintColor#E67E22return// 不继续往下走了}this.attempts// 次数加一// 判断大小if(guessthis.targetNumber){// 猜中了this.hintText 恭喜就是${this.targetNumber}用了${this.attempts}次this.hintColor#27AE60// 绿色this.isGameOvertruethis.showCelebrationtrue}elseif(guessthis.targetNumber){// 小了this.hintText${guess}小了this.hintColor#E74C3C// 红色}else{// 大了this.hintText${guess}大了this.hintColor#E74C3C// 红色}// 记录到历史新的在前面this.guessHistory[{guess:guess,result:guessthis.targetNumber?✅ 正确:(guessthis.targetNumber?⬆ 小了:⬇ 大了),resultColor:guessthis.targetNumber?#27AE60:#E74C3C},...this.guessHistory// 把原来的历史展开]this.userInput// 清空输入框}流程把输入转成数字检查是不是 1-100 的整数判断大小更新提示文字和颜色记录到历史清空输入框五、界面搭建5.1 整体布局build(){Column(){Scroll(){Column({space:12}){// 标题Text( 猜数字).fontSize(28).fontWeight(FontWeight.Bold)Text(猜一个 1 ~ 100 之间的数字).fontSize(14).fontColor(#999999)// 这里放输入卡片、快捷按钮、历史记录...}.width(100%).alignItems(HorizontalAlign.Center)// 居中}}.width(100%).height(100%).backgroundColor(#F0F2F5)// 浅灰背景}布局结构最外层Column占满全屏Scroll可以滚动防止小屏幕显示不下内部Column垂直排列居中对齐5.2 输入卡片Column({space:16}){// 提示文字Text(this.hintText).fontSize(18).fontColor(this.hintColor).textAlign(TextAlign.Center).width(100%)// 已猜次数if(this.attempts0){Text(已猜${this.attempts}次).fontSize(13).fontColor(#AAAAAA)}// 输入框 按钮Row({space:10}){TextInput({text:this.userInput,placeholder:输入数字...}).type(InputType.Number)// 弹数字键盘.maxLength(3)// 最多3位.fontSize(20).height(50).layoutWeight(1)// 占剩余空间.backgroundColor(#F5F5F5).borderRadius(12).onChange((val:string){this.userInputval// 输入时更新}).onSubmit((){if(!this.isGameOver){this.submitGuess()// 回车提交}}).enabled(!this.isGameOver)// 结束后禁用// 提交/重开按钮Button(this.isGameOver?:↵).width(50).height(50).backgroundColor(this.isGameOver?#3498DB:#2D3436).borderRadius(12).fontColor(#FFFFFF).onClick((){if(this.isGameOver){this.newGame()}else{this.submitGuess()}})}.width(100%)// 猜中后的庆祝动画if(this.showCelebration){Text(✨ ⭐ ✨).fontSize(24).textAlign(TextAlign.Center).width(100%)}}.width(85%).padding(20).backgroundColor(#FFFFFF).borderRadius(16).shadow({radius:6,color:#1A000000,offsetY:3})要点InputType.Number弹数字键盘方便输入maxLength(3)最多 3 位100 也是 3 位enabled(!this.isGameOver)游戏结束后禁用输入框5.3 快捷按钮不想输数字点击快捷按钮BuilderquickButton(value:number):void{Button(${value}).width(58).height(36).backgroundColor(#EEEEEE).borderRadius(8).fontSize(14).fontColor(#555555).onClick((){if(!this.isGameOver){this.userInputvalue.toString()}})}使用Row({space:8}){this.quickButton(10)this.quickButton(25)this.quickButton(50)this.quickButton(75)this.quickButton(90)}5.4 历史记录if(this.guessHistory.length0){Column({space:8}){Text( 猜测记录).fontSize(16).fontColor(#666666)Column({space:4}){ForEach(this.guessHistory,(item:GuessRecord){Row(){// 序号Text(#${this.guessHistory.length-this.guessHistory.indexOf(item)}).fontSize(14).fontColor(#AAAAAA).width(36)// 猜的数字Text(${item.guess}).fontSize(18).fontWeight(FontWeight.Bold).width(60)// 结果Text(item.result).fontSize(15).fontColor(item.resultColor)}.width(100%).padding(8).backgroundColor(#FAFAFA).borderRadius(10)})}}.width(85%)}序号怎么算新记录在数组开头索引是 0所以序号 数组长度 - 索引六、初始化游戏aboutToAppear():void{this.newGame()// 组件加载时开始新游戏}七、常见问题Q1输入框清不掉A确保onChange里更新了userInput.onChange((val:string){this.userInputval})Q2历史记录序号反了A用数组长度 - 索引this.guessHistory.length-this.guessHistory.indexOf(item)Q3庆祝动画不显示A要用if包着if(this.showCelebration){Text(✨ ⭐ ✨)}Q4结束后还能猜A禁用输入框.enabled(!this.isGameOver)八、运行效果九、学到了什么状态管理State让数据变化自动更新界面条件渲染根据状态显示/隐藏组件列表渲染ForEach遍历数组显示列表输入处理数字键盘、验证、清空组件封装Builder复用按钮组件十、还能加什么难度选择简单1-50、困难1-500计时功能记录猜了多久最佳记录保存最少次数提示功能猜太多次给点帮助有问题欢迎评论区留言