You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter游戏设计中如何创建可复用类?

解决方案

1. 先明确你的枚举与数据类结构(示例)

假设你的基础定义是这样的:

enum GridTileClass { goblin, dragon, knight, empty }

class GridTileData {
  final GridTileClass type;
  final String name;
  final int hp;
  final int attack;
  final int defense;
  // 这里补上你那20+个属性

  const GridTileData({
    required this.type,
    required this.name,
    required this.hp,
    required this.attack,
    required this.defense,
    // 对应其他属性的必填参数
  });
}

2. 创建预定义实例的统一管理类

把所有需要复用的tile实例提前定义好,存放在一个静态类里,后续直接调用:

class TileTemplates {
  // 预定义哥布林实例,一次性填完所有20+属性
  static const goblin = GridTileData(
    type: GridTileClass.goblin,
    name: "哥布林",
    hp: 30,
    attack: 8,
    defense: 2,
    // 这里补上其他所有属性的固定值
  );

  // 预定义巨龙实例
  static const dragon = GridTileData(
    type: GridTileClass.dragon,
    name: "巨龙",
    hp: 200,
    attack: 50,
    defense: 25,
    // 其他属性值...
  );

  // 预定义空格子实例(初始化棋盘时用)
  static const empty = GridTileData(
    type: GridTileClass.empty,
    name: "空地",
    hp: 0,
    attack: 0,
    defense: 0,
    // 其他属性值...
  );
}

3. 初始化棋盘并直接赋值

现在你可以像你想要的那样,直接用预定义实例给棋盘格子赋值:

// 初始化一个3x3的棋盘,默认填充空格子
List<List<GridTileData>> newBoard = List.generate(
  3, 
  (row) => List.generate(3, (col) => TileTemplates.empty)
);

// 直接给指定格子赋值预定义实例
newBoard[0][1] = TileTemplates.goblin;
newBoard[1][1] = TileTemplates.dragon;

4. 可选优化:添加copyWith方法支持局部修改

如果需要基于预定义实例修改个别属性(比如给哥布林加buff),可以在GridTileData里添加copyWith方法:

class GridTileData {
  // 原有属性与构造函数...

  GridTileData copyWith({
    GridTileClass? type,
    String? name,
    int? hp,
    int? attack,
    int? defense,
    // 对应其他属性的可选参数
  }) {
    return GridTileData(
      type: type ?? this.type,
      name: name ?? this.name,
      hp: hp ?? this.hp,
      attack: attack ?? this.attack,
      defense: defense ?? this.defense,
      // 其他属性用原实例值或传入的新值
    );
  }
}

// 使用示例:创建一个血量提升的哥布林
var buffedGoblin = TileTemplates.goblin.copyWith(hp: 45);
newBoard[0][2] = buffedGoblin;

内容的提问来源于stack exchange,提问作者Bisclavret

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:25:17