SHOP SYSTEM
The ShopSystem class handles shop items and slots, as well as transactions.
Slots -
Maintains a list of shop slots, inherited from the InventoryItemSlot class. tracks available slots, and places new items in appropriate slots.
Items -
Checks if an item exists in stock. Add, remove, or merge items based on the action.
Transactions -
Updates gold and inventory accordingly. Supports buying and selling with price markups.
⇅
[Serializable]
public class ShopSystem
{
[SerializeField] private List<ShopInventorySlot> _shopInventory;
[SerializeField] private int _availableGold;
[SerializeField] private float _buyMarkUp;
[SerializeField] private float _sellMarkUp;
#region Properties
public List<ShopInventorySlot> ShopInventory => _shopInventory;
public int AvailableGold => _availableGold;
public float BuyMarkUp => _buyMarkUp;
public float SellMarkUp => _sellMarkUp;
#endregion
// Constuctor
public ShopSystem(int shopSize, int goldAmount, float buyMarkUp, float sellMarkUp)
{
_availableGold = goldAmount;
_buyMarkUp = buyMarkUp;
_sellMarkUp = sellMarkUp;
SetShopInventorySize(shopSize);
}
private void SetShopInventorySize(int shopSize)
{
_shopInventory = new List<ShopInventorySlot>(shopSize);
for (int i = 0; i < shopSize; i++)
{
_shopInventory.Add(new ShopInventorySlot());
}
}
public void AddItemToShopInventory(InventoryItemData inventoryItemData, int amount)
{
if (ContainsItem(inventoryItemData, out ShopInventorySlot shopInventorySlot))
{
shopInventorySlot.AddToStack(amount);
return;
}
ShopInventorySlot availableShopInventorySlot = GetAvailableShopInventorySlot();
availableShopInventorySlot.AssignItemData(inventoryItemData, amount);
}
private ShopInventorySlot GetAvailableShopInventorySlot()
{
ShopInventorySlot availableShopInventorySlot = _shopInventory.FirstOrDefault(slot => slot.InventoryItemData == null);
if (availableShopInventorySlot == null)
{
availableShopInventorySlot= new ShopInventorySlot();
_shopInventory.Add(availableShopInventorySlot);
}
return availableShopInventorySlot;
}
// shop inventory has item - return shop inventory slot with item
public bool ContainsItem(InventoryItemData inventoryItemData, out ShopInventorySlot shopInventorySlot)
{
shopInventorySlot = _shopInventory.Find(slot => slot.InventoryItemData == inventoryItemData);
return shopInventorySlot != null;
}
public void BuyItem(InventoryItemData inventoryItemData, int amount)
{
if (!ContainsItem(inventoryItemData, out ShopInventorySlot shopInventorySlot)) return;
shopInventorySlot.RemoveFromStack(amount);
}
public void GetGold(int priceTotal)
{
_availableGold += priceTotal;
}
public void UseGold(int priceTotal)
{
_availableGold -= priceTotal;
}
public void SellItem(InventoryItemData inventoryItemData, int amount, int finalPrice)
{
AddItemToShopInventory(inventoryItemData, amount);
UseGold(finalPrice);
}
}