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

51 lines
2 KiB
GDScript

extends StructureBehaviour
@onready var inventory : InOutInventory = structure_parent.inventory
@export var selected_recipe : Recipe
func _ready() -> void:
inventory.stack_added.connect(check_for_recipe)
switch_recipe.call_deferred(selected_recipe)
func switch_recipe(recipe: Recipe) -> void:
selected_recipe = recipe
inventory.input_capacity = len(selected_recipe.ingridients)
inventory.resize()
for i in range(len(selected_recipe.ingridients)):
inventory.input_array[i].filter = selected_recipe.ingridients[i].item
func _tick(_current_tick : int) -> void:
if inventory.output_slot.amount <= 0:
return
inventory.refresh()
var output : Structure = get_output_structure()
if output == null:
return
var transfer_context : InventoryContext = InventoryContext.new(structure_parent,output,structure_parent.relative_tile_as_global(get_output_position()))
if output.inventory.can_add(inventory.output_slot.held_item,transfer_context):
inventory.output_slot.merge_stack(output.inventory.add(inventory.output_slot.extract(),transfer_context))
func get_output_structure() -> Structure:
var rotated = Vector2(1.5,-0.5).rotated(structure_parent.direction)
return structure_parent.get_relative(rotated+Vector2(0.5,0.5))
func get_output_position() -> Vector2:
return to_global(Vector2(1.5,-0.5).rotated(structure_parent.direction)+Vector2(0.5,0.5))
func check_for_recipe(_stack : Stack, _position : int) -> void:
var flag:bool = false
for i in range(inventory.input_capacity):
if inventory.input_array[i].can_be_merged(_stack.held_item):
flag = true
if flag == false:
return
for i in range(len(selected_recipe.ingridients)):
if inventory.input_array[i].amount < selected_recipe.ingridients[i].amount:
return
craft()
func craft() -> void:
for i in range(len(selected_recipe.ingridients)):
inventory.input_array[i].extract_stack(selected_recipe.ingridients[i].amount)
inventory.output_slot.merge_stack(Stack.new(selected_recipe.result.item,selected_recipe.result.amount))