Quest menu closeable

This commit is contained in:
2025-05-07 11:16:08 -05:00
parent f940247a48
commit 55081f777a
11 changed files with 168 additions and 141 deletions

102
scripts/Item/Inventory.gd Normal file
View File

@@ -0,0 +1,102 @@
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, quantity: int = 1) -> void:
if !item.isStackable():
# 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, 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, 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)

View File

@@ -0,0 +1 @@
uid://dgunweso54t2t