64 lines
2.1 KiB
GDScript
64 lines
2.1 KiB
GDScript
class_name InventoryState
|
|
extends RefCounted
|
|
|
|
const ItemInstanceType = preload("res://scripts/domain/items/item_instance.gd")
|
|
|
|
var capacity: int
|
|
var items: Array[ItemInstance] = []
|
|
|
|
func _init(new_capacity: int = 20) -> void:
|
|
capacity = maxi(0, new_capacity)
|
|
|
|
func add_item(item: ItemInstance) -> Dictionary:
|
|
if item == null or item.definition == null or not item.definition.is_valid():
|
|
return _result(false, &"invalid_item", item)
|
|
if item.definition.stackable:
|
|
var existing := _stack_for(item.definition.id)
|
|
if existing != null:
|
|
existing.quantity += item.quantity
|
|
return _result(true, &"", item, existing.instance_id)
|
|
if items.size() >= capacity:
|
|
return _result(false, &"capacity", item)
|
|
items.append(item)
|
|
return _result(true, &"", item)
|
|
|
|
func pick_up_ground_item(floor: FloorState, cell: Vector2i) -> Dictionary:
|
|
if floor == null or not floor.ground_items.has(cell) or floor.ground_items[cell].is_empty():
|
|
return _result(false, &"no_ground_item")
|
|
var item: ItemInstance = floor.ground_items[cell][0]
|
|
var result := add_item(item)
|
|
if not bool(result.accepted):
|
|
return result
|
|
floor.ground_items[cell].remove_at(0)
|
|
if floor.ground_items[cell].is_empty():
|
|
floor.ground_items.erase(cell)
|
|
return result
|
|
|
|
func to_dict() -> Dictionary:
|
|
var serialized: Array[Dictionary] = []
|
|
for item in items:
|
|
serialized.append(item.to_dict())
|
|
return {"capacity": capacity, "items": serialized}
|
|
|
|
static func from_dict(data: Dictionary, catalog: ContentCatalog) -> InventoryState:
|
|
var inventory := InventoryState.new(int(data.get("capacity", 20)))
|
|
for item_data: Dictionary in data.get("items", []):
|
|
var item := ItemInstanceType.from_dict(item_data, catalog)
|
|
if item.definition.is_valid():
|
|
inventory.add_item(item)
|
|
return inventory
|
|
|
|
func _stack_for(item_id: StringName) -> ItemInstance:
|
|
for item in items:
|
|
if item.definition.id == item_id:
|
|
return item
|
|
return null
|
|
|
|
func _result(accepted: bool, reason: StringName = &"", item: ItemInstance = null, stack_merged_into: StringName = &"") -> Dictionary:
|
|
return {
|
|
"accepted": accepted,
|
|
"reason": reason,
|
|
"item": item,
|
|
"stack_merged_into": stack_merged_into,
|
|
}
|