package cz.davza.studentadventure.objects; import cz.davza.studentadventure.base.ItemCollectionBase; import cz.davza.studentadventure.enums.CommandState; import cz.davza.studentadventure.interfaces.IItem; import cz.davza.studentadventure.interfaces.IObservable; import cz.davza.studentadventure.interfaces.IObserver; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * The player's personal item inventory, with Observer support for change notifications. * *

Extends {@link ItemCollectionBase} with the full slot-based stacking logic, * and additionally implements {@link IObservable} so that external listeners * (such as a GUI panel) can react whenever the inventory contents change.

* *

Every call to {@link #Add} or {@link #Remove} automatically fires a * {@link CommandState#INVENTORY_CHANGE} notification to all registered observers * after delegating the operation to the superclass.

* * @see cz.davza.studentadventure.base.ItemCollectionBase * @see IObservable * @see IObserver */ public class PlayerInventory extends ItemCollectionBase implements IObservable { private final Map> observers = new HashMap<>(); /** * Creates a new inventory with the given number of bulk-unit capacity. * * @param size the total bulk capacity of this inventory */ public PlayerInventory(int size) { super(size); } /** * {@inheritDoc} * *

After the item is added (or partially added) by the superclass, * all observers registered for {@link CommandState#INVENTORY_CHANGE} are notified.

*/ @Override public int Add(IItem item, int count){ int result = super.Add(item, count); notifyObservers(CommandState.INVENTORY_CHANGE); return result; } /** * {@inheritDoc} * *

After the item is removed by the superclass, * all observers registered for {@link CommandState#INVENTORY_CHANGE} are notified.

*/ @Override public void Remove(String itemCode, int count) { super.Remove(itemCode, count); notifyObservers(CommandState.INVENTORY_CHANGE); } /** * {@inheritDoc} */ @Override public void addObserver(CommandState observedstate, IObserver o) { if (!observers.containsKey(observedstate)) observers.put(observedstate, new HashSet<>()); observers.get(observedstate).add(o); } /** * {@inheritDoc} */ @Override public void notifyObservers(CommandState notifiedState) { if (!observers.containsKey(notifiedState)) return; for (IObserver observer : observers.get(notifiedState)) { observer.update(); } } }