鸿蒙应用示例:舒尔特方格游戏实现

实现目标
1. 随机生成:每次游戏开始时,自动打乱数字顺序。
2. 计时功能:记录玩家完成游戏所需的时间。
3. 交互反馈:点击数字时提供交互反馈,包括正确与否的提示。
4. 重新开始:游戏完成后可重新开始。
完整示例
import { promptAction } from '@kit.ArkUI'; @Entry @Component struct Index { @State numbers: number[] = []; @State currentIndex: number = 0; //用于判断用户点击是否正确 @State timeStart: number = 0; @State widthItem: number = 120 @State marginItem: number = 5 // 初始化舒尔特方格 initGrid() { this.numbers = [] for (let i = 0; i < 25; i++) { this.numbers.push(i + 1) } this.shuffleArray(JSON.parse(JSON.stringify(this.numbers))); this.currentIndex = 0; this.timeStart = Date.now() } // 随机打乱数组 shuffleArray(array: number[]) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * 25); let temp = array[i] array[i] = array[j] array[j] = temp } this.numbers = array } // 判断是否完成 isCompleted() { return this.currentIndex === 25; } build() { Column({ space: 20 }) { Flex({ wrap: FlexWrap.Wrap }) { ForEach(this.numbers, (item: number, index: number) => { Text(`${item}`) .width(`${this.widthItem}lpx`) .height(`${this.widthItem}lpx`) .margin(`${this.marginItem}lpx`) .fontSize(`${this.widthItem/2}lpx`) .textAlign(TextAlign.Center) .backgroundColor(Color.Orange) .fontColor(Color.White) .borderRadius(5) .visibility(item <= this.currentIndex ? Visibility.Hidden : Visibility.Visible) .onClick(() => { if (this.numbers[index] === this.currentIndex + 1) { this.currentIndex++; if (this.isCompleted()) { console.info('完成!'); promptAction.showDialog({ title: `用时`, message: `${((Date.now() - this.timeStart) / 1000).toFixed(3)}秒`, buttons: [ { text: '重新开始', color: '#ffa500' } ], }).then(()=>{ this.initGrid(); }) } } else { console.info('错误的顺序!'); } }) }) } .width(`${(this.widthItem + this.marginItem * 2) * 5}lpx`) .height(`${(this.widthItem + this.marginItem * 2) * 5}lpx`) // 开始按钮 Button('开始') .width('50%') .height('10%') .onClick(() => { this.initGrid(); console.info('游戏开始'); }); } .width('100%') .height('100%') } }
代码解析
1. 初始化舒尔特方格
initGrid() { this.numbers = []; for (let i = 0; i < 25; i++) { this.numbers.push(i + 1); } this.shuffleArray(JSON.parse(JSON.stringify(this.numbers))); this.currentIndex = 0; this.timeStart = Date.now(); }
这段代码的作用是在游戏开始时初始化数字数组,并调用 shuffleArray 方法来随机打乱数字顺序。同时,重置当前索引为0,并记录开始时间。
2. 随机打乱数组
shuffleArray(array: number[]) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * 25); let temp = array[i]; array[i] = array[j]; array[j] = temp; } this.numbers = array; }
使用 Fisher-Yates 洗牌算法来打乱数组中的数字顺序。为了保证原数组不被修改,这里先复制了一份数组。
3. 判断是否完成
isCompleted() { return this.currentIndex === 25; }
检查当前索引是否等于25,如果等于则表示游戏完成。
4. 构建UI布局
• Flex布局:使用 Flex 布局来创建一个5×5的网格,其中每个格子是一个 Text 组件,显示数字。
• ForEach循环:遍历 numbers 数组,在每个格子上绑定点击事件。
• 点击事件处理:当点击某个数字时,检查是否为正确的顺序,如果是则更新当前索引,并检查是否完成游戏。若完成,则弹出对话框显示所用时间,并允许重新开始。
5. 开始按钮
在页面底部放置一个“开始”按钮,点击后初始化游戏状态。
结语
通过上述代码实现了一个基本的舒尔特方格游戏,这不仅有助于训练用户的注意力集中度,还可以作为学习HarmonyOS应用开发的一个良好示例。你可以在此基础上进一步扩展功能,如增加难度级别、记录最佳成绩等,使游戏更具趣味性和挑战性。