TinyAdventure/inventory.gd

73 lines
1.5 KiB
GDScript

class_name Inventory
var _content:Array[ItemStack] = []
const INVENTORY_SIZE:int = 36
func _init() -> void:
_content.resize(INVENTORY_SIZE)
func get_free_item_stack_index() -> int:
for i:int in range(_content.size()):
if _content[i] == null:
return i
return -1
func add_item(item:Item) -> bool:
for item_stack:ItemStack in _content:
if item_stack == null:
continue
if item_stack.item.resource_path != item.resource_path:
continue
if item_stack.count < item_stack.item.max_stack_size:
item_stack.count = item_stack.count + 1
return true
var item_stack_index:int = get_free_item_stack_index()
if item_stack_index >= 0:
var item_stack:ItemStack = ItemStack.new()
item_stack.item = item
item_stack.count = 1
_content[item_stack_index] = item_stack
return true
return false
func remove_item(item:Item):
for i in range(_content.size() - 1, -1, -1):
var item_stack:ItemStack = _content[i]
if item_stack == null:
continue
if item_stack.item.resource_path == item.resource_path:
if item_stack.count > 1:
item_stack.count = item_stack.count - 1
else:
_content[i] = null
return
func get_item_stacks() -> Array[ItemStack]:
return _content
func clear() -> void:
_content.clear()
func has_all(items:Array[Item]) -> bool:
var needed:Array[Item] = items.duplicate()
for item_stack:ItemStack in _content:
if item_stack == null:
continue
for i in range (item_stack.count):
needed.erase(item_stack.item)
return needed.is_empty()