Files
aetherbound-guild/runtime/fg3/contract2_battle_service.gd
T

375 lines
13 KiB
GDScript

class_name FG3Contract2BattleService
extends RefCounted
const Content = preload("res://fg3/content_registry.gd")
const State = preload("res://fg3/run_state.gd")
const PLAN_IDS := ["interrupt_pulse", "fortify_links", "stagger_actions", "reorder_line"]
const BOSS_PLAN_IDS := ["interrupt_pulse_family", "durable_links_stagger"]
const PRIMARY_PLAN := {
1: "stagger_actions", 2: "reorder_line", 3: "fortify_links",
4: "reorder_line", 5: "interrupt_pulse", 6: "stagger_actions",
7: "reorder_line", 8: "interrupt_pulse", 9: "reorder_line",
10: "fortify_links", 11: "fortify_links", 12: "stagger_actions",
}
const SECONDARY_PLAN := {
1: "fortify_links", 2: "stagger_actions", 3: "reorder_line",
4: "interrupt_pulse", 5: "fortify_links", 6: "reorder_line",
7: "stagger_actions", 8: "fortify_links", 9: "stagger_actions",
10: "stagger_actions", 11: "interrupt_pulse", 12: "interrupt_pulse",
}
const ARTIFACT_PLAN_BONUS := {
"AR-009": {"interrupt_pulse": 2, "fortify_links": -1},
"AR-010": {"reorder_line": 2, "stagger_actions": -1},
"AR-011": {"fortify_links": 2, "reorder_line": -1},
"AR-012": {"stagger_actions": 2, "interrupt_pulse": -1},
"AR-013": {"fortify_links": 2, "reorder_line": 1},
"AR-014": {"reorder_line": 2, "fortify_links": -1},
"AR-015": {"stagger_actions": 2, "fortify_links": 1},
}
var source := State.new()
var valid := false
var error_code := "invalid_state"
var catalog: Dictionary = Content.snapshot()
var event_log: Array[Dictionary] = []
var event_tick := 0
func _init(snapshot_value: Dictionary) -> void:
valid = source.restore_snapshot(snapshot_value)
if valid and String(source.current_run.phase) in ["contract2_prepared", "contract2_boss_prepared"]:
error_code = ""
else:
valid = false
error_code = "contract2_prepared_state_required"
func run_to_terminal(plan_id: String) -> Dictionary:
if not valid:
return {"ok": false, "code": error_code}
if String(source.current_run.phase) == "contract2_boss_prepared":
return _run_boss(plan_id)
return _run_route(plan_id)
static func route_plan_score(
market_index: int,
risk: int,
plan_id: String,
artifact_id: String,
equipment_matches: int,
hp_ratio: float
) -> int:
if market_index not in PRIMARY_PLAN or plan_id not in PLAN_IDS or risk < 0 or risk > 2:
return -999
var score := 15
if plan_id == String(PRIMARY_PLAN[market_index]):
score += 6
elif plan_id == String(SECONDARY_PLAN[market_index]):
score += 4
else:
score -= 8
score += int(ARTIFACT_PLAN_BONUS.get(artifact_id, {}).get(plan_id, 0))
score += mini(3, maxi(0, equipment_matches))
score -= 2 * risk
score -= int(floor(float(market_index - 1) / 4.0))
if hp_ratio < 0.45:
score -= 2
return score
func _run_route(plan_id: String) -> Dictionary:
if plan_id not in PLAN_IDS:
return {"ok": false, "code": "unknown_plan"}
var run: Dictionary = source.current_run
var route: Dictionary = run.pending_encounter
var market_index := int(route.round_index)
var primary := String(PRIMARY_PLAN[market_index])
var secondary := String(SECONDARY_PLAN[market_index])
_reset_events()
var artifact_id := _artifact_id(run)
var artifact_modifier := _artifact_plan_modifier(artifact_id, plan_id)
var equipment_matches := _equipment_match_count(run, route.response_tags)
var score := route_plan_score(
market_index,
int(route.risk),
plan_id,
artifact_id,
equipment_matches,
_hp_ratio(run)
)
var outcome := "victory" if score >= 15 else "defeat"
var actors := _route_actor_results(
run,
route,
plan_id == primary,
plan_id == secondary,
equipment_matches,
maxi(0, artifact_modifier),
outcome
)
var fallen_ids := _fallen_ids(actors)
_add_event("battle_started", String(run.run_id), String(route.route_id), {
"round_index": market_index,
"risk": int(route.risk),
"plan_id": plan_id,
"primary_plan": primary,
"secondary_plan": secondary,
"artifact_id": artifact_id,
})
_add_event("pulse_linked", String(route.pulse_disclosure.pulse_family), "line", {
"indices": Array(route.pulse_disclosure.linked_indices).duplicate(),
"linked_count": int(route.pulse_disclosure.linked_count),
})
for wave in route.wave_order:
_add_event("wave_entered", String(wave.enemy_id), "line", {"scheduled_tick": int(wave.tick)})
_add_event("plan_response", plan_id, String(route.route_id), {
"primary": plan_id == primary,
"secondary": plan_id == secondary,
"decisive": plan_id in [primary, secondary],
})
for recruit_id in run.deployed_recruit_ids:
var result: Dictionary = actors[recruit_id]
_add_event("allied_basic", String(recruit_id), String(route.enemy_ids[0]), {"plan_id": plan_id})
_add_event("authoritative_damage", String(route.enemy_ids[-1]), String(recruit_id), {
"amount": int(result.hp_before) - int(result.hp),
"hp_before": int(result.hp_before),
"hp_after": int(result.hp),
})
if int(result.hp) <= 0:
_add_event("fallen", String(route.enemy_ids[-1]), String(recruit_id), {"permanent": true})
_add_event("battle_terminal", String(route.route_id), String(run.run_id), {
"outcome": outcome,
"score": score,
"cause": "linked_response_succeeded" if outcome == "victory" else String(route.failure_cause),
})
var snapshot := {
"kind": "fg3_contract2_route",
"run_id": String(run.run_id),
"contract_id": "CTR-R2-02",
"region_id": "RG-02",
"market_index": int(run.market_index),
"round_index": market_index,
"offer_id": String(route.offer_id),
"route_id": String(route.route_id),
"risk": int(route.risk),
"plan_id": plan_id,
"primary_plan": primary,
"secondary_plan": secondary,
"fixed_tick_ms": 100,
"tick": event_tick,
"terminal": true,
"outcome": outcome,
"cause": "linked_response_succeeded" if outcome == "victory" else String(route.failure_cause),
"score": score,
"equipment_matches": equipment_matches,
"artifact_id": artifact_id,
"artifact_modifier": artifact_modifier,
"actors": actors,
"final_order": Array(run.deployed_recruit_ids).duplicate(),
"fallen_recruit_ids": fallen_ids,
"event_log": event_log.duplicate(true),
"reward_coin": int(route.reward_coin),
"recovery_coin": int(route.recovery_coin),
"xp_grant": 10 + 2 * market_index + 4 * int(route.risk),
"board_hash": String(run.market_board.board_hash),
"checkpoint_id": String(run.pre_battle_checkpoint_id),
}
return _finalize_snapshot(snapshot, "contract2_route_terminal")
func _run_boss(plan_id: String) -> Dictionary:
if plan_id not in BOSS_PLAN_IDS:
return {"ok": false, "code": "unknown_boss_plan"}
var run: Dictionary = source.current_run
if String(run.selected_boss_plan) != plan_id:
return {"ok": false, "code": "boss_plan_mismatch"}
_reset_events()
var artifact_id := _artifact_id(run)
var equipment_matches := _equipment_match_count(run, ["linked_cost", "pulse_interrupt", "staggered_actions", "boss_telegraph"])
var score := 18
if plan_id == "interrupt_pulse_family":
score += 4 if artifact_id in ["AR-009", "AR-010", "AR-011", "AR-013"] or equipment_matches >= 1 else -1
else:
score += 4 if run.deployed_recruit_ids.size() >= 5 or artifact_id in ["AR-012", "AR-014", "AR-015"] else -1
var outcome := "victory" if score >= 18 else "defeat"
var actors := _boss_actor_results(run, outcome)
var fallen_ids := _fallen_ids(actors)
_add_event("boss_started", "BO-R2-02", String(run.run_id), {"plan_id": plan_id})
_add_event("pulse_family_forecast", "BO-R2-02", "line", {"family": "healing_movement_cleanse"})
_add_event("linked_positions_disclosed", "BO-R2-02", "line", {"indices": [3, 4]})
_add_event("third_pulse_link", "BO-R2-02", "line", {"indices": [3, 4, 5], "pulse_ordinal": 3})
if plan_id == "interrupt_pulse_family":
_add_event("pulse_family_interrupted", "line", "BO-R2-02", {"decisive": true})
else:
_add_event("linked_actions_staggered", "line", "BO-R2-02", {"decisive": true})
for recruit_id in run.deployed_recruit_ids:
var result: Dictionary = actors[recruit_id]
_add_event("authoritative_damage", "BO-R2-02", String(recruit_id), {
"amount": int(result.hp_before) - int(result.hp),
"hp_before": int(result.hp_before),
"hp_after": int(result.hp),
})
if int(result.hp) <= 0:
_add_event("fallen", "BO-R2-02", String(recruit_id), {"permanent": true})
_add_event("boss_terminal", "BO-R2-02", String(run.run_id), {
"outcome": outcome,
"score": score,
"cause": "drowned_bell_plan_succeeded" if outcome == "victory" else "linked_cost_chained_through_recovery",
})
var snapshot := {
"kind": "fg3_contract2_boss",
"run_id": String(run.run_id),
"contract_id": "CTR-R2-02",
"region_id": "RG-02",
"boss_id": "BO-R2-02",
"muster_hash": String(run.boss_muster.muster_hash),
"plan_id": plan_id,
"fixed_tick_ms": 100,
"tick": event_tick,
"terminal": true,
"outcome": outcome,
"cause": "drowned_bell_plan_succeeded" if outcome == "victory" else "linked_cost_chained_through_recovery",
"score": score,
"artifact_id": artifact_id,
"equipment_matches": equipment_matches,
"actors": actors,
"final_order": Array(run.deployed_recruit_ids).duplicate(),
"fallen_recruit_ids": fallen_ids,
"event_log": event_log.duplicate(true),
"checkpoint_id": String(run.pre_battle_checkpoint_id),
}
return _finalize_snapshot(snapshot, "contract2_boss_terminal")
func _route_actor_results(
run: Dictionary,
route: Dictionary,
primary: bool,
secondary: bool,
equipment_matches: int,
artifact_mitigation: int,
outcome: String
) -> Dictionary:
var actors := {}
var base_damage := 4 + 2 * int(route.risk) + int(floor(float(int(route.round_index) - 1) / 3.0))
var mitigation := (3 if primary else (2 if secondary else 0)) + mini(3, equipment_matches)
mitigation += floori(float(artifact_mitigation) / 2.0)
for index in range(run.deployed_recruit_ids.size()):
var recruit_id := String(run.deployed_recruit_ids[index])
var record: Dictionary = run.recruit_records[recruit_id]
var damage := maxi(1, base_damage + int(index / 3) - mitigation)
actors[recruit_id] = {
"id": recruit_id,
"hp_before": int(record.current_hp),
"hp": maxi(1, int(record.current_hp) - damage),
"max_hp": int(record.max_hp),
"profession_id": String(record.profession_id),
}
if outcome == "defeat" and run.deployed_recruit_ids.size() > 1:
actors[String(run.deployed_recruit_ids[-1])].hp = 0
return actors
func _boss_actor_results(run: Dictionary, outcome: String) -> Dictionary:
var actors := {}
for index in range(run.deployed_recruit_ids.size()):
var recruit_id := String(run.deployed_recruit_ids[index])
var record: Dictionary = run.recruit_records[recruit_id]
var damage := 7 + int(index / 2)
actors[recruit_id] = {
"id": recruit_id,
"hp_before": int(record.current_hp),
"hp": maxi(1, int(record.current_hp) - damage),
"max_hp": int(record.max_hp),
"profession_id": String(record.profession_id),
}
if outcome == "defeat" and run.deployed_recruit_ids.size() > 1:
actors[String(run.deployed_recruit_ids[-1])].hp = 0
return actors
func _equipment_match_count(run: Dictionary, response_tags: Array) -> int:
var equipment := Content.rows_by_id(catalog, "equipment")
var matched := 0
for recruit_id in run.deployed_recruit_ids:
var instance_id := String(run.equipped_by_recruit.get(recruit_id, ""))
var catalog_id := String(run.inventory.get(instance_id, {}).get("catalog_id", ""))
if not equipment.has(catalog_id):
continue
if Array(equipment[catalog_id].response_tags).any(func(tag): return tag in response_tags):
matched += 1
return matched
func _artifact_id(run: Dictionary) -> String:
return "" if run.active_artifact_ids.is_empty() else String(run.active_artifact_ids[0])
func _artifact_plan_modifier(artifact_id: String, plan_id: String) -> int:
return int(ARTIFACT_PLAN_BONUS.get(artifact_id, {}).get(plan_id, 0))
func _hp_ratio(run: Dictionary) -> float:
var total := 0.0
for recruit_id in run.deployed_recruit_ids:
var record: Dictionary = run.recruit_records[recruit_id]
total += float(record.current_hp) / float(maxi(1, int(record.max_hp)))
return total / float(maxi(1, run.deployed_recruit_ids.size()))
func _fallen_ids(actors: Dictionary) -> Array:
var result: Array = []
for recruit_id in actors:
if int(actors[recruit_id].hp) <= 0:
result.append(String(recruit_id))
return result
func _reset_events() -> void:
event_log = []
event_tick = 0
func _add_event(kind: String, source_id: String, target_id: String, payload: Dictionary) -> void:
var event := {
"index": event_log.size(),
"tick": event_tick,
"kind": kind,
"source_id": source_id,
"target_id": target_id,
"payload": payload.duplicate(true),
}
event["event_id"] = _hash(event)
event_log.append(event)
event_tick += 1
func _finalize_snapshot(snapshot: Dictionary, code: String) -> Dictionary:
snapshot["event_log_hash"] = _hash(snapshot.event_log)
snapshot["snapshot_hash"] = _hash(snapshot)
return {"ok": true, "code": code, "snapshot": snapshot}
func _hash(value) -> String:
return JSON.stringify(_canonical(value)).sha256_text()
func _canonical(value):
if value is float and is_equal_approx(value, round(value)):
return int(round(value))
if value is Dictionary:
var result := {}
var keys: Array = value.keys()
keys.sort_custom(func(left, right): return String(left) < String(right))
for key in keys:
result[key] = _canonical(value[key])
return result
if value is Array:
var result: Array = []
for item in value:
result.append(_canonical(item))
return result
return value