98 lines
2.0 KiB
GDScript
98 lines
2.0 KiB
GDScript
extends Resource
|
|
class_name Inventory
|
|
|
|
signal updated(inventory: Inventory)
|
|
|
|
@export var items: Array[Item] = []
|
|
@export var current_item_ind: int = 0
|
|
@export var size = 0 :
|
|
set(s):
|
|
size = s
|
|
items.resize(size)
|
|
updated.emit(self)
|
|
|
|
func _init(inventory_size: int = 1):
|
|
size = inventory_size
|
|
|
|
|
|
func get_best_available_slot_ind():
|
|
if items[current_item_ind] == null:
|
|
return current_item_ind
|
|
for i in items.size():
|
|
if items[i] == null:
|
|
return i
|
|
return current_item_ind
|
|
|
|
func set_current_item(new_ind: int):
|
|
if new_ind >= items.size():
|
|
return
|
|
|
|
if new_ind != current_item_ind:
|
|
current_item_ind = new_ind
|
|
updated.emit(self)
|
|
|
|
func change_current_item(ind_mod: int):
|
|
if items.size() == 0:
|
|
current_item_ind = 0
|
|
return
|
|
var new_ind: int = current_item_ind + ind_mod
|
|
new_ind = new_ind % items.size()
|
|
if new_ind < 0:
|
|
new_ind += items.size()
|
|
set_current_item(new_ind)
|
|
|
|
func add_item(item: Item):
|
|
var best_ind = get_best_available_slot_ind()
|
|
if best_ind != current_item_ind:
|
|
set_item(item, best_ind)
|
|
updated.emit(self)
|
|
return true
|
|
else:
|
|
return false
|
|
|
|
func set_item(item: Item, ind: int = 0) -> bool:
|
|
if ind < 0 || ind >= items.size():
|
|
return false
|
|
while len(items) <= ind:
|
|
items.append(null)
|
|
items[ind] = item
|
|
updated.emit(self)
|
|
return true
|
|
|
|
func get_item(ind: int = current_item_ind) -> Item:
|
|
if ind < 0 || items.size() <= ind:
|
|
return null
|
|
return items[ind]
|
|
|
|
func has_item(item: Item) -> bool:
|
|
return item in items
|
|
|
|
func remove_item(item: Item):
|
|
var ind = items.find(item)
|
|
if ind >= 0:
|
|
items[ind] = null
|
|
updated.emit(self)
|
|
|
|
func remove_item_at(ind: int = current_item_ind):
|
|
if items.size() <= ind:
|
|
return
|
|
|
|
items[ind] = null
|
|
updated.emit(self)
|
|
|
|
func remove_current_item():
|
|
remove_item_at()
|
|
|
|
func pop_item(ind: int = current_item_ind) -> Item:
|
|
if items.size() == 0:
|
|
return
|
|
|
|
var item_removed: Item = items[ind]
|
|
items[ind] = null
|
|
updated.emit(self)
|
|
return item_removed
|
|
|
|
func is_full():
|
|
for i in items:
|
|
if i == null : return false
|
|
return true |