TinyAdventure/inventory.gd

90 lines
2.0 KiB
GDScript
Raw Permalink Normal View History

2024-07-09 22:33:38 +02:00
class_name Inventory
var _content:Array[ItemStack] = []
const INVENTORY_SIZE:int = 36
const INVENTORY_TOOL_START:int = 36 - 9
2024-07-09 22:33:38 +02:00
func _init() -> void:
clear()
2024-07-09 22:33:38 +02:00
func get_free_tool_stack_index() -> int:
for i:int in range(INVENTORY_TOOL_START, _content.size()):
if _content[i].count == 0:
return i
return -1
func get_free_item_stack_index() -> int:
for i:int in range(_content.size()):
if _content[i].count == 0:
return i
return -1
func add_item(item:ItemResource) -> bool:
for item_stack:ItemStack in _content:
if item_stack.count == 0:
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
# First try to put it into the tool stacks...
var item_stack_index:int = get_free_tool_stack_index()
# ... and if that failed try use the regular inventory.
if item_stack_index < 0:
item_stack_index = get_free_item_stack_index()
if item_stack_index >= 0:
_content[item_stack_index].item = item
_content[item_stack_index].count = 1
return true
return false
2024-07-09 22:33:38 +02:00
func remove_item(item:ItemResource):
for i in range(_content.size() - 1, -1, -1):
var item_stack:ItemStack = _content[i]
if item_stack.count == 0:
continue
if item_stack.item.resource_path == item.resource_path:
if item_stack.count > 1:
item_stack.count = item_stack.count - 1
return
2024-07-09 22:33:38 +02:00
func get_item_stacks() -> Array[ItemStack]:
2024-07-09 22:33:38 +02:00
return _content
func get_tool_item_stacks() -> Array[ItemStack]:
return _content.slice(_content.size() - 9)
2024-08-15 20:24:41 +02:00
func clear() -> void:
_content.clear()
_content.resize(INVENTORY_SIZE)
for i:int in range(_content.size()):
if _content[i] == null:
_content[i] = ItemStack.new()
2024-08-15 20:24:41 +02:00
func has_all(items:Array[ItemResource]) -> bool:
var needed:Array[ItemResource] = items.duplicate()
2024-07-09 22:33:38 +02:00
for item_stack:ItemStack in _content:
if item_stack.count == 0:
continue
for i in range (item_stack.count):
needed.erase(item_stack.item)
2024-07-09 22:33:38 +02:00
return needed.is_empty()