Flutter for OpenHarmony 实战:记忆棋游戏完整开发指南

欢迎加入开源鸿蒙跨平台社区:开源鸿蒙跨平台开发者社区

Flutter for OpenHarmony 实战:记忆棋游戏完整开发指南

文章目录

  • [Flutter for OpenHarmony 实战:记忆棋游戏完整开发指南](#Flutter for OpenHarmony 实战:记忆棋游戏完整开发指南)

摘要

记忆棋(Simon Says)是一款经典的记忆力训练游戏,玩家需要记住并重复越来越长的颜色序列。本文将详细介绍如何使用Flutter for OpenHarmony框架开发一款功能完整的记忆棋游戏。文章涵盖了序列生成算法、定时器协调、音效模拟、按钮高亮等核心技术点。通过本文学习,读者将掌握Flutter在节奏类游戏开发中的完整流程,了解定时器协调和状态同步的应用。


一、项目背景与功能概述

1.1 记忆棋游戏介绍

记忆棋(Simon Says)是一款考验记忆力的经典电子游戏:

  • 目标:尽可能长地记住并重复颜色序列
  • 规则
    1. 游戏展示一个颜色序列
    2. 玩家按相同顺序点击按钮
    3. 每回合增加一个新的颜色
    4. 出错则游戏结束

1.2 应用功能规划

功能模块 具体功能
四色按钮 青色、黄色、橙色、紫色
序列生成 随机生成颜色序列
序列展示 按顺序高亮显示
玩家输入 点击按钮重复序列
正误判断 实时检测玩家输入
关卡计数 记录当前关卡
最高分记录 保存最高关卡数

1.3 游戏配置

参数 说明
按钮数量 4 四种颜色
高亮时长 400ms 按钮亮起时间
序列间隔 800ms 颜色之间间隔
按钮布局 2×2 四个象限

二、数据模型设计

2.1 颜色定义

dart 复制代码
static const List<Color> _colors = [
  Color(0xFF00BCD4), // 青色 (左上 - 0)
  Color(0xFFFFEB3B), // 黄色 (右上 - 1)
  Color(0xFFFF9800), // 橙色 (左下 - 2)
  Color(0xFF9C27B0), // 紫色 (右下 - 3)
];

2.2 游戏状态

dart 复制代码
class _GamePageState extends State<GamePage> {
  // 游戏状态
  List<int> _sequence = [];          // 完整的颜色序列
  List<int> _playerSequence = [];    // 玩家的输入序列
  int _currentLevel = 0;             // 当前关卡
  int _highScore = 0;                // 最高分
  bool _isShowingSequence = false;   // 是否正在展示序列
  bool _isGameActive = false;        // 游戏是否进行中
  int? _highlightedButton;           // 当前高亮的按钮

  Timer? _sequenceTimer;             // 序列展示定时器
  Timer? _highlightTimer;            // 按钮高亮定时器
  final _random = Random();
}

三、游戏流程控制

3.1 开始游戏

dart 复制代码
void _startGame() {
  setState(() {
    _sequence = [];
    _playerSequence = [];
    _currentLevel = 0;
    _isGameActive = true;
  });
  _nextLevel();
}

3.2 进入下一关

dart 复制代码
void _nextLevel() {
  setState(() {
    _currentLevel++;
    _playerSequence = [];
  });

  // 添加新的颜色到序列
  _sequence.add(_random.nextInt(4));
  _showSequence();
}

算法流程

  1. 关卡数加1
  2. 清空玩家输入
  3. 随机选择一个新颜色
  4. 展示完整序列

四、序列展示算法

4.1 定时器展示序列

dart 复制代码
void _showSequence() {
  setState(() {
    _isShowingSequence = true;
  });

  int index = 0;
  _sequenceTimer = Timer.periodic(
    const Duration(milliseconds: 800),
    (timer) {
      if (index >= _sequence.length) {
        timer.cancel();
        setState(() {
          _isShowingSequence = false;
        });
        return;
      }

      _highlightButton(_sequence[index]);
      index++;
    }
  );
}

关键点

  • 使用Timer.periodic定期触发
  • 每800ms展示一个颜色
  • 展示完成后允许玩家输入

4.2 按钮高亮

dart 复制代码
void _highlightButton(int buttonIndex) {
  setState(() {
    _highlightedButton = buttonIndex;
  });

  _highlightTimer = Timer(
    const Duration(milliseconds: 400),
    () {
      setState(() {
        _highlightedButton = null;
      });
    }
  );
}

动画效果

  1. 立即设置高亮状态
  2. 400ms后取消高亮
  3. 使用AnimatedContainer实现平滑过渡

五、玩家输入处理

5.1 点击处理

dart 复制代码
void _onButtonTap(int buttonIndex) {
  // 防护检查
  if (!_isGameActive) return;
  if (_isShowingSequence) return;

  // 高亮按钮
  _highlightButton(buttonIndex);

  // 添加到玩家序列
  _playerSequence.add(buttonIndex);

  // 检查是否正确
  final currentIndex = _playerSequence.length - 1;
  if (_playerSequence[currentIndex] != _sequence[currentIndex]) {
    _gameOver();
    return;
  }

  // 检查是否完成当前关卡
  if (_playerSequence.length == _sequence.length) {
    Future.delayed(
      const Duration(milliseconds: 500),
      () {
        if (_isGameActive) {
          _nextLevel();
        }
      }
    );
  }

  setState(() {});
}

验证逻辑

  1. 检查游戏状态和展示状态
  2. 比较玩家输入与目标序列
  3. 错误则游戏结束
  4. 完成则进入下一关

5.2 游戏结束

dart 复制代码
void _gameOver() {
  _sequenceTimer?.cancel();
  _highlightTimer?.cancel();

  if (_currentLevel > _highScore) {
    _highScore = _currentLevel;
  }

  setState(() {
    _isGameActive = false;
    _isShowingSequence = false;
  });

  _showGameOverDialog();
}

六、UI界面实现

6.1 游戏面板布局

dart 复制代码
Widget _buildGameBoard() {
  return Stack(
    children: [
      // 中心圆
      Center(
        child: Container(
          width: 100,
          height: 100,
          decoration: BoxDecoration(
            color: Colors.grey.shade800,
            shape: BoxShape.circle,
            border: Border.all(
              color: Colors.grey.shade900,
              width: 4,
            ),
          ),
        ),
      ),

      // 四个象限按钮
      Positioned(top: 0, left: 0, child: _buildGameButton(0, 0)),
      Positioned(top: 0, right: 0, child: _buildGameButton(0, 1)),
      Positioned(bottom: 0, left: 0, child: _buildGameButton(1, 0)),
      Positioned(bottom: 0, right: 0, child: _buildGameButton(1, 1)),
    ],
  );
}

6.2 游戏按钮

dart 复制代码
Widget _buildGameButton(int row, int col) {
  final index = row * 2 + col;
  final isHighlighted = _highlightedButton == index;
  final color = _colors[index];

  return GestureDetector(
    onTap: () => _onButtonTap(index),
    child: AnimatedContainer(
      duration: const Duration(milliseconds: 100),
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        color: isHighlighted ? _lightenColor(color) : color,
        borderRadius: row == 0
          ? const BorderRadius.only(topLeft: Radius.circular(150))
          : const BorderRadius.only(bottomLeft: Radius.circular(150)),
        border: Border.all(
          color: Colors.grey.shade900,
          width: 4,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.3),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
    ),
  );
}

6.3 颜色变亮函数

dart 复制代码
Color _lightenColor(Color color) {
  final hsl = HSLColor.fromColor(color);
  return hsl.withLightness(0.8).toColor();
}

七、状态指示

7.1 游戏信息面板

dart 复制代码
Container(
  padding: const EdgeInsets.all(16),
  color: Colors.grey.shade100,
  child: Column(
    children: [
      Text(
        '当前关卡: $_currentLevel',
        style: const TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
        ),
      ),
      const SizedBox(height: 8),
      Text(
        _isShowingSequence ? '观察序列...' : '你的回合',
        style: TextStyle(
          fontSize: 18,
          color: _isShowingSequence ? Colors.blue : Colors.green,
          fontWeight: FontWeight.bold,
        ),
      ),
    ],
  ),
)

八、资源管理

8.1 定时器销毁

dart 复制代码
@override
void dispose() {
  _sequenceTimer?.cancel();
  _highlightTimer?.cancel();
  super.dispose();
}

重要 :在dispose方法中取消所有定时器。


九、总结

本文详细介绍了使用Flutter for OpenHarmony开发记忆棋游戏的完整过程,涵盖了以下核心技术点:

  1. 数据模型:颜色定义、序列存储、游戏状态
  2. 游戏流程:开始游戏、关卡递进、序列展示
  3. 序列展示:定时器协调、按钮高亮
  4. 玩家输入:点击处理、正误判断
  5. UI实现:堆叠布局、圆角按钮、动画效果
  6. 状态管理:展示状态、游戏状态
  7. 资源管理:定时器销毁、内存管理

这个项目展示了Flutter在节奏类游戏开发中的完整流程,特别是定时器协调和状态同步的应用。


欢迎加入开源鸿蒙跨平台社区 : 开源鸿蒙跨平台开发者社区

相关推荐
程序猿阿伟2 小时前
《游戏AI训练模拟环境:高保真可加速构建实战指南》
人工智能·游戏
飞羽殇情2 小时前
基于React Native鸿蒙跨平台开发构建完整电商预售系统数据模型,完成参与预售、支付尾款、商品信息展示等
react native·react.js·华为·harmonyos
Betelgeuse763 小时前
【Flutter For OpenHarmony】TechHub技术资讯界面开发
flutter·ui·华为·交互·harmonyos
铅笔侠_小龙虾3 小时前
Flutter 安装&配置
flutter
大雷神4 小时前
HarmonyOS智慧农业管理应用开发教程--高高种地-- 第33篇:应用打包、签名与发布
华为·harmonyos
mocoding4 小时前
使用已经完成鸿蒙化适配的Flutter本地持久化存储三方库shared_preferences让你的应用能够保存用户偏好设置、缓存数据等
flutter·华为·harmonyos·鸿蒙
zhuweisky6 小时前
ArkTS实现鸿蒙手机视频聊天、屏幕分享(HarmonyOS)
音视频·harmonyos·鸿蒙开发
无熵~6 小时前
Flutter入门
flutter
hudawei9966 小时前
要控制动画的widget为什么要with SingleTickerProviderStateMixin
flutter·mixin·with·ticker·动画控制