DEV Community

Cover image for 鸿蒙NEXT开发案例:舒尔特方格
zhongcx
zhongcx

Posted on

1 1 1 1 1

鸿蒙NEXT开发案例:舒尔特方格

Image description

【引言】

舒尔特方格是一种用于训练注意力和视觉搜索能力的游戏。本文将介绍如何使用鸿蒙NEXT框架开发一个简单的舒尔特方格应用,帮助开发者理解鸿蒙NEXT的基本用法和组件。

【开发环境准备】

电脑系统:windows 10

开发工具:DevEco Studio NEXT Beta1 Build Version: 5.0.3.806

工程版本:API 12

真机:mate60 pro

语言:ArkTS、ArkUI

【项目结构】

在项目中,我们将创建一个名为Index的组件,负责实现舒尔特方格的逻辑和界面。该组件将包含以下主要部分:

状态管理:用于存储数字数组、当前索引、开始时间等信息。
初始化方格:生成1到25的数字并打乱顺序。
用户交互:处理用户点击事件,判断点击的数字是否正确。
界面构建:使用鸿蒙NEXT的组件构建用户界面。
【代码解析】

状态管理:使用@State装饰器定义组件的状态,便于管理和更新。
初始化方格:initGrid方法生成1到25的数字并随机打乱,设置游戏开始时间。
用户交互:通过onClick事件处理用户点击,判断点击的数字是否正确,并更新当前索引。
界面构建:使用Column和Flex组件构建方格布局,使用Text组件显示数字,并根据当前索引控制可见性。
【总结】

通过本案例,我们实现了一个简单的舒尔特方格游戏,展示了鸿蒙NEXT框架的基本用法。开发者可以在此基础上扩展更多功能,如增加难度、记录历史成绩等。希望本文能为您在鸿蒙开发中提供帮助!

【完整代码】

import { promptAction } from '@kit.ArkUI'; // 导入提示框组件

@Entry // 入口装饰器,标识该组件为应用的入口
@Component // 组件装饰器,定义一个组件
struct Index { // 定义一个结构体 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++) { // 循环25次
      this.numbers.push(i + 1); // 将1到25的数字添加到数组中
    }
    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; // 检查当前索引是否为25,表示完成
  }

  build() { // 构建组件界面
    Column({ space: 20 }) { // 创建一个垂直排列的列,间距为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%') // 设置整体高度
  }
}
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay