93 lines
2.4 KiB
GDScript
93 lines
2.4 KiB
GDScript
@tool
|
|
extends Inventory
|
|
|
|
## Base class for simple storages with no differentiation.
|
|
|
|
class_name Storage
|
|
|
|
## Amount of stacks that can be held in storage
|
|
@export var capacity : int:
|
|
set(value):
|
|
if value < 0:
|
|
return
|
|
if value == capacity:
|
|
return
|
|
capacity = value
|
|
get:
|
|
return capacity
|
|
|
|
## :3
|
|
@export_storage var internal_array : Array[InventorySlot] = []
|
|
|
|
func _init() -> void:
|
|
super()
|
|
deferred_init.call_deferred()
|
|
|
|
func deferred_init():
|
|
internal_array.resize(capacity)
|
|
for i in range(capacity):
|
|
internal_array[i] = InventorySlot.new()
|
|
|
|
## Finds first entry of item. Returns -1 if no item found
|
|
func find(item : Item) -> int:
|
|
for i in range(len(internal_array)):
|
|
if internal_array[i].held_item == item:
|
|
return i
|
|
return -1
|
|
|
|
## Tries to add an item into inventory. Returns not stored stack of item.
|
|
func add(stack: Stack, _context: InventoryContext = null) -> Stack:
|
|
var found_index : int = find(stack.held_item)
|
|
if found_index != -1:
|
|
stack_added.emit(stack,found_index)
|
|
internal_array[found_index].merge_stack(stack)
|
|
if stack.is_valid() == false:
|
|
return null
|
|
for i in range(len(internal_array)):
|
|
if internal_array[i].can_be_merged(stack.held_item):
|
|
stack_added.emit(stack,i)
|
|
internal_array[i].merge_stack(stack)
|
|
if stack.is_valid() == false:
|
|
return null
|
|
return stack
|
|
|
|
func can_add(item : Item = null, _context: InventoryContext = null) -> bool:
|
|
if item == null:
|
|
for i in range(capacity):
|
|
if internal_array[i].can_be_merged(item):
|
|
return true
|
|
return false
|
|
else:
|
|
for i in range(capacity):
|
|
if internal_array[i].can_be_merged(item):
|
|
return true
|
|
return false
|
|
|
|
## Tries to take first item. Returns null if no items in inventory
|
|
func pop() -> Stack:
|
|
for i in range(len(internal_array)):
|
|
if internal_array[i].held_item != null:
|
|
var extracted = internal_array[i].extract()
|
|
stack_taken.emit(extracted,i)
|
|
return extracted
|
|
return null
|
|
|
|
func peek() -> Stack:
|
|
for i in range(len(internal_array)):
|
|
if internal_array[i].held_item != null:
|
|
var peeked = internal_array[i].as_stack()
|
|
return peeked
|
|
return null
|
|
|
|
## Tries to take certain item from inventory. Returns null if no item found
|
|
func take(item: Item,amount: int) -> Stack:
|
|
var found = find(item)
|
|
if found == -1:
|
|
return null
|
|
var extracted = internal_array[found].extract_stack(amount)
|
|
stack_taken.emit(extracted,found)
|
|
return extracted
|
|
|
|
func refresh() -> void:
|
|
for i in range(capacity):
|
|
internal_array[i].updated = false
|