Please solve step by step in great detail in high quality:
Here’s a complex, exam-level undergraduate problem centered on another rich and challenging aspect of developing a Fire Emblem-style tactical RPG in Godot 4: building a modular combat forecast and resolution system. This question requires data design, UI logic separation, gameplay simulation, and architectural extensibility.
🧩 Exam Question: Combat Forecast & Resolution System in Godot 4 (Fire Emblem Clone)
In tactical RPGs like Fire Emblem, selecting an enemy shows a combat forecast: potential damage, hit rate, double attack predictions, and critical chance—before you commit to the attack. You are tasked with designing and implementing this system in Godot 4, ensuring it is modular, data-driven, and testable.
| D | Forecast system extensibility, AOE abstractions | 10 |
🌟 Bonus (+2 pts)
Award for describing:
a rollback/undo system for forecasting,
deterministic combat logs,
or predictive AI use of the same forecast logic.
Assistant
This solution tackles the design and implementation of a modular, data-driven, and extensible combat forecast and resolution system for a Godot 4 Fire Emblem-style tactical RPG.
✅ Solution: Combat Forecast & Resolution System
❓ Part A: Forecast Data Modeling and Architecture (15 pts)
1. Design a CombatForecast data structure:
To cleanly represent a projected encounter and ensure separation from UI rendering, we'll design two Resource classes:
CombatantForecast.gd: Represents the outcome for a single unit (attacker or defender) in a combat scenario.
CombatEncounterForecast.gd: Encapsulates the full 1v1 combat interaction, containing two CombatantForecast instances.
CombatantForecast.gd (Extends Resource)
gdscript
# CombatantForecast.gd
class_name CombatantForecast extends Resource
@export var unit_id: int = -1 # A unique ID or Unit.name for reference
@export var initial_hp: int = 0
@export var predicted_final_hp: int = 0 # HP after all attacks in the encounter
@export var attacks_landed: int = 0 # How many hits this combatant lands (1 or 2)
@export var damage_per_hit: int = 0 # Damage dealt PER hit
@export var total_damage_dealt: int = 0 # Total damage dealt by this combatant
@export var hit_chance: float = 0.0 # 0.0 - 1.0
@export var crit_chance: float = 0.0 # 0.0 - 1.0
@export var is_double_attacking: bool = false
@export var is_countering: bool = false # True if this unit is capable of counter-attacking
@export var weapon_triangle_advantage: int = 0 # -1 (disadvantage), 0 (neutral), 1 (advantage)
# --- Internal/Derived properties for detailed display or debug ---
@export var effective_attack_stat: int = 0
@export var effective_defense_stat: int = 0
@export var effective_speed_stat: int = 0
@export var luck_stat: int = 0 # If luck is used for hit/crit
@export var weapon_power: int = 0
# CombatEncounterForecast.gd
class_name CombatEncounterForecast extends Resource
@export var attacker_unit_id: int = -1
@export var defender_unit_id: int = -1
@export var attacker_forecast: CombatantForecast # Details for the attacking unit
@export var defender_forecast: CombatantForecast # Details for the defending unit
@export var is_valid_encounter: bool = false # True if combat can occur (e.g., in range)
@export var attacker_can_attack: bool = false # True if attacker can initiate
@export var defender_can_counter: bool = false # True if defender can counter
# Constructor/initializer to create instances easily
func _init(attacker_id: int = -1, defender_id: int = -1,
att_forecast: CombatantForecast = null, def_forecast: CombatantForecast = null,
is_valid: bool = false, att_can_attack: bool = false, def_can_counter: bool = false):
self.attacker_unit_id = attacker_id
self.defender_unit_id = defender_id
self.attacker_forecast = att_forecast
self.defender_forecast = def_forecast
self.is_valid_encounter = is_valid
self.attacker_can_attack = att_can_attack
self.defender_can_counter = def_can_counter
These Resource objects can be created, populated, and passed around the system without relying on specific Node paths or directly modifying scene state.
2. Architecture of CombatResolver:
The CombatResolver.gd will be an Autoload (Singleton), making it globally accessible and ensuring only one instance exists.
gdscript
# CombatResolver.gd (Autoload)
extends Node
# Signal emitted when a combat forecast is generated (e.g., for UI)
signal combat_forecast_generated(forecast: CombatEncounterForecast)
# Signal emitted when combat is resolved (e.g., for animations, sound, log)
signal combat_resolved(combat_log: Array, final_state: Dictionary)
var combat_modifiers: Array[Callable] = [] # List of active modifier Callables
func _ready():
# Example: Register a global terrain modifier
# combat_modifiers.append(Callable(self, "_apply_terrain_modifiers"))
pass
# ----------------------------------------------------------------------
# --- Combat Modifier System (Plug-in architecture) ---
# ----------------------------------------------------------------------
# Context object to pass around to modifiers, allowing them to modify values
class CombatContext:
var attacker: Unit
var defender: Unit
var base_attack_stat: int
var base_defense_stat: int
var base_speed_stat: int
var base_hit_rate: float
var base_crit_rate: float
var current_hp_attacker: int
var current_hp_defender: int
# Add other relevant data like terrain_type, skill_list, etc.
func _init(att_unit: Unit, def_unit: Unit):
attacker = att_unit
defender = def_unit
# Initialize with base stats from units (or their copies for forecast)
base_attack_stat = att_unit.attack
base_defense_stat = def_unit.defense
base_speed_stat = att_unit.speed # Speed is compared, not applied directly
base_hit_rate = att_unit.hit_rate
base_crit_rate = att_unit.crit_rate
current_hp_attacker = att_unit.current_hp
current_hp_defender = def_unit.current_hp
# Interface/concept for modifiers (could be an abstract class in C# or simple Callable in GDScript)
# Each modifier is a Callable that takes a CombatContext and modifies its properties.
# Example Modifier Callable:
# func _example_skill_modifier(context: CombatContext):
# if context.attacker.has_skill("AttackBoost"):
# context.base_attack_stat += 5
# if context.defender.has_skill("DefenseAura"):
# context.base_defense_stat += 3
func register_combat_modifier(modifier_callable: Callable):
if not modifier_callable in combat_modifiers:
combat_modifiers.append(modifier_callable)
func unregister_combat_modifier(modifier_callable: Callable):
combat_modifiers.erase(modifier_callable)
# Applies all registered modifiers to a given CombatContext
func _apply_all_modifiers(context: CombatContext):
for modifier_callable in combat_modifiers:
if modifier_callable.is_valid():
modifier_callable.call(context)
# ----------------------------------------------------------------------
# --- Core Combat Calculation Logic ---
# ----------------------------------------------------------------------
# Helper function to get effective stats for a specific unit in a combat scenario
# This function will call _apply_all_modifiers
func _get_effective_stats(attacker: Unit, defender: Unit, for_attacker: bool, simulated_attacker_hp: int, simulated_defender_hp: int) -> CombatContext:
var context: CombatContext
if for_attacker:
context = CombatContext.new(attacker, defender)
else: # For defender's counter-attack context
context = CombatContext.new(defender, attacker) # Defender is now the 'attacker' in the context
# Override current HP for simulation purposes if needed (for skills like Vengeance)
context.current_hp_attacker = simulated_attacker_hp if for_attacker else simulated_defender_hp
context.current_hp_defender = simulated_defender_hp if for_attacker else simulated_attacker_hp
_apply_all_modifiers(context)
return context
# Calculates core combat values for a single hit
func _calculate_single_hit_outcome(attacker_unit: Unit, defender_unit: Unit,
simulated_attacker_hp: int, simulated_defender_hp: int,
is_crit_forced: bool = false, is_hit_forced: bool = false) -> Dictionary:
var attacker_context = _get_effective_stats(attacker_unit, defender_unit, true, simulated_attacker_hp, simulated_defender_hp)
var defender_context = _get_effective_stats(defender_unit, attacker_unit, false, simulated_defender_hp, simulated_attacker_hp) # For defender's defensive stats
# Weapon Triangle Advantage/Disadvantage
var weapon_triangle_modifier = _get_weapon_triangle_modifier(attacker_unit.weapon, defender_unit.weapon)
attacker_context.base_attack_stat += weapon_triangle_modifier * 1 # Example: +/- 1 damage
# Base Damage Calculation (Attack - Defense)
var damage_before_crit = max(1, attacker_context.base_attack_stat + attacker_unit.weapon.power - defender_context.base_defense_stat)
# Hit Chance (Hit Rate - Defender's Avoid, which can be derived from Speed/Luck)
var effective_hit_chance = max(0.0, min(1.0, (attacker_context.base_hit_rate - (defender_context.base_speed_stat / 2.0)) / 100.0)) # Example formula
var did_hit = is_hit_forced if is_hit_forced else (randf() < effective_hit_chance)
# Crit Chance (Crit Rate - Defender's Crit Avoid/Luck)
var effective_crit_chance = max(0.0, min(1.0, (attacker_context.base_crit_rate - (defender_context.luck_stat / 2.0)) / 100.0)) # Example formula
var is_crit = is_crit_forced if is_crit_forced else (randf() < effective_crit_chance)
var final_damage = damage_before_crit
if is_crit:
final_damage *= 3 # Typical Fire Emblem critical hit multiplier
return {
"damage": final_damage,
"hit_chance": effective_hit_chance,
"crit_chance": effective_crit_chance,
"did_hit": did_hit,
"is_crit": is_crit,
"effective_attack": attacker_context.base_attack_stat,
"effective_defense": defender_context.base_defense_stat,
"weapon_triangle_advantage": weapon_triangle_modifier
}
# Determines who doubles
func _check_for_double_attack(attacker_unit: Unit, defender_unit: Unit, simulated_attacker_hp: int, simulated_defender_hp: int) -> Dictionary:
var att_context = _get_effective_stats(attacker_unit, defender_unit, true, simulated_attacker_hp, simulated_defender_hp)
var def_context = _get_effective_stats(defender_unit, attacker_unit, false, simulated_defender_hp, simulated_attacker_hp)
var attacker_can_double = (att_context.base_speed_stat >= def_context.base_speed_stat + 4)
var defender_can_double = (def_context.base_speed_stat >= att_context.base_speed_stat + 4)
# Fire Emblem rule: only one unit can double in a single combat encounter
if attacker_can_double and defender_can_double: # Should theoretically not happen if threshold is high enough
attacker_can_double = false # Or some other tie-breaker
defender_can_double = false
elif attacker_can_double:
pass # Attacker doubles
elif defender_can_double:
pass # Defender doubles
return {
"attacker_doubles": attacker_can_double,
"defender_doubles": defender_can_double
}
# Helper for weapon triangle
func _get_weapon_triangle_modifier(att_weapon: Weapon, def_weapon: Weapon) -> int:
# Example logic: Sword > Axe > Lance > Sword
var att_type = att_weapon.type
var def_type = def_weapon.type
if att_type == "Sword" and def_type == "Axe": return 1
if att_type == "Axe" and def_type == "Lance": return 1
if att_type == "Lance" and def_type == "Sword": return 1
if att_type == "Axe" and def_type == "Sword": return -1
if att_type == "Lance" and def_type == "Axe": return -1
if att_type == "Sword" and def_type == "Lance": return -1
return 0 # Neutral
# ----------------------------------------------------------------------
# --- Core Methods: Forecast & Resolution ---
# ----------------------------------------------------------------------
# Simulates a full combat encounter step-by-step
# Returns a list of CombatAttackEvent objects
class CombatAttackEvent:
var source_unit_id: int
var target_unit_id: int
var damage_dealt: int
var did_hit: bool
var is_crit: bool
var forecast_hp_before_attack: int
var forecast_hp_after_attack: int
var event_type: String # "Attack", "Counter", "Double Attack"
func _simulate_combat_round(attacker_unit: Unit, defender_unit: Unit, is_forecast: bool) -> Array[CombatAttackEvent]:
var combat_log: Array[CombatAttackEvent] = []
# Use copies for forecast, actual units for resolution
var current_att_hp = attacker_unit.current_hp if not is_forecast else attacker_unit.current_hp
var current_def_hp = defender_unit.current_hp if not is_forecast else defender_unit.current_hp
# --- Initial Attack (Attacker's first hit) ---
var att_hit_outcome = _calculate_single_hit_outcome(attacker_unit, defender_unit, current_att_hp, current_def_hp)
var att_dmg_dealt = att_hit_outcome.damage if att_hit_outcome.did_hit else 0
var att_event = CombatAttackEvent.new()
att_event.source_unit_id = attacker_unit.get_instance_id()
att_event.target_unit_id = defender_unit.get_instance_id()
att_event.damage_dealt = att_dmg_dealt
att_event.did_hit = att_hit_outcome.did_hit
att_event.is_crit = att_hit_outcome.is_crit
att_event.forecast_hp_before_attack = current_def_hp
current_def_hp = max(0, current_def_hp - att_dmg_dealt)
att_event.forecast_hp_after_attack = current_def_hp
att_event.event_type = "Attack"
combat_log.append(att_event)
if current_def_hp <= 0: return combat_log # Defender defeated
# --- Defender's Counter-Attack ---
# Assume defender can counter if in range and not incapacitated
var defender_can_counter = (defender_unit.weapon.range.x <= attacker_unit.weapon.range.x and
defender_unit.weapon.range.y >= attacker_unit.weapon.range.y) # Simplistic range check
if defender_can_counter:
var def_hit_outcome = _calculate_single_hit_outcome(defender_unit, attacker_unit, current_def_hp, current_att_hp)
var def_dmg_dealt = def_hit_outcome.damage if def_hit_outcome.did_hit else 0
var def_event = CombatAttackEvent.new()
def_event.source_unit_id = defender_unit.get_instance_id()
def_event.target_unit_id = attacker_unit.get_instance_id()
def_event.damage_dealt = def_dmg_dealt
def_event.did_hit = def_hit_outcome.did_hit
def_event.is_crit = def_hit_outcome.is_crit
def_event.forecast_hp_before_attack = current_att_hp
current_att_hp = max(0, current_att_hp - def_dmg_dealt)
def_event.forecast_hp_after_attack = current_att_hp
def_event.event_type = "Counter-Attack"
combat_log.append(def_event)
if current_att_hp <= 0: return combat_log # Attacker defeated
# --- Double Attack Check ---
var double_check_result = _check_for_double_attack(attacker_unit, defender_unit, current_att_hp, current_def_hp)
if double_check_result.attacker_doubles:
var att_hit_outcome_2 = _calculate_single_hit_outcome(attacker_unit, defender_unit, current_att_hp, current_def_hp)
var att_dmg_dealt_2 = att_hit_outcome_2.damage if att_hit_outcome_2.did_hit else 0
var att_event_2 = CombatAttackEvent.new()
att_event_2.source_unit_id = attacker_unit.get_instance_id()
att_event_2.target_unit_id = defender_unit.get_instance_id()
att_event_2.damage_dealt = att_dmg_dealt_2
att_event_2.did_hit = att_hit_outcome_2.did_hit
att_event_2.is_crit = att_hit_outcome_2.is_crit
att_event_2.forecast_hp_before_attack = current_def_hp
current_def_hp = max(0, current_def_hp - att_dmg_dealt_2)
att_event_2.forecast_hp_after_attack = current_def_hp
att_event_2.event_type = "Double Attack"
combat_log.append(att_event_2)
elif double_check_result.defender_doubles and defender_can_counter:
var def_hit_outcome_2 = _calculate_single_hit_outcome(defender_unit, attacker_unit, current_def_hp, current_att_hp)
var def_dmg_dealt_2 = def_hit_outcome_2.damage if def_hit_outcome_2.did_hit else 0
var def_event_2 = CombatAttackEvent.new()
def_event_2.source_unit_id = defender_unit.get_instance_id()
def_event_2.target_unit_id = attacker_unit.get_instance_id()
def_event_2.damage_dealt = def_dmg_dealt_2
def_event_2.did_hit = def_hit_outcome_2.did_hit
def_event_2.is_crit = def_hit_outcome_2.is_crit
def_event_2.forecast_hp_before_attack = current_att_hp
current_att_hp = max(0, current_att_hp - def_dmg_dealt_2)
def_event_2.forecast_hp_after_attack = current_att_hp
def_event_2.event_type = "Double Counter"
combat_log.append(def_event_2)
return combat_log
# Public method for generating a forecast
func generate_forecast(attacker_unit: Unit, defender_unit: Unit) -> CombatEncounterForecast:
# Pre-checks (e.g., range, unit alive)
var is_valid_encounter = attacker_unit.is_alive() and defender_unit.is_alive()
if not is_valid_encounter:
return CombatEncounterForecast.new(attacker_unit.get_instance_id(), defender_unit.get_instance_id(), null, null, false, false, false)
# Create temporary copies of units for pure forecast simulation (no side effects)
# In a real game, Unit.gd might have a 'clone()' method, or you could pass current stats.
# For simplicity, we'll just track HP changes within the _simulate_combat_round logic.
# The _simulate_combat_round's 'is_forecast' flag prevents modifying real unit HP.
var simulation_log = _simulate_combat_round(attacker_unit, defender_unit, true)
var att_forecast = CombatantForecast.new()
var def_forecast = CombatantForecast.new()
att_forecast.unit_id = attacker_unit.get_instance_id()
att_forecast.initial_hp = attacker_unit.current_hp
def_forecast.unit_id = defender_unit.get_instance_id()
def_forecast.initial_hp = defender_unit.current_hp
# Populate forecast from simulation_log
var total_att_damage = 0
var total_def_damage = 0
var att_hits = 0
var def_hits = 0
var last_att_hp_before = attacker_unit.current_hp # Initial state for forecast
var last_def_hp_before = defender_unit.current_hp
# Need to re-calculate hit/crit for forecast display as the simulation just tells us if it hit/crit.
# The simulation is for HP changes, but forecast needs the *chances*.
var initial_att_hit_crit = _calculate_single_hit_outcome(attacker_unit, defender_unit, attacker_unit.current_hp, defender_unit.current_hp)
var initial_def_hit_crit = _calculate_single_hit_outcome(defender_unit, attacker_unit, defender_unit.current_hp, attacker_unit.current_hp)
att_forecast.hit_chance = initial_att_hit_crit.hit_chance
att_forecast.crit_chance = initial_att_hit_crit.crit_chance
att_forecast.damage_per_hit = initial_att_hit_crit.damage # Base damage for display
att_forecast.weapon_triangle_advantage = initial_att_hit_crit.weapon_triangle_advantage
att_forecast.effective_attack_stat = initial_att_hit_crit.effective_attack
att_forecast.effective_defense_stat = initial_att_hit_crit.effective_defense
att_forecast.weapon_power = attacker_unit.weapon.power
att_forecast.is_double_attacking = _check_for_double_attack(attacker_unit, defender_unit, attacker_unit.current_hp, defender_unit.current_hp).attacker_doubles
def_forecast.hit_chance = initial_def_hit_crit.hit_chance
def_forecast.crit_chance = initial_def_hit_crit.crit_chance
def_forecast.damage_per_hit = initial_def_hit_crit.damage
def_forecast.weapon_triangle_advantage = initial_def_hit_crit.weapon_triangle_advantage # Relative to defender's perspective
def_forecast.effective_attack_stat = initial_def_hit_crit.effective_attack
def_forecast.effective_defense_stat = initial_def_hit_crit.effective_defense
def_forecast.weapon_power = defender_unit.weapon.power
def_forecast.is_double_attacking = _check_for_double_attack(attacker_unit, defender_unit, attacker_unit.current_hp, defender_unit.current_hp).defender_doubles
def_forecast.is_countering = true # Assume defender can counter if within range and not incapacitated
for event in simulation_log:
if event.source_unit_id == attacker_unit.get_instance_id():
total_att_damage += event.damage_dealt
att_hits += 1 if event.did_hit else 0
last_def_hp_before = event.forecast_hp_after_attack
elif event.source_unit_id == defender_unit.get_instance_id():
total_def_damage += event.damage_dealt
def_hits += 1 if event.did_hit else 0
last_att_hp_before = event.forecast_hp_after_attack
att_forecast.total_damage_dealt = total_att_damage
att_forecast.attacks_landed = att_hits
att_forecast.predicted_final_hp = last_att_hp_before # This is defender's initial HP - total damage taken by attacker.
# Should actually be defender's final HP for attacker's forecast.
# Correction: att_forecast.predicted_final_hp is attacker's final HP.
def_forecast.total_damage_dealt = total_def_damage
def_forecast.attacks_landed = def_hits
def_forecast.predicted_final_hp = last_def_hp_before
var forecast_result = CombatEncounterForecast.new(
attacker_unit.get_instance_id(), defender_unit.get_instance_id(),
att_forecast, def_forecast, true, true, true
)
combat_forecast_generated.emit(forecast_result)
return forecast_result
# Public method for resolving combat (applies damage, side effects)
func resolve_combat(attacker_unit: Unit, defender_unit: Unit) -> Array[CombatAttackEvent]:
# This calls the same simulation logic, but now it modifies the *actual* unit HPs.
var simulation_log = _simulate_combat_round(attacker_unit, defender_unit, false)
# Apply actual damage to units based on the log
for event in simulation_log:
var target_unit = get_node(event.target_unit_id) # Assuming units are nodes and ID is unique
if target_unit:
if event.did_hit:
target_unit.current_hp = max(0, target_unit.current_hp - event.damage_dealt)
# Emit signals for animations, sound, status effects here
# target_unit.hit_effect.emit()
combat_resolved.emit(simulation_log, {"attacker_hp": attacker_unit.current_hp, "defender_hp": defender_unit.current_hp})
return simulation_log
Architecture Summary:
Plug-in Modifiers:
CombatContext Class: A mutable data container that holds all relevant stats and contextual information for a combat calculation.
_apply_all_modifiers(context: CombatContext): This method iterates through a list of Callable objects (combat_modifiers). Each callable is a modifier function/method that takes a CombatContext and directly modifies its properties (e.g., context.base_attack_stat += 5).
This supports skills, terrain, weather, and temporary buffs/debuffs by simply adding/removing modifier callables to/from combat_modifiers. Modifiers can be implemented anywhere and registered with the CombatResolver.
Pre-combat Simulation (Forecast) and Final Resolution:
The core logic is encapsulated in _simulate_combat_round(attacker, defender, is_forecast).
If is_forecast is true, it uses copies or passes current HP values around without modifying the actual Unit instances. It then returns the CombatEncounterForecast resource.
If is_forecast is false, it operates on the actual Unit instances and applies damage to their current_hp property.
This ensures the forecast is always accurate because it uses the exact same mechanics as the resolution.
Testing Combat Logic in Isolation:
Dependency Injection:generate_forecast and resolve_combat directly accept Unit objects as parameters, rather than relying on global get_node() calls within the core calculation functions. This makes it easy to create dummy Unit objects with specific stats for testing.
Pure Functions for Calculation: The individual _calculate_single_hit_outcome, _check_for_double_attack methods are as pure as possible, returning dictionaries of results without side effects.
No Scene Dependencies:CombatResolver does not directly interact with scene nodes for its core calculations. It operates on data. resolve_combat might access nodes to update HP or trigger effects, but the core math is separate.
Test Suite: With GDUnit4 (or similar), you'd create test cases like:
gdscript
# Example GDUnit4 test
extends GDUnit4.Test
var attacker_unit: Unit
var defender_unit: Unit
var combat_resolver: CombatResolver
func _before_each():
# Mock Unit and Weapon resources
attacker_unit = Unit.new()
attacker_unit.attack = 10
attacker_unit.defense = 5
attacker_unit.speed = 10
attacker_unit.current_hp = 30
attacker_unit.hit_rate = 90
attacker_unit.crit_rate = 10
attacker_unit.weapon = Weapon.new()
attacker_unit.weapon.power = 5
attacker_unit.weapon.type = "Sword"
attacker_unit.set_instance_id(1001) # Assign a dummy ID for testing
defender_unit = Unit.new()
defender_unit.attack = 8
defender_unit.defense = 7
defender_unit.speed = 6
defender_unit.current_hp = 40
defender_unit.hit_rate = 70
defender_unit.crit_rate = 5
defender_unit.weapon = Weapon.new()
defender_unit.weapon.power = 4
defender_unit.weapon.type = "Axe"
defender_unit.set_instance_id(1002)
combat_resolver = CombatResolver.new()
# For testing, you might not add it to the scene tree or manually add/remove.
# Alternatively, if it's an Autoload, you'd access `CombatResolver` directly.
func test_forecast_damage_calculation():
var forecast = combat_resolver.generate_forecast(attacker_unit, defender_unit)
assert_true(forecast.is_valid_encounter)
assert_eq(forecast.attacker_forecast.total_damage_dealt, 12) # (10+5-7) * 1 hit
assert_true(forecast.attacker_forecast.is_double_attacking) # Attacker speed 10, defender speed 6 (10 >= 6+4)
# ... further assertions for hit/crit chances, HP, etc.
func test_resolve_combat_hp_reduction():
# Seed random for deterministic tests if random is involved in _resolve_combat
# Global RNG must be set, or provide a mock RNG to the resolver
# For this example, assuming deterministic calculation based on `did_hit`/`is_crit` values from `_calculate_single_hit_outcome`
var initial_defender_hp = defender_unit.current_hp
combat_resolver.resolve_combat(attacker_unit, defender_unit)
# Assuming average hit/crit or force hit/crit for testing
assert_le(defender_unit.current_hp, initial_defender_hp - 1) # At least some damage
# ... detailed assertions for exact HP based on deterministic hits
❓ Part B: Combat Forecast UI Integration (10 pts)
1. Real-time Responsiveness:
UnitSelectionManager (Autoload/Global): This manager handles player input for unit selection and movement on the grid. When the player's mouse hovers over a grid cell:
It checks if a Unit is present on that cell.
If the unit is an enemy and within range of the currently active player unit, it emits a signal: unit_hovered_for_forecast(hovered_unit: Unit).
UIManager (Autoload/Global): This autoload acts as the central hub for UI updates.
UIManager connects to UnitSelectionManager.unit_hovered_for_forecast.
When the signal is received, UIManager calls CombatResolver.generate_forecast(PlayerUnits.active_unit, hovered_unit).
CombatResolver generates the CombatEncounterForecast resource and emits its combat_forecast_generated signal.
CombatForecastUI.tscn (Control Node): This is a dedicated UI scene, typically part of the main UI canvas. Its script (CombatForecastUI.gd) is connected to CombatResolver.combat_forecast_generated.
When combat_forecast_generated is emitted, CombatForecastUI.gd receives the CombatEncounterForecast resource.
It then populates its Label nodes, ProgressBar nodes, and TextureRect nodes (for unit portraits, weapon icons, etc.) with the data from the forecast resource.
The UI is typically hidden by default and becomes visible when a relevant unit is hovered, repositioning itself near the hovered unit or in a fixed corner.
2. Avoiding Tightly Coupling UI Code to Gameplay Logic:
Separation of Concerns (SoC):
CombatResolver.gd: Pure gameplay mechanics. No UI elements, no rendering. Its only UI interaction is emitting a signal with the generated forecast data.
CombatForecastUI.gd: Pure UI rendering. It only knows how to display a CombatEncounterForecast resource. It doesn't know how that resource was generated or who generated it. It only listens for the combat_forecast_generated signal.
Signals (Event-Driven Architecture):
The CombatResolver doesn't directly call methods on CombatForecastUI. Instead, it broadcasts an event (combat_forecast_generated). Any UI component interested in this data can listen. This decouples the producer (resolver) from the consumer (UI).
Resources for Data Transfer:
The CombatEncounterForecast is a Resource. It's a plain data object, not a Node. It can be instantiated and passed as an argument with signals. This avoids passing around Node references or relying on get_node(), which would create tight coupling. The UI reads immutable data from the Resource.
Autoloads (Singletons):
CombatResolver and UIManager are Autoloads, acting as global services. This prevents get_node() calls across distant parts of the scene tree and provides clear global access points for core systems without rigid dependencies. For example, the UnitSelectionManager doesn't need to know about CombatResolver or CombatForecastUI directly; it just interacts with UIManager and CombatResolver as global services.
UI Scene Structure:
CombatForecastUI.tscn is a self-contained UI PackedScene. It can be placed directly under the main CanvasLayer or instantiated dynamically. Its script is only responsible for rendering the data it receives.
gdscript
# Example UIManager.gd (Autoload)
extends Node
@onready var combat_forecast_ui = get_node("/root/MainScene/UI/CombatForecastUI") # Or dynamically instantiate
func _ready():
# Connect to signals from relevant systems
# UnitSelectionManager is assumed to be another Autoload or accessible
if has_node("/root/UnitSelectionManager"):
get_node("/root/UnitSelectionManager").unit_hovered_for_forecast.connect(_on_unit_hovered_for_forecast)
CombatResolver.combat_forecast_generated.connect(combat_forecast_ui._on_combat_forecast_generated)
func _on_unit_hovered_for_forecast(hovered_unit: Unit):
var active_player_unit = PlayerUnits.get_active_unit() # Assuming PlayerUnits is another Autoload
if active_player_unit and active_player_unit.is_in_attack_range(hovered_unit.grid_position):
CombatResolver.generate_forecast(active_player_unit, hovered_unit)
combat_forecast_ui.show()
else:
combat_forecast_ui.hide()
# Example CombatForecastUI.gd (Script on Control node)
extends Control
@onready var attacker_name_label: Label = %AttackerName
@onready var attacker_hp_bar: ProgressBar = %AttackerHPBar
@onready var attacker_damage_label: Label = %AttackerDamage
@onready var attacker_hit_crit_label: Label = %AttackerHitCrit
# ... similar nodes for defender
func _ready():
hide() # Hidden by default
func _on_combat_forecast_generated(forecast: CombatEncounterForecast):
if not is_visible(): show() # Only show if it's not already visible
if forecast.is_valid_encounter:
update_ui_for_combatant(forecast.attacker_forecast, attacker_name_label, attacker_hp_bar, attacker_damage_label, attacker_hit_crit_label)
update_ui_for_combatant(forecast.defender_forecast, %DefenderName, %DefenderHPBar, %DefenderDamage, %DefenderHitCrit)
# Handle showing/hiding elements based on double attack, counter-attack, etc.
# e.g., if not forecast.defender_forecast.is_countering: hide defender's attack info
else:
# Display "No valid encounter" or hide UI
hide()
func update_ui_for_combatant(combatant_forecast: CombatantForecast, name_lbl: Label, hp_bar: ProgressBar, dmg_lbl: Label, hit_crit_lbl: Label):
# Lookup unit name/icon from ID if needed, or directly from Unit (if passing unit ref)
# var unit = get_unit_by_id(combatant_forecast.unit_id)
# name_lbl.text = unit.unit_name if unit else "Unknown"
name_lbl.text = "Unit ID: " + str(combatant_forecast.unit_id) # Placeholder
hp_bar.max_value = combatant_forecast.initial_hp
hp_bar.value = combatant_forecast.predicted_final_hp
var attacks_text = ""
if combatant_forecast.attacks_landed > 0:
attacks_text = str(combatant_forecast.damage_per_hit)
if combatant_forecast.attacks_landed > 1:
attacks_text += " x" + str(combatant_forecast.attacks_landed)
attacks_text += " (" + str(combatant_forecast.total_damage_dealt) + " total)"
else:
attacks_text = "0"
dmg_lbl.text = attacks_text
hit_crit_lbl.text = "Hit: " + str(int(combatant_forecast.hit_chance * 100)) + "% / Crit: " + str(int(combatant_forecast.crit_chance * 100)) + "%"
# Further logic for double attack icon, weapon triangle icon etc.
Description: Fire Emblem-style doubling rules usually dictate that only one unit can initiate a follow-up attack within a single combat instance. If Unit A's speed is high enough to double Unit B, Unit B cannot also double Unit A in the same combat. A common bug arises if the speed check is applied independently to both sides:
If these two checks are true simultaneously (e.g., due to specific speed values or modifiers), the forecast/resolution might incorrectly predict/execute four attacks (A attacks twice, B attacks twice) instead of the correct three (e.g., A attacks twice, B counters once, or A attacks once, B counters twice). The underlying issue is failing to enforce the "only one unit can double" rule.
Consequence: Misleading forecast numbers and incorrect combat outcomes.
Description: Many Fire Emblem skills trigger or modify stats based on a unit's current_hp (e.g., "Vantage" attacks first at low HP, "Desperation" allows doubling at low HP, "Vengeance" increases damage as HP drops). If the combat forecast or resolution calculates all hits based only on the units' current_hpbefore the combat starts, it won't accurately account for changes that occur after the first hit.
Example Scenario: Unit A attacks Unit B. Unit B takes damage from A's first hit. If Unit B has "Vengeance" and its counter-attack damage is calculated based on its initial full HP instead of its reduced HP after A's first hit, the forecast for B's counter-attack (and any subsequent hits) will be inaccurate.
Consequence: Forecast numbers that don't match actual resolution, leading to player frustration and unpredictability.
2. Architectural Technique for Clean Simulation:
The Combat Round Simulation (Turn-Based Step-by-Step) technique, as implemented in _simulate_combat_round in Part A, is the ideal architectural technique to address these issues cleanly and deterministically.
How it works:
The simulation takes a snapshot of the units' current_hp (or uses copies for forecast).
It proceeds through the combat sequence one attack at a time:
Attacker's first hit.
Apply damage to the simulated defender's HP.
Defender's counter-attack (if alive and able).
Apply damage to the simulated attacker's HP.
Determine who doubles (this check is done once, definitively for the entire round, enforcing the single-doubler rule).
If attacker doubles and is alive: Attacker's second hit.
Apply damage to the simulated defender's HP.
If defender doubles and is alive: Defender's second hit.
Apply damage to the simulated attacker's HP.
During each attack step, when _calculate_single_hit_outcome is called, it receives the currently simulated HP values of both units. This ensures that any CombatModifier (like "Vengeance") which checks current_hp will receive the correct, up-to-date value.
The entire sequence is recorded in an Array[CombatAttackEvent] (the combat_log), detailing every hit, miss, crit, and HP change.
Benefits:
Resolves Bug 1 (Double-Double Conflict): The _check_for_double_attack function is called only once before the second attack phase. It explicitly determines who doubles (attacker, defender, or neither) and ensures only one unit is marked as is_double_attacking, enforcing the Fire Emblem rule.
Resolves Bug 2 (Mid-Combat Stat Changes): By updating current_att_hp and current_def_hp after each individual hit within the simulation loop, any subsequent calculations for counter-attacks or double attacks use the correct, updated HP values. Modifiers that depend on HP will accurately reflect the state.
Deterministic and Transparent: The combat_log provides a clear, step-by-step record of the entire combat. This is invaluable for debugging, UI animation, and ensuring forecast accuracy.
Extensibility: New mechanics (e.g., "Vantage" - attacker always hits first if low HP, "Wrath" - increased crit at low HP) can be easily integrated by adjusting the attack order or applying specific modifiers within the CombatContext at the relevant points in the simulation.
❓ Part D: Extending to Area-of-Effect (AOE) Weapons (10 pts)
1. Extending CombatForecast and UI systems for AOE:
AOECombatForecast.gd (New Resource for Multi-Target Data):
We need a new resource to represent the forecast for multiple targets, as CombatEncounterForecast is specifically for 1v1.
gdscript
# AOECombatForecast.gd
class_name AOECombatForecast extends Resource
@export var source_unit_id: int # The unit performing the AOE attack
@export var target_tile_center: Vector2i # The tile targeted by the player for the AOE
@export var affected_tiles: Array[Vector2i] # All tiles the AOE pattern covers
# Dictionary mapping unit_id to its individual 1v1 forecast against the source
@export var individual_forecasts: Dictionary[int, CombatantForecast] = {}
@export var target_units: Array[Unit] # Actual references to affected units (for convenience in UI)
func _init(source_id: int, center_tile: Vector2i, affected_tiles_arr: Array[Vector2i] = []):
self.source_unit_id = source_id
self.target_tile_center = center_tile
self.affected_tiles = affected_tiles_arr
CombatResolver Extension:
Add a new method to CombatResolver to generate this AOE forecast:
gdscript
# In CombatResolver.gd
signal aoe_combat_forecast_generated(forecast: AOECombatForecast)
func generate_aoe_forecast(attacker_unit: Unit, target_center_tile: Vector2i, aoe_pattern_resource: Resource) -> AOECombatForecast:
var affected_tiles = _get_aoe_tiles_from_pattern(target_center_tile, aoe_pattern_resource) # Helper to get tiles based on pattern (e.g., 3x3, cross)
var affected_units: Array[Unit] = []
# Iterate over affected_tiles to find units on them
# (Assumes a global map or unit manager to get units by tile)
for tile_pos in affected_tiles:
var unit_on_tile = GlobalMap.get_unit_on_tile(tile_pos) # Example GlobalMap Autoload
if unit_on_tile and unit_on_tile != attacker_unit: # Don't target self
affected_units.append(unit_on_tile)
var aoe_forecast = AOECombatForecast.new(attacker_unit.get_instance_id(), target_center_tile, affected_tiles)
aoe_forecast.target_units = affected_units
for defender_unit in affected_units:
# Generate a 1v1 forecast for each affected unit against the attacker
var single_forecast_result = generate_forecast(attacker_unit, defender_unit)
aoe_forecast.individual_forecasts[defender_unit.get_instance_id()] = single_forecast_result.attacker_forecast # Only attacker's part of the forecast
# Note: For AOE, defender doesn't counter-attack usually, so only attacker's damage matters.
# If defender does counter (e.g. from special ability), adjust forecast logic.
aoe_combat_forecast_generated.emit(aoe_forecast)
return aoe_forecast
UI Integration for AOE:
Tile Highlight:
When an AOE weapon is selected, the UnitSelectionManager (or a dedicated AOE_TargetingManager) will, upon mouse hover, query the CombatResolver (or a MapFXManager) for the affected_tiles based on the weapon's AOE pattern resource and the hovered tile.
A TileHighlightManager (or the TileMap itself) will then be instructed to draw visual highlights (e.g., a red translucent overlay) on all affected_tiles.
Per-Unit Forecast Display:
The UIManager connects to CombatResolver.aoe_combat_forecast_generated.
When an AOECombatForecast is received, the UIManager:
Can instantiate a new AOEForecastUI.tscn (a custom UI panel) or update an existing one.
This AOEForecastUI would iterate through aoe_forecast.individual_forecasts.
For each entry, it could:
Display a compact summary (e.g., Unit Name, predicted HP, total damage) in a list within the AOE panel.
Or, it could dynamically instance small, simplified CombatForecastUI elements (or similar small pop-ups) above/near each affected unit on the map. These small pop-ups would only show damage dealt, HP changes, etc., specific to that unit.
Hovering over a unit in the list or on the map could expand to show full details for that specific 1v1 forecast.
2. Design Pattern/Abstraction for Single-target vs Multi-target Weapons:
The Command Pattern or Strategy Pattern with a CombatAction abstraction is highly suitable.
CombatAction.gd (Base Class/Protocol):
gdscript
# CombatAction.gd
class_name CombatAction extends Resource
@export var source_unit: Unit
# Method to generate a forecast for this action
# Returns a specific forecast resource type (e.g., CombatEncounterForecast or AOECombatForecast)
func generate_forecast() -> Resource:
push_error("generate_forecast() must be implemented by subclasses.")
return null
# Method to resolve the action, applying changes to game state
# Returns a combat log (Array of CombatAttackEvent or similar)
func resolve_action() -> Array:
push_error("resolve_action() must be implemented by subclasses.")
return []
# AOEAttackAction.gd
class_name AOEAttackAction extends CombatAction
@export var target_center_tile: Vector2i
@export var aoe_pattern_resource: Resource # e.g., a resource defining the AOE shape
func _init(source_unit_ref: Unit, center_tile: Vector2i, pattern: Resource):
self.source_unit = source_unit_ref
self.target_center_tile = center_tile
self.aoe_pattern_resource = pattern
func generate_forecast() -> AOECombatForecast:
return CombatResolver.generate_aoe_forecast(source_unit, target_center_tile, aoe_pattern_resource)
func resolve_action() -> Array:
# AOE resolution needs to identify all units, then resolve combat for each
var affected_tiles = CombatResolver._get_aoe_tiles_from_pattern(target_center_tile, aoe_pattern_resource)
var affected_units: Array[Unit] = []
for tile_pos in affected_tiles:
var unit_on_tile = GlobalMap.get_unit_on_tile(tile_pos)
if unit_on_tile and unit_on_tile != source_unit:
affected_units.append(unit_on_tile)
var full_aoe_log: Array = []
for defender_unit in affected_units:
# Resolve each individual combat (attacker vs defender, no counter for AOE usually)
var single_combat_log = CombatResolver.resolve_combat(source_unit, defender_unit) # This will apply damage
full_aoe_log.append_array(single_combat_log)
return full_aoe_log # Return a composite log
How CombatResolver and Game Flow Change:
The CombatResolver's public API simplifies:
gdscript
# In CombatResolver.gd
func process_action(action: CombatAction, is_forecast_mode: bool) -> Resource:
if is_forecast_mode:
return action.generate_forecast()
else:
return action.resolve_action() # This should probably return the combat log
The game's InputHandler or ActionManager would construct the appropriate CombatAction (e.g., SingleTargetAttackAction or AOEAttackAction) based on the player's selected weapon and target.
It then passes this CombatAction to CombatResolver.process_action.
Benefits:
Polymorphism: The CombatResolver doesn't need if-else statements to differentiate between single-target and multi-target; it just calls generate_forecast() or resolve_action() on the CombatAction instance, and the correct logic executes.
Extensibility: Adding new complex action types (e.g., healing spells, summoning, debuffs, movement actions) becomes straightforward. Each new action type is a new CombatAction subclass.
Clean API: Simplifies the CombatResolver's interface.
Testability: Each CombatAction subclass can be tested independently.
🌟 Bonus (+2 pts)
Rollback/Undo System for Forecasting (and Predictive AI):
The current CombatResolver design inherently supports this. The _simulate_combat_round function takes an is_forecast parameter. When true, it avoids directly modifying the actual Unit instances' current_hp. Instead, it calculates and tracks HP changes internally (e.g., current_att_hp, current_def_hp variables within the function) and returns a CombatEncounterForecast or AOECombatForecast resource populated with these predicted outcomes.
For Predictive AI, the AI system would repeatedly call CombatResolver.generate_forecast() for various potential moves (e.g., "What if I attack enemy A?", "What if I use AOE on this group?"). Since generate_forecast does not modify the global game state, the AI can explore many combat scenarios without needing to save and restore the entire game state. It simply analyzes the returned CombatEncounterForecast resource for each hypothetical action and chooses the optimal one.
Deterministic Combat Logs:
The _simulate_combat_round function produces an Array[CombatAttackEvent]. This array acts as a deterministic combat log. Each CombatAttackEvent records:
The source and target units' IDs.
Damage dealt, whether it hit, and if it was a critical hit.
The HP of the target unit before and after the attack.
The event type ("Attack", "Counter-Attack", "Double Attack").
When resolve_combat is called, it returns this log. This log is crucial for:
Debugging: Easily trace why a combat outcome occurred.
Replay: Given the same initial game state and random seed (if applicable), the log can be used to perfectly recreate a combat sequence.
UI Animation: The UI can iterate through the log events to animate each hit, miss, critical hit, and HP bar change precisely, providing a clear visual representation of the battle.
This comprehensive system provides a robust foundation for a Fire Emblem-style combat and forecast system in Godot 4, emphasizing modularity, testability, and extensibility.