class_name Inventory 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() const ITEM_STACK_SIZE_MAX = 99; var contents:Array[ItemStack] = []; func addItem(item:Item.ItemType, quantity: int = 1) -> void: if !Item.isStackable(item): # Item cannot be stacked, add each item to inv for i in range(quantity): contents.append(ItemStack.new(item, 1)) return # Check for existing stacks for stack in contents: 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); contents.append(ItemStack.new(item, newStackQuantity)); quantity -= newStackQuantity; func removeItem(item:Item.ItemType, quantity:int) -> void: var totalQuantity = 0 # Calculate total quantity of the item in the inventory for stack in contents: 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 contents: if stack.item != item: continue if stack.quantity < quantity: quantity -= stack.quantity contents.erase(stack) stack.quantity -= quantity if stack.quantity == 0: contents.erase(stack) if quantity == 0: return func removeStack(stack: ItemStack) -> void: self.removeItem(stack.item, stack.quantity); func hasItem(item:Item.ItemType, quantity: int = 1) -> bool: var totalQuantity = 0 for stack in contents: if stack.item != item: continue totalQuantity += stack.quantity if totalQuantity >= quantity: return true return false func sortBy(by:ItemSortType) -> void: match by: ItemSortType.NAME: contents.sort_custom(ItemStackNameComparator._sort) ItemSortType.TYPE: contents.sort_custom(ItemStackTypeComparator._sort) _: assert(false, "Invalid sort type: %s" % by)