87 lines
2.2 KiB
GDScript
87 lines
2.2 KiB
GDScript
class_name ItemSystem extends Node
|
|
const Item = preload("res://scripts/Item/Item.gd");
|
|
const ItemStack = preload("res://scripts/Item/ItemStack.gd");
|
|
|
|
enum ItemSortType {
|
|
NAME,
|
|
TYPE
|
|
};
|
|
|
|
class ItemStackNameComparator:
|
|
static func _sort(a, b):
|
|
return a.item.getName().to_lower() < b.item.getName().to_lower()
|
|
|
|
class ItemStackTypeComparator:
|
|
static func _sort(a, b):
|
|
return a.item.getCategory() < b.item.getCategory()
|
|
|
|
# Constants
|
|
const ITEM_STACK_SIZE_MAX = 99;
|
|
var ITEM_POTION = preload("res://scripts/Item/Potion.gd").new();
|
|
var inventory:Array[ItemStack] = [];
|
|
|
|
# Methods
|
|
func addItem(item: Item, quantity: int = 1) -> void:
|
|
print("Adding ", quantity, "x ", item.getName());
|
|
if !item.isStackable():
|
|
# Item cannot be stacked, add each item to inv
|
|
for i in range(quantity):
|
|
inventory.append(ItemStack.new(item, 1))
|
|
return
|
|
|
|
# Check for existing stacks
|
|
for stack in inventory:
|
|
if stack.item != item or stack.quantity >= ITEM_STACK_SIZE_MAX:
|
|
continue
|
|
|
|
var spaceAvailable = ITEM_STACK_SIZE_MAX - stack.quantity
|
|
|
|
if quantity <= spaceAvailable:
|
|
stack.quantity += quantity;
|
|
return
|
|
|
|
stack.quantity = ITEM_STACK_SIZE_MAX;
|
|
quantity -= spaceAvailable;
|
|
|
|
# Add any remaining inventory as new stack.
|
|
while quantity > 0:
|
|
var newStackQuantity = min(quantity, ITEM_STACK_SIZE_MAX);
|
|
inventory.append(ItemStack.new(item, newStackQuantity));
|
|
quantity -= newStackQuantity;
|
|
|
|
func removeItem(item: Item, quantity: int) -> void:
|
|
var totalQuantity = 0
|
|
|
|
# Calculate total quantity of the item in the inventory
|
|
for stack in inventory:
|
|
if stack.item != item:
|
|
continue
|
|
totalQuantity += stack.quantity
|
|
|
|
if totalQuantity < quantity:
|
|
push_error("Not enough quantity to remove");
|
|
return
|
|
|
|
# Remove the quantity from the stacks
|
|
for stack in inventory:
|
|
if stack.item != item:
|
|
continue
|
|
|
|
if stack.quantity < quantity:
|
|
quantity -= stack.quantity
|
|
inventory.erase(stack)
|
|
|
|
stack.quantity -= quantity
|
|
if stack.quantity == 0:
|
|
inventory.erase(stack)
|
|
|
|
if quantity == 0:
|
|
return
|
|
|
|
func sortBy(by:ItemSortType) -> void:
|
|
match by:
|
|
ItemSortType.NAME:
|
|
inventory.sort_custom(ItemStackNameComparator._sort)
|
|
ItemSortType.TYPE:
|
|
inventory.sort_custom(ItemStackTypeComparator._sort)
|