文档开发者中心
我的
|

HarmonyOS 5

骰子模拟器 + 掷骰历史记录

如何实现一个骰子模拟器呢?
点赞
收藏
回复
1
分享
举报
浏览195 发布于2025-12-16 07:23北京
全部评论
最多点赞
最新发布
最早发布

实现功能点:

  • 点击按钮掷出 1~6 的随机骰子
  • 带动画翻转效果(使用 animateTo)
  • 自动记录最近 10 次结果(带时间戳)
  • 历史记录自动保存到本地,重启不丢失

实现思路

1、使用preferences记录,将历史记录保存在本地。

2、通过animateTo实现一个基础动画效果。

实现效果

完整代码

收起
自动换行
深色代码主题
复制
import preferences from '@ohos.data.preferences';
import { common } from '@kit.AbilityKit';


interface RollRecord {
  value: number;
  time: string; // ISO 字符串,如 "14:30:22"
}

@Entry
@Component
struct DiceRoller {
  @State currentDice: number = 1;
  @State history: RollRecord[] = [];
  private prefs: preferences.Preferences = null!;
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;

  aboutToAppear() {
    preferences.getPreferences(this.context,'dice_app', (err, prefs) => {
      if (!err) {
        this.prefs = prefs;
        prefs.get('history', '[]', (err, value) => {
          if (!err) {
            try {
              this.history = JSON.parse(value as string);
            } catch (e) {
              console.warn('No valid history found');
            }
          }
        });
      }
    });
  }

  private saveHistory() {
    if (this.prefs) {
      this.prefs.put('history', JSON.stringify(this.history), () => {});
      this.prefs.flush(() => {});
    }
  }

  private rollDice() {
    // 获取当前时间(时:分:秒)
    const now = new Date();
    const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;

    const newValue = Math.floor(Math.random() * 6) + 1;

    // 触发动画:先翻转到背面(显示 7 - 当前值),再翻到新值
    animateTo(
      { duration: 200, curve: Curve.EaseInOut ,
      onFinish:()=>{
        animateTo(
          { duration: 200, curve: Curve.EaseInOut ,
          },
          () => {
            this.currentDice = newValue; // 显示新值
          }
        );
      }},
      () => {
        this.currentDice = 7 - this.currentDice; // 翻转中间态
      }
    )

    // 更新历史(最多保留10条)
    this.history.unshift({ value: newValue, time: timeStr });
    if (this.history.length > 10) {
      this.history.pop();
    }
    this.saveHistory();
  }

  build() {
    Column({ space: 25 }) {
      Text('🎲 骰子模拟器')
        .fontSize(28)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 30 })

      // 骰子显示区
      Column() {
        Text(this.currentDice.toString())
          .fontSize(60)
          .fontColor($r('sys.color.comp_background_list_card'))
          .width(120)
          .height(120)
          .borderRadius(20)
          .textAlign(TextAlign.Center)
          .backgroundColor('#333333')
      }
      .margin({ top: 20 })

      // 掷骰按钮
      Button('掷骰子')
        .width(200)
        .height(50)
        .fontSize(18)
        .backgroundColor($r('sys.color.brand'))
        .fontColor(Color.White)
        .onClick(() => {
          this.rollDice();
        })

      // 历史记录标题
      if (this.history.length > 0) {
        Text('最近记录')
          .fontSize(20)
          .fontWeight(FontWeight.Medium)
          .alignSelf(ItemAlign.Start)
          .margin({ top: 20, left: 30 })
      }

      // 历史列表
      List({ space: 8 }) {
        ForEach(
          this.history,
          (item: RollRecord) => {
            ListItem() {
              Row() {
                Text(`第 ${item.value} 点`)
                  .fontSize(16)
                  .layoutWeight(1)
                Text(item.time)
                  .fontSize(14)
                  .fontColor('#888')
              }
              .padding({ left: 16, right: 16, top: 12, bottom: 12 })
              .width('100%')
              .borderRadius(10)
              .backgroundColor('#F9F9F9')
            }
          }
        )
      }
      .width('90%')
      .layoutWeight(1)
      .margin({ bottom: 20 })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}
展开全部
1楼回复于2025-12-16 07:32 来自北京
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。