Inventory System
Almost every game has an inventory: a backpack in an RPG, ammo and keys in a shooter, resources in a strategy game. It looks simple until the rules arrive: items stack up to a limit, the bag has a fixed number of slots, some items are unique, picking up more than fits must leave the rest on the ground, and the UI must always show the truth. This lesson builds a slot-based inventory with those rules.
Item definitions vs item instances
Separate what an item is (its definition: name, max stack, value) from how many you have (a stack in a slot). Definitions are shared data loaded once; the inventory stores only ids and counts. This is the same split as in Save & Load: a save file stores potion: 3, never the potion's whole definition.
using System;
using System.Collections.Generic;
var items = new Dictionary<string, ItemDef>
{
["potion"] = new("Health Potion", MaxStack: 5, Value: 25),
["arrow"] = new("Arrow", MaxStack: 99, Value: 1),
["sword"] = new("Iron Sword", MaxStack: 1, Value: 120),
};
foreach (var (id, def) in items)
Console.WriteLine(quot;{id,-7} {def.Name,-14} stacks to {def.MaxStack,2}, worth {def.Value,3} gold");
record ItemDef(string Name, int MaxStack, int Value);potion Health Potion stacks to 5, worth 25 gold
arrow Arrow stacks to 99, worth 1 gold
sword Iron Sword stacks to 1, worth 120 gold
A slot inventory with stacking
Add fills existing stacks of the same item first, then empty slots, and returns how many items didn't fit. The caller decides what to do with the leftovers (leave them on the ground, show "inventory full"). Remove takes from the last stacks first, so partial stacks get used up.
using System;
using System.Collections.Generic;
using System.Linq;
var defs = new Dictionary<string, ItemDef>
{
["potion"] = new("Health Potion", 5, 25),
["arrow"] = new("Arrow", 99, 1),
["sword"] = new("Iron Sword", 1, 120),
};
var bag = new Inventory(slotCount: 4, defs);
Report("pick up 3 potions", bag.Add("potion", 3));
Report("pick up 4 potions", bag.Add("potion", 4));
Report("pick up 150 arrows", bag.Add("arrow", 150));
Report("pick up a sword", bag.Add("sword", 1));
Console.WriteLine(bag);
Console.WriteLine(quot;drink 2 potions: {(bag.Remove("potion", 2) ? "ok" : "not enough")}");
Console.WriteLine(quot;drink 9 potions: {(bag.Remove("potion", 9) ? "ok" : "not enough")}");
Console.WriteLine(bag);
Console.WriteLine(quot;total value: {bag.TotalValue()} gold");
void Report(string action, int leftover) =>
Console.WriteLine(quot;{action,-20} -> {(leftover == 0 ? "all fit" : quot;{leftover} left on the ground")}");
record ItemDef(string Name, int MaxStack, int Value);
class Slot { public string Id = null; public int Count; }
class Inventory
{
readonly Slot[] slots;
readonly Dictionary<string, ItemDef> defs;
public Inventory(int slotCount, Dictionary<string, ItemDef> defs)
{
slots = Enumerable.Range(0, slotCount).Select(_ => new Slot()).ToArray();
this.defs = defs;
}
public int Add(string id, int amount)
{
int max = defs[id].MaxStack;
foreach (var s in slots.Where(s => s.Id == id && s.Count < max)) // 1. top up existing stacks
{
int moved = Math.Min(amount, max - s.Count);
s.Count += moved; amount -= moved;
if (amount == 0) return 0;
}
foreach (var s in slots.Where(s => s.Id == null)) // 2. fill empty slots
{
int moved = Math.Min(amount, max);
s.Id = id; s.Count = moved; amount -= moved;
if (amount == 0) return 0;
}
return amount; // 3. what didn't fit
}
public int Count(string id) => slots.Where(s => s.Id == id).Sum(s => s.Count);
public bool Remove(string id, int amount)
{
if (Count(id) < amount) return false; // all or nothing: never remove half
foreach (var s in slots.AsEnumerable().Reverse().Where(s => s.Id == id))
{
int taken = Math.Min(amount, s.Count);
s.Count -= taken; amount -= taken;
if (s.Count == 0) s.Id = null;
if (amount == 0) break;
}
return true;
}
public int TotalValue() => slots.Where(s => s.Id != null).Sum(s => s.Count * defs[s.Id].Value);
public override string ToString() =>
string.Join(" | ", slots.Select((s, i) => s.Id == null ? quot;[{i}] empty" : quot;[{i}] {s.Id} x{s.Count}"));
}pick up 3 potions -> all fit
pick up 4 potions -> all fit
pick up 150 arrows -> all fit
pick up a sword -> 1 left on the ground
[0] potion x5 | [1] potion x2 | [2] arrow x99 | [3] arrow x51
drink 2 potions: ok
drink 9 potions: not enough
[0] potion x5 | [1] empty | [2] arrow x99 | [3] arrow x51
total value: 275 gold
Rules worth copying
- Return what didn't fit.
Addnever silently deletes items. Losing a rare drop because the bag was full is the kind of bug players remember. - All-or-nothing removal. Crafting "3 wood + 1 rope" must check all ingredients before removing any; otherwise a failed craft eats half the materials.
RemovechecksCountfirst for the same reason. - One source of truth. The UI reads from the inventory; it never keeps its own copy of the counts. Raise an event (
InventoryChanged) after each change and let the UI redraw (see Game Events). - Ids, not objects. Slots hold ids and counts, which makes saving, networking and sorting trivial.
Variations
| Style | Example games | Change to the model |
|---|---|---|
| Slots + stacks | Minecraft, most survival games | this lesson |
| Weight limit | Skyrim, many RPGs | Add checks total weight instead of slots |
| Grid (Tetris-like) | Diablo, Resident Evil 4 | items have a width and height; Add searches for a free rectangle |
| Unlimited list | many JRPGs | no slots; a dictionary id → count is enough |
Test yourself
Why does Add return the number of items that didn't fit?
- For debugging only
- So the caller can leave the leftovers in the world instead of silently deleting them
- To compute the value
- It is required by C#
The bag has an arrow stack of 99/99 and one empty slot. You pick up 120 arrows. What happens?
- All 120 fit in the empty slot
- 99 go into the empty slot and 21 are left over
- Nothing fits
- The existing stack grows to 219
Why should crafting check all ingredients before removing any?
- To be faster
- So a failed craft doesn't consume part of the materials
- Because Remove is slow
- To sort the inventory