class_name DialogueEngine extends RefCounted const ConditionEngineType = preload("res://scripts/domain/combat/condition_engine.gd") const DialogueStateType = preload("res://scripts/domain/dialogue/dialogue_state.gd") var condition_engine: ConditionEngine func _init(new_condition_engine: ConditionEngine = null) -> void: condition_engine = new_condition_engine if new_condition_engine != null else ConditionEngineType.new() func start(definition: Dictionary, context: Dictionary) -> DialogueState: return DialogueStateType.new(definition) func visible_choices(state: DialogueState, context: Dictionary) -> Array[Dictionary]: if state == null or state.is_over(): return [] var choices: Array[Dictionary] = [] for option: Variant in state.current_node().get("options", []): if option is Dictionary and _conditions_met(option, context): choices.append(option) return choices func choose(state: DialogueState, visible_index: int, context: Dictionary) -> Dictionary: var choices := visible_choices(state, context) if state == null or visible_index < 0 or visible_index >= choices.size(): return {"accepted": false, "reason": &"invalid_choice", "applications": [], "opens_shop": false} var choice := choices[visible_index] var applications := condition_engine.apply_effects(choice.get("effects", []), context) var next_node := StringName(choice.get("goto", "")) if bool(choice.get("end", false)): state.ended = true elif next_node == &"__SHOP__": state.node_id = next_node state.ended = true elif not next_node.is_empty() and state.definition.get("nodes", {}).has(String(next_node)): state.node_id = next_node applications.append_array(condition_engine.apply_effects(state.current_node().get("on_enter", []), context)) else: state.ended = true return { "accepted": true, "choice": choice, "applications": applications, "opens_shop": next_node == &"__SHOP__", "ended": state.is_over(), "node_id": state.node_id, } func _conditions_met(choice: Dictionary, context: Dictionary) -> bool: if choice.has("condition"): var condition: Variant = choice.condition if not condition is Dictionary or not condition_engine.evaluate(condition, context): return false var conditions: Variant = choice.get("conditions", []) return condition_engine.evaluate_all(conditions, context) if conditions is Array else false