【问题标题】:How to hold a limited collection of items for pseudo-RPG player equipment (dictionary?)如何为伪RPG玩家装备(字典?)
【发布时间】:2012-05-24 00:41:32
【问题描述】:

基本上,我正在创建一个伪 RPG 游戏,其中玩家拥有物品清单和角色玩偶(以了解当前装备了哪些物品)。

您建议处理当前装备物品集合的最佳方式是什么?

我目前拥有的是一个 EquipmentSlot 枚举,其中包含玩家装备物品的所有可能位置,我可以将其设置为玩家拥有的每个物品的属性。

public enum EquipmentSlot
{
    Head,
    Chest,
    Arms,
    Legs,
    Feet,
    OffHand,
    MainHand
}

然后我有一个字典,其中包含每个枚举作为键,在 Player 构造函数中将它们全部初始化为 null:

PlayerEquipment = new Dictionary<EquipmentSlot, Item>(7);
PlayerEquipment.Add(EquipmentSlot.Head, null);
PlayerEquipment.Add(EquipmentSlot.Chest, null);
PlayerEquipment.Add(EquipmentSlot.Arms, null);
PlayerEquipment.Add(EquipmentSlot.Legs, null);
PlayerEquipment.Add(EquipmentSlot.Feet, null);
PlayerEquipment.Add(EquipmentSlot.OffHand, null);
PlayerEquipment.Add(EquipmentSlot.MainHand, null);

但是当我编写这个代码时,我开始意识到它不起作用,因为我无法在我的 Player 的其他方法中将键作为枚举访问,因为它们是在构造函数中添加的。我不确定我还可以将它们添加到哪里,以供全班其他人使用。

我的字典方法是不是错误的方法来解决这个问题?

【问题讨论】:

  • “但是当我编写这个代码时,我开始意识到它不起作用,因为我无法在我的播放器的其他方法中访问密钥作为枚举,因为它们是在构造函数中添加的。”当然可以,你总是可以使用 PlayerEquipment[EquipmentSlot .Head] 来获取当前的 Helm 或者使用这条线来设置当前的 helm。总的来说,我认为这是一个合理的方法。

标签: c#


【解决方案1】:

我不确定你的意思:

我无法在我的播放器的其他方法中将密钥作为枚举访问, 因为它们是在构造函数中添加的

但是为什么不...

public class Player
{
    public Item EquipmentHead { get; set; }
    public Item EquipmentChest { get; set; }
    public Item EquipmentArms { get; set; }
    public Item EquipmentLegs { get; set; }
    public Item EquipmentFeet { get; set; }
    public Item EquipmentOffHand { get; set; }
    public Item EquipmentMainHand { get; set; }
}

附:我不会说您的 Dictionary 实现是 错误 方式,这只是一种替代方法,您可能更容易理解。

【讨论】:

    【解决方案2】:

    如果您将PlayerEquipment 定义为类成员,而不是局部变量,则您可以在类中的任何位置访问它:

    public class Player
    {
         public Dictionary<EquipmentSlot, Item> PlayerEquipment { get; set; }
    
         public Player()
         {
             PlayerEquipment = new Dictionary<EquipmentSlot, Item>(7);
             PlayerEquipment.Add(EquipmentSlot.Head, null);
             // ...
         }
    
         // In other methods, you can use this as needed... ie:
         public void DropItem(EquipmentSlot slot)
         {
             this.PlayerEquipment[slot] = null; // Remove the item here...
         }
    
         //....Rest of class
    

    请注意,如果您定义了您的类的enuminside,则在其他类中使用它时,您必须完全限定它,即:Player.EquipmentSlot.Head。但是,如果它在类之外定义,则可以使用 EquipmentSlot.Head(假设存在相同的命名空间或适当的 using 子句)。

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2019-08-10
      • 2022-07-31
      • 2022-12-19
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多