delurbelako/scripts/structures/splitter.gd
2025-10-17 18:22:49 +05:00

47 lines
1.5 KiB
GDScript

extends StructureBehaviour
@onready var inventory: SplitterInventory = structure_parent.inventory
var split: bool = true
func get_upper_next() -> Vector2:
return Vector2.RIGHT.rotated(structure_parent.direction)
func get_down_next() -> Vector2:
var base = get_upper_next()
return base + base.rotated(PI/2).abs()
func _tick(current_tick: int) -> void:
if current_tick % 8 != 0:
return
inventory.refresh()
if has_non_empty(inventory.upper_array) == false and has_non_empty(inventory.down_array) == false:
return
var transfer_upper = try_transfer(get_upper_next(),false)
var transfer_down = try_transfer(get_down_next(),true)
if transfer_upper or transfer_down or not (transfer_down or transfer_upper):
inverse_split()
func try_transfer(point:Vector2,down:bool) -> bool:
var next :Structure = structure_parent.get_relative(point)
var array : Array[InventorySlot] = inventory.down_array if split != down else inventory.upper_array
if next == null:
return false
var context : InventoryContext = InventoryContext.new(structure_parent,next,to_global(point))
for i in range(inventory.capacity):
if array[i].amount > 0 and next.inventory.can_add(array[i].held_item,context):
var stack = array[i].extract()
stack = next.inventory.add(stack,context)
array[i].merge_stack(stack)
return true
return false
func inverse_split() -> void:
split = not split
func has_non_empty(array:Array[InventorySlot]) -> bool:
for i in range(inventory.capacity):
if array[i].amount > 0:
return true
return false