DOD Inventory Implementation Example

 avatar
unknown
csharp
2 years ago
2.3 kB
2
Indexable
public struct ItemData
{
    public int itemId;
    public string name;
    public ItemType itemType;
    // Add any other necessary properties
}

public enum ItemType
{
    Consumable,
    Equipment,
    // Add other item types as needed
}

public interface IItemAction
{
    void PerformAction();
}

public class ConsumableItemAction : IItemAction
{
    public void PerformAction()
    {
        // Perform action specific to consumable item
    }
}

public class EquipmentItemAction : IItemAction
{
    public void PerformAction()
    {
        // Perform action specific to equipment item
    }
}

public struct InventoryItem
{
    public int itemId;
    public int quantity;
    public IItemAction itemAction;
    // Add any other necessary properties
}

public class InventorySystem
{
    private ItemData[] itemDataArray;
    private InventoryItem[] inventoryItems;
    private Dictionary<int, int> itemIndexMap;

    public InventorySystem(ItemData[] itemData)
    {
        itemDataArray = itemData;
        inventoryItems = new InventoryItem[itemData.Length];
        itemIndexMap = new Dictionary<int, int>();

        for (int i = 0; i < itemData.Length; i++)
        {
            itemIndexMap[itemData[i].itemId] = i;
        }
    }

    public void AddItem(int itemId, int quantity)
    {
        int itemIndex;
        if (itemIndexMap.TryGetValue(itemId, out itemIndex))
        {
            inventoryItems[itemIndex].quantity += quantity;
        }
        else
        {
            // Item not found in the inventory, handle accordingly
        }
    }

    public void RemoveItem(int itemId, int quantity)
    {
        int itemIndex;
        if (itemIndexMap.TryGetValue(itemId, out itemIndex))
        {
            inventoryItems[itemIndex].quantity -= quantity;
            // Handle case when quantity becomes zero or negative
        }
        else
        {
            // Item not found in the inventory, handle accordingly
        }
    }

    public void UseItem(int itemId)
    {
        int itemIndex;
        if (itemIndexMap.TryGetValue(itemId, out itemIndex))
        {
            inventoryItems[itemIndex].itemAction.PerformAction();
        }
        else
        {
            // Item not found in the inventory, handle accordingly
        }
    }
}
Editor is loading...