ThreeKingdomsSlingshot/Assets/Scripts/Runtime/AI/TacticalAI.cs

715 lines
37 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
namespace TKS
{
/// <summary>적 유닛 1기의 행동 후보 1건(가상 실행 결과 점수 포함).</summary>
public class AiPlan
{
public Unit Unit;
public Vector2 Target;
public bool UseSkill;
public float Score;
/// <summary>0 = 서포터(창병 밀기 · 책사 덤불 제거 · 이득 있는 버프) · 1 = 돌격(보·기·창) · 2 = 사격(궁·책).</summary>
public int Group;
public string Why = "";
public int Candidates;
public float Ms;
/// <summary>가상 실행에서 플레이어 유닛에게 준 피해 합.</summary>
public float PlayerDmg;
/// <summary>얻는 것(플레이어 피해 · 처치 · 서포트) 없이 밀친 같은 편(적 측) 수 — ally_bump 감점 대상.</summary>
public int AllyBumps;
/// <summary>가상 실행에서 사격·광역이 같은 편(적 측)을 맞혀 준 피해 합(오사) — 반격으로 잃은 체력은 넣지 않는다.</summary>
public float OwnDmg;
/// <summary>공격은 아니지만 끝난 자리에서 다음 턴에 플레이어를 칠 수 있다(공격 자리 · 사격 자리).</summary>
public bool Setup;
}
/// <summary>
/// 적 AI 예측 시뮬레이션(PD 2026-11-06 #1098 · 전술규칙_적AI_기획서 §2): 후보 행동을 실제 규칙(ActionResolver · 기믹 · 스킬 · 견제)으로 가상 실행(Sim)해
/// ai_weights.csv 점수가 가장 높은 것을 고른다. 후보 = 방위(유닛 ≤ many_units = dirs · 넘으면 dirs_many) × 파워 3단 × 액티브 사용 여부 ·
/// 궁·책 = 사거리 안 표적 + (책사) 덤불 중심 + 방위 이동 · 유닛 1기 예산 budget_ms · 난이도 = aiAccuracy(보스 +boss_accuracy · 투기장 mode_accuracy)로
/// 최고 선택 · 아니면 상위 top_n 무작위 + 파워 ±noise_power · 턴 운영 = 서포터 → 돌격 → 사격 순, 1기 실행마다 재평가(BattleManager).
/// </summary>
public static class TacticalAI
{
static readonly List<float> lastEvalMs = new List<float>();
/// <summary>최근 평가 시간(ms · 성능 테스트용).</summary>
public static IReadOnlyList<float> LastEvalMs
{
get { return lastEvalMs; }
}
public static bool Available
{
get { return AiWeights.Load() != null; }
}
/// <summary>이 적 보스가 액티브를 쓰는가(1부 보스만 · 다음 행동형만 · ai_weights boss_active · active_max_chapter).</summary>
public static bool BossUsesActive(BalanceConfig.StageDef stage, BalanceConfig.EnemySpawn e)
{
var w = AiWeights.Load();
if (w == null || stage == null || e == null || !e.isBoss) return false;
return w["boss_active"] >= 0.5f && stage.chapter >= 1 && stage.chapter <= Mathf.RoundToInt(w["active_max_chapter"]);
}
/// <summary>
/// 다음에 움직일 적 1기와 그 행동: 남은 유닛 전원 평가 → 그룹(서포터 → 돌격 → 사격) 순 · 같은 그룹은 점수 높은 순 → 그 유닛의 후보에서 난이도대로 고른다.
/// 교전 범위 밖(가장 가까운 아군이 aggro 보다 멂)은 대기 → null 이면 이번 턴 끝.
/// </summary>
public static AiPlan Next(BattleManager bm, List<Unit> pending, float accuracy, float aggro, System.Random rng)
{
lastEvalMs.Clear();
var w = AiWeights.Load();
if (w == null) return null;
var players = bm.AliveUnits(Faction.Player);
players.RemoveAll(ScenarioEvent.Absent); // 연출이 숨긴(아직 나타나지 않은) 아군 = 표적 아님(2026-11-19)
if (players.Count == 0) return null;
AiPlan best = null;
List<AiPlan> bestList = null;
int enemyCount = bm.AliveCount(Faction.Enemy);
foreach (var u in pending)
{
if (u == null || !u.IsAlive) continue;
// 교전 범위 밖(PD 2026-11-21 「무조건 대기하지도 않고 상황에 맞게」): 이동이 유리할 때만 움직이고 아니면 자리를 지킨다
bool far = NearestDist(u, players) > aggro;
if (far && !WorthEvaluating(bm, u, players, w)) continue;
List<AiPlan> list;
var top = Evaluate(bm, u, enemyCount, out list);
if (top == null) continue;
if (far && !Engages(bm, u, top, w)) continue;
if (best == null || top.Group < best.Group || (top.Group == best.Group && top.Score > best.Score))
{
best = top;
bestList = list;
}
}
if (best == null) return null;
return Choose(bm, best.Unit, bestList, accuracy, rng, w);
}
/// <summary>교전 범위 밖 유닛을 평가해 볼 만한가(싼 검사): 경계 중이거나, 한 번 움직이면 공격 거리에 플레이어가 들어올 만큼 가깝다 — 아니면 평가 없이 대기.</summary>
static bool WorthEvaluating(BattleManager bm, Unit u, List<Unit> players, AiWeights w)
{
if (Alerted(bm, u, w)) return true;
float reach = UnitTypeInfo.IsRanged(u.Type) ? SkillMods.Range(u) : SkillMods.SlingMax(u);
return NearestDist(u, players) <= SkillMods.SlingMax(u) + reach + 1f;
}
/// <summary>경계(PD 2026-11-21 「아군 중 한명이 공격을 받은 상황」): 자신이 맞았거나 assist_range 안의 같은 편이 맞았다(체력이 깎여 있음).</summary>
public static bool Alerted(BattleManager bm, Unit u, AiWeights w)
{
if (u.Hp < u.MaxHp) return true;
float r = w["assist_range"];
foreach (var a in bm.AliveUnits(u.Faction))
if (a != u && a.Hp < a.MaxHp && Vector2.Distance(a.Position, u.Position) <= r) return true;
return false;
}
/// <summary>지금 자리가 지킬 만한 곳인가(PD 2026-11-21 「방어 효과 지형 · 아군의 호위를 받을 수 있는 위치」): 고지 · 목책 엄폐 · guard_radius 안에 같은 편 guard_allies 기 이상.</summary>
public static bool HoldsGround(BattleManager bm, Unit u, AiWeights w)
{
var layer = GimmickLayer.Current;
if (layer != null && (layer.ZoneAt(u.Position, GimmickZone.High) != null || Covered(u, bm, layer))) return true;
return Guarded(bm, u, w);
}
static bool Guarded(BattleManager bm, Unit u, AiWeights w)
{
int n = 0;
float r = w["guard_radius"];
foreach (var a in bm.AliveUnits(u.Faction))
if (a != u && Vector2.Distance(a.Position, u.Position) <= r) n++;
return n >= Mathf.Max(1, Mathf.RoundToInt(w["guard_allies"]));
}
/// <summary>
/// 교전 범위 밖 유닛이 움직이는가: 플레이어를 때릴 수 있다(같은 편을 밀쳐서라도) · 경계 중이다 ·
/// 다음 턴 공격 자리로 갈 수 있고 지금 자리가 지킬 만한 곳이 아니다 — 아니면 대기.
/// </summary>
static bool Engages(BattleManager bm, Unit u, AiPlan top, AiWeights w)
{
if (top.PlayerDmg > 0f) return true;
if (Alerted(bm, u, w)) return true;
return top.Setup && !HoldsGround(bm, u, w);
}
static float NearestDist(Unit u, List<Unit> players)
{
float best = float.MaxValue;
foreach (var p in players)
{
if (p.IsAlive) best = Mathf.Min(best, Vector2.Distance(u.Position, p.Position));
}
return best;
}
/// <summary>난이도: 최고 점수를 accuracy(+보스 · 투기장 = mode) 확률로 · 아니면 상위 top_n 중 무작위 + 파워 ±noise.</summary>
static AiPlan Choose(BattleManager bm, Unit u, List<AiPlan> list, float accuracy, System.Random rng, AiWeights w)
{
float acc = Mathf.Max(accuracy, w["accuracy_floor"]) + (u.IsBoss ? w["boss_accuracy"] : 0f); // 스테이지 정확도의 바닥(PD 2026-11-21 「적이 너무 멍청」)
if (bm.Mode != null && bm.Mode.kind == OutGame.ArenaRules.Arena) acc = w["mode_accuracy"];
if (list.Count == 1 || rng.NextDouble() < acc) return list[0];
// 최고를 고르지 않을 때도 같은 종류 안에서만 고른다(PD 2026-11-19 「플레이어를 우선 공격 · 자기편끼리 공격 ✕」 · 그 전 = 상위 top_n 아무거나 → 같은 편 밀치기가 뽑힘):
// 최고가 플레이어에게 피해를 주면 피해를 주는 후보만 · 아니면 얻는 것 없이 같은 편을 밀치지 않는 후보만(없으면 전체)
var best = list[0];
var pool = new List<AiPlan>();
foreach (var x in list)
{
// 차선도 말이 되는 것만(PD 2026-11-21): 최선이 공격이면 그 피해의 pick_dmg_ratio 이상이고 다른 같은 편을 해치지 않는 공격 ·
// 아니면 같은 편을 밀치거나 해치지 않고 점수가 최선에서 pick_score_gap 안쪽인 것
bool ok = best.PlayerDmg > 0f
? x.PlayerDmg >= best.PlayerDmg * w["pick_dmg_ratio"] && (x.OwnDmg <= 0f || best.OwnDmg > 0f)
: x.AllyBumps == 0 && x.OwnDmg <= 0f && x.Score >= best.Score - w["pick_score_gap"];
if (ok) pool.Add(x);
}
if (pool.Count == 0) pool = list;
int n = Mathf.Clamp(Mathf.RoundToInt(w["top_n"]), 1, pool.Count);
var pick = pool[rng.Next(n)];
float noise = w["noise_power"];
Vector2 v = pick.Target - u.Position;
float k = 1f + ((float)rng.NextDouble() * 2f - 1f) * noise;
var copy = new AiPlan { Unit = pick.Unit, UseSkill = pick.UseSkill, Score = pick.Score, Group = pick.Group, Why = pick.Why + " · 오차", Candidates = pick.Candidates, Ms = pick.Ms, PlayerDmg = pick.PlayerDmg, AllyBumps = pick.AllyBumps };
float max = SkillMods.SlingMax(u);
v *= k;
if (v.magnitude > max) v = v.normalized * max;
copy.Target = bm.Board.ClampInside(u.Position + v, u.Radius);
if (pick.PlayerDmg > 0f)
{
// 세기 오차 때문에 빗나가거나 같은 편을 맞히게 되면 오차 없이 쏜다(헛수 방지 · PD 2026-11-21)
var check = Simulate(bm, new ActionResolver(bm.Config, bm, new System.Random(12345)), u, copy.Target, pick.UseSkill, Sim.Take(bm), w);
if (check == null || check.PlayerDmg <= 0f || check.OwnDmg > pick.OwnDmg) return pick;
}
return copy;
}
/// <summary>유닛 1기 평가: 후보마다 가상 실행 → 점수 내림차순 목록(list[0] = 최고).</summary>
public static AiPlan Evaluate(BattleManager bm, Unit u, int enemyCount, out List<AiPlan> list)
{
list = new List<AiPlan>();
var w = AiWeights.Load();
if (w == null || u == null || !u.IsAlive) return null;
var sw = Stopwatch.StartNew();
float budget = Mathf.Max(5f, w["budget_ms"]);
var cands = Candidates(bm, u, enemyCount, w);
var skills = bm.Skills != null ? bm.Skills.Of(u) : null;
bool canSkill = skills != null && skills.HasActive && skills.Active.Trigger == SkillTrigger.NextAction && skills.CooldownLeft(bm.TurnNumber) <= 0;
var resolver = new ActionResolver(bm.Config, bm, new System.Random(12345));
var snap = Sim.Take(bm);
int done = 0;
foreach (var t in cands)
{
for (int s = 0; s < (canSkill ? 2 : 1); s++)
{
if (sw.Elapsed.TotalMilliseconds > budget && list.Count > 0) break;
var plan = Simulate(bm, resolver, u, t, s == 1, snap, w);
done++;
if (plan != null) list.Add(plan);
}
}
list.Sort((a, b) => b.Score.CompareTo(a.Score));
float ms = (float)sw.Elapsed.TotalMilliseconds;
lastEvalMs.Add(ms);
if (list.Count == 0) return null;
list[0].Candidates = done;
list[0].Ms = ms;
return list[0];
}
/// <summary>후보 목표점: 방위 × 파워 3단 · 궁·책은 사거리(+접근) 안 표적 · 책사는 덤불 중심까지.</summary>
static List<Vector2> Candidates(BattleManager bm, Unit u, int enemyCount, AiWeights w)
{
var res = new List<Vector2>();
float sling = SkillMods.SlingMax(u);
int dirs = Mathf.Max(4, Mathf.RoundToInt(enemyCount > w["many_units"] ? w["dirs_many"] : w["dirs"]));
float[] powers = { w["power_1"], w["power_2"], w["power_3"] };
if (!UnitTypeInfo.IsRanged(u.Type)) AimCandidates(bm, u, sling, w, res); // 조준 후보가 먼저(예산 안에서 먼저 평가)
if (UnitTypeInfo.IsRanged(u.Type))
{
float reach = SkillMods.Range(u);
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
float gap = Vector2.Distance(u.Position, p.Position) - u.Radius * Combat.CastRadiusScale - p.Radius;
if (gap <= reach + 0.5f) res.Add(p.Position); // 표적 = 그 유닛 중심(목표점 명중 크리)
}
var layer = GimmickLayer.Current;
if (u.Type == UnitType.Strategist && layer != null)
{
foreach (var g in layer.Items)
{
if (!g.BlocksMove || !g.Def.strategistClear) continue;
if (Vector2.Distance(u.Position, g.Shape.Center) - g.Shape.BoundingRadius <= reach) res.Add(g.Shape.Center);
}
}
// 사격 자리 후보(PD 2026-11-21): 플레이어마다 사거리 조금 안쪽 원 위에서 지금 자리와 가까운 다섯 점 — 같은 편에 사선이 막혔을 때 옆으로 돌아 쏠 자리를 찾는다
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue;
Vector2 back = u.Position - p.Position;
if (back.sqrMagnitude < 1e-4f) continue;
float a0 = Mathf.Atan2(back.y, back.x);
foreach (var da in SetupAngles)
{
Vector2 spot = p.Position + new Vector2(Mathf.Cos(a0 + da), Mathf.Sin(a0 + da)) * (reach * 0.85f);
if (Vector2.Distance(spot, u.Position) <= sling) res.Add(bm.Board.ClampInside(spot, u.Radius));
}
}
dirs = Mathf.Max(4, dirs / 2); // 이동 후보(엄폐·고지 자리 잡기)
}
for (int i = 0; i < dirs; i++)
{
float a = i * Mathf.PI * 2f / dirs;
Vector2 d = new Vector2(Mathf.Cos(a), Mathf.Sin(a));
foreach (var k in powers) res.Add(bm.Board.ClampInside(u.Position + d * sling * k, u.Radius));
}
res.Add(u.Position); // 제자리 대기(PD 2026-11-21 「이동이 불리한 경우 대기」 — 방어 지형 · 같은 편 곁의 점수가 이동보다 높으면 고른다)
return res;
}
/// <summary>
/// 근접 병종 조준 후보(PD 2026-11-19 「플레이어를 우선 공격하거나 아군을 밀쳐 공격하는 등 더 똑똑하게」 · 그 전 = 고정 방위 × 파워만 → 플레이어를 정확히 겨누는 후보가 없어 빗나가거나 같은 편에 부딪힘):
/// ① 슬링 안 플레이어 유닛마다 그 중심 방향 = 목표점 명중(중심까지) + 최대 힘(power_3)
/// ② 보병·창병 = 슬링 안 같은 편(적 측)마다 그 유닛에서 가장 가까운 플레이어 쪽으로 밀리게 뒤를 치는 방향(power_2 · power_3) — 밀린 같은 편이 플레이어와 부딪히면 피해(ActionResolver.Push).
/// 점수는 가상 실행이 매기므로 여기서는 방향만 만든다.
/// </summary>
static void AimCandidates(BattleManager bm, Unit u, float sling, AiWeights w, List<Vector2> res)
{
var players = bm.AliveUnits(Faction.Player);
players.RemoveAll(ScenarioEvent.Absent); // 숨은 아군 = 표적 아님
if (players.Count == 0) return;
foreach (var p in players)
{
Vector2 to = p.Position - u.Position;
float d = to.magnitude;
if (d < 1e-3f || d - u.Radius - p.Radius > sling) continue;
Vector2 dir = to / d;
res.Add(bm.Board.ClampInside(u.Position + dir * Mathf.Min(d, sling), u.Radius));
if (d < sling) res.Add(bm.Board.ClampInside(u.Position + dir * sling * w["power_3"], u.Radius));
}
if (u.Type == UnitType.Infantry)
{
// 꺾어 치기(PD 2026-11-21 「각 병종의 특성」): 보병은 비스듬히 맞히면 거울처럼 튕겨 다른 유닛까지 친다 → 플레이어마다 좌·우로 반 두께 비켜 최대 힘
foreach (var p in players)
{
Vector2 to = p.Position - u.Position;
float d = to.magnitude;
if (d < 1e-3f || d - u.Radius - p.Radius > sling) continue;
Vector2 side = new Vector2(-to.y, to.x) / d * ((u.Radius + p.Radius) * 0.5f);
for (int sgn = -1; sgn <= 1; sgn += 2)
res.Add(bm.Board.ClampInside(u.Position + (p.Position + side * sgn - u.Position).normalized * sling, u.Radius));
}
}
if (u.Type == UnitType.Cavalry)
{
// 줄 세워 관통: 두 플레이어 사이를 겨눠 한 번에 꿰뚫는다(가운데 방향 · 최대 힘)
for (int i = 0; i < players.Count; i++)
for (int j = i + 1; j < players.Count; j++)
{
Vector2 mid = (players[i].Position + players[j].Position) * 0.5f - u.Position;
if (mid.sqrMagnitude < 1e-4f || mid.magnitude > sling + 1f) continue;
res.Add(bm.Board.ClampInside(u.Position + mid.normalized * sling, u.Radius));
}
}
if (u.Type != UnitType.Infantry && u.Type != UnitType.Spear) return; // 같은 편을 밀어내는 병종만(기병 = 같은 편 앞에서 멈춤 · 궁·책 = 밀지 않음)
foreach (var a in bm.AliveUnits(u.Faction))
{
if (a == u || ScenarioEvent.Absent(a)) continue;
if (Vector2.Distance(u.Position, a.Position) - u.Radius - a.Radius > sling) continue;
Unit near = null;
float nd = float.MaxValue;
foreach (var p in players)
{
float g = Vector2.Distance(a.Position, p.Position) - a.Radius - p.Radius;
if (g < nd)
{
nd = g;
near = p;
}
}
if (near == null || nd > sling) continue;
Vector2 ap = near.Position - a.Position;
if (ap.sqrMagnitude < 1e-6f) continue;
Vector2 back = a.Position - ap.normalized * (a.Radius + u.Radius); // 이 자리에서 부딪히면 중심선이 플레이어 쪽을 향한다
Vector2 d = back - u.Position;
if (d.sqrMagnitude < 1e-6f) continue;
d.Normalize();
res.Add(bm.Board.ClampInside(u.Position + d * sling * w["power_2"], u.Radius));
res.Add(bm.Board.ClampInside(u.Position + d * sling * w["power_3"], u.Radius));
}
}
static AiPlan Simulate(BattleManager bm, ActionResolver resolver, Unit u, Vector2 target, bool useSkill, Sim.Snapshot snap, AiWeights w)
{
var o = new ActionOutcome();
float score, playerDmg, ownDmg;
int bumps;
string why;
bool wasActive = Sim.Active, wasLive = Sim.LiveRolls; // 레벨디자인 자동 플레이는 전투 전체가 Sim.Active 안에서 돈다 → 끝나면 원래 값으로
Sim.Active = true;
Sim.LiveRolls = false;
try
{
if (useSkill) bm.Skills.Of(u).Reserved = true;
var before = Before(bm, snap);
Sim.Run(resolver.Resolve(u, target, false, o));
Sim.Run(bm.ApplyOverwatch(u, o));
score = Score(bm, u, o, useSkill, before, snap, w, out why, out playerDmg, out bumps, out ownDmg);
}
finally
{
Sim.Active = wasActive;
Sim.LiveRolls = wasLive;
Sim.Restore(bm, snap);
}
int group = UnitTypeInfo.IsRanged(u.Type) ? 2 : 1;
if (why.Contains("서포트") || why.Contains("덤불")) group = 0;
return new AiPlan { Unit = u, Target = target, UseSkill = useSkill, Score = score, Group = group, Why = why, PlayerDmg = playerDmg, AllyBumps = bumps, OwnDmg = ownDmg, Setup = playerDmg <= 0f && (why.Contains("공격 자리") || why.Contains("사격 자리")) };
}
class Pre
{
public readonly Dictionary<Unit, Sim.UnitSnap> Units = new Dictionary<Unit, Sim.UnitSnap>();
public readonly HashSet<GimmickInstance> Removed = new HashSet<GimmickInstance>();
}
static Pre Before(BattleManager bm, Sim.Snapshot snap)
{
var p = new Pre();
foreach (var x in snap.Units) p.Units[x.U] = x;
var layer = GimmickLayer.Current;
if (layer != null)
{
foreach (var g in layer.Items)
{
if (g.Removed || g.Broken) p.Removed.Add(g);
}
}
return p;
}
/// <summary>점수(기획서 §2-3) — 가상 실행 직후 상태 vs 실행 전.</summary>
static float Score(BattleManager bm, Unit u, ActionOutcome o, bool useSkill, Pre pre, Sim.Snapshot snap, AiWeights w, out string why, out float playerDmg, out int bumps, out float ownDmg)
{
ownDmg = 0f;
var parts = new List<string>();
float s = 0f;
playerDmg = 0f;
bumps = 0;
int kills = 0;
float ownLoss = 0f;
foreach (var kv in pre.Units)
{
var x = kv.Value;
var v = x.U;
if (v == null || x.Hp <= 0) continue;
int dmg = Mathf.Max(0, x.Hp - v.Hp);
if (v.Faction == Faction.Player)
{
playerDmg += dmg;
s += w["dmg_player"] * dmg;
if (v.Hp <= 0)
{
kills++;
s += w["kill_base"] + w["kill_hp_ratio"] * (x.MaxHp > 0 ? (float)x.Hp / x.MaxHp : 0f);
}
}
else ownLoss += dmg; // 같은 편(자신 포함)이 잃은 체력 — 아래에서 오사와 그 밖으로 나눠 점수
}
// 같은 편이 잃은 체력(PD 2026-11-21): 사격·광역이 같은 편을 맞힌 것(오사 = o.FriendlyDamage) = dmg_own(무겁게 — 같은 편을 겨누지 않는다) ·
// 그 밖(자신 · 밀려서 부딪힌 같은 편이 받는 반격 · 기믹) = dmg_self(가볍게 — 반격이 무서워 공격을 포기하지 않는다)
ownDmg = Mathf.Min(ownLoss, o.FriendlyDamage);
s += w["dmg_own"] * ownDmg + w["dmg_self"] * (ownLoss - ownDmg);
if (playerDmg > 0f)
{
s += w["attack_bonus"]; // 플레이어를 실제로 때리는 행동을 접근·자리 잡기보다 앞세운다(PD 2026-11-21 「충분히 공격이 가능함에도 공격하지 않는」)
parts.Add("피해 " + playerDmg);
}
if (kills > 0) parts.Add("처치 " + kills);
var layer = GimmickLayer.Current;
if (layer != null)
{
foreach (var a in layer.Affected)
{
if (a.Unit == null) continue;
float val = w["gimmick_dest_bonus"] + a.Value;
s += a.Unit.Faction == Faction.Player ? val : -val;
if (a.Unit.Faction == Faction.Player) parts.Add("기믹 " + a.Kind);
}
// 플레이어 유닛을 폭약 수레 반경으로 밀어 넣음
foreach (var d in o.Displaced)
{
if (d.Unit == null || d.Unit.Faction != Faction.Player || !d.Unit.IsAlive) continue;
foreach (var g in layer.Items)
{
if (!g.BlocksMove || g.Def.projectile != GimmickProjectile.Destroy) continue;
float r = g.P(1, 0f);
if (Vector2.Distance(d.Unit.Position, g.Shape.Center) <= r && Vector2.Distance(d.From, g.Shape.Center) > r)
{
s += w["gimmick_dest_bonus"];
parts.Add("수레 반경");
}
}
}
}
if (o.Chains > 0)
{
s += w["chain"] * o.Chains;
parts.Add("연쇄 " + o.Chains);
}
int reach = 0;
if (u.Type == UnitType.Spear)
{
var seen = new HashSet<Unit>();
foreach (var d in o.Displaced)
{
var a = d.Unit;
if (a == null || a == u || a.Faction != u.Faction || !a.IsAlive || !seen.Add(a)) continue;
if (Vector2.Distance(d.From, d.To) < 0.1f) continue;
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
float before = Vector2.Distance(d.From, p.Position) - a.Radius - p.Radius;
float after = Vector2.Distance(a.Position, p.Position) - a.Radius - p.Radius;
if (after <= SkillMods.SlingMax(a) && before > SkillMods.SlingMax(a)) reach++; // 밀어서 새로 닿게 된 플레이어만(PD 2026-11-19 · 그 전 = 조금만 가까워져도 전부 → 이미 닿는 아군을 밀치는 것이 공격보다 높았다)
}
}
if (reach > 0)
{
s += w["support_reach"] * reach;
parts.Add("서포트 " + reach);
}
}
if (u.Type == UnitType.Cavalry)
{
var hit = new HashSet<Unit>();
foreach (var a in o.Attacked)
{
if (a != null && a.Faction == Faction.Player) hit.Add(a);
}
if (hit.Count > 0)
{
s += w["pierce_hit"] * hit.Count; // 복귀 성공·실패 점수 = 기병 복귀 제거로 삭제(PD 2026-11-10)
parts.Add("관통 " + hit.Count);
}
}
if (u.IsAlive && UnitTypeInfo.IsRanged(u.Type))
{
if (layer != null && Covered(u, bm, layer))
{
s += w["archer_cover"];
parts.Add("목책 엄폐");
}
if (layer != null && layer.ZoneAt(u.Position, GimmickZone.High) != null)
{
s += w["high_ground"];
parts.Add("고지");
}
if (OnCavalryLine(u, bm, layer))
{
s += w["cav_line"];
parts.Add("기병 관통선");
}
}
if (u.Type == UnitType.Strategist)
{
var hit = new HashSet<Unit>();
foreach (var a in o.Attacked)
{
if (a != null && a.Faction == Faction.Player) hit.Add(a);
}
if (hit.Count > 0)
{
s += w["splash_hit"] * hit.Count;
parts.Add("광역 " + hit.Count);
}
if (layer != null)
{
int routes = OpenedRoutes(bm, u, layer, pre);
if (routes > 0)
{
s += w["route_open"] * routes;
parts.Add("덤불 제거 " + routes);
}
}
}
if (u.IsAlive && layer != null)
{
var burn = layer.ZoneAt(u.Position, GimmickZone.Burn);
if (burn != null) s += w["zone_end"] * burn.P(1, 0f) * u.MaxHp;
foreach (var g in layer.Items)
{
if (g.Zone != GimmickZone.Capture || !g.ZoneActive) continue;
float r = g.P(1, 0f);
if (Vector2.Distance(u.Position, g.Shape.Center) - u.Radius > r) continue;
bool foe = false;
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
if (Vector2.Distance(p.Position, g.Shape.Center) - p.Radius <= r) foe = true;
}
if (!foe && g.Owner != (int)u.Faction)
{
s += w["banner"];
parts.Add("군기");
}
}
}
// 같은 편 밀치기(PD 2026-11-19 「적 AI끼리 공격 ✕ · 플레이어를 우선」): 플레이어 피해 · 처치 · 서포트가 없는데 같은 편(적 측)을 밀었으면 1기당 ally_bump
if (playerDmg <= 0f && kills == 0 && reach == 0)
{
var bumped = new HashSet<Unit>();
foreach (var a in o.Pushed)
{
if (a != null && a != u && a.Faction == u.Faction && bumped.Add(a)) bumps++;
}
if (bumps > 0)
{
s += w["ally_bump"] * bumps;
parts.Add("같은 편 밀침 " + bumps);
}
}
if (useSkill && playerDmg <= 0f) s += w["skill_waste"];
if (useSkill) parts.Add("액티브");
if (playerDmg <= 0f && kills == 0 && u.IsAlive)
{
var start = pre.Units[u].Pos;
float before = float.MaxValue, after = float.MaxValue;
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
before = Mathf.Min(before, Vector2.Distance(start, p.Position));
after = Mathf.Min(after, Vector2.Distance(u.Position, p.Position));
}
if (before < float.MaxValue)
{
float gain = before - after;
if (UnitTypeInfo.IsRanged(u.Type)) gain = Mathf.Min(gain, Mathf.Max(0f, before - SkillMods.Range(u))); // 원거리 = 사거리까지만 다가간다
s += w["approach"] * gain;
}
bool rangedU = UnitTypeInfo.IsRanged(u.Type);
if (ClearShot(bm, u))
{
// 지금은 못 치지만 끝난 자리에서는 다음 턴에 닿는다(궁·책 = 사선이 열림 · 근접 = 돌진 길이 열림 · PD 2026-11-21 「다음 턴에 공격하기 좋은 위치로 미리 이동」)
s += w[rangedU ? "shot_setup" : "threat_next"];
parts.Add(rangedU ? "사격 자리" : "공격 자리");
}
if (!rangedU && layer != null && (layer.ZoneAt(u.Position, GimmickZone.High) != null || Covered(u, bm, layer)))
{
s += w["def_terrain"]; // 근접 병종도 방어 지형에서는 자리를 지킨다(궁·책은 archer_cover · high_ground)
parts.Add("방어 지형");
}
if (Guarded(bm, u, w))
{
s += w["guarded"];
parts.Add("같은 편 곁");
}
}
why = string.Join(" · ", parts.ToArray());
return s;
}
/// <summary>그 자리에서 공격 거리 안의 플레이어를 가리는 유닛 없이 칠 수 있는가(그 방향 길의 첫 유닛 = 그 플레이어) — 궁·책 사격 · 근접 돌진 공용.</summary>
static bool ClearShot(BattleManager bm, Unit u)
{
float reach = UnitTypeInfo.IsRanged(u.Type) ? SkillMods.Range(u) : SkillMods.SlingMax(u); // 궁·책 = 사거리 · 근접 = 쏘는 최대 거리
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue;
Vector2 v = p.Position - u.Position;
float d = v.magnitude;
if (d < 1e-3f || d - u.Radius * Combat.CastRadiusScale - p.Radius > reach) continue;
float hd;
if (Combat.FirstUnitOnPath(u, u.Position, v / d, d, out hd) == p) return true;
}
return false;
}
/// <summary>사격 자리 후보를 뽑는 각도(플레이어에서 본 지금 자리 방향 기준 · 라디안).</summary>
static readonly float[] SetupAngles = { 0f, 0.5f, -0.5f, 1f, -1f };
/// <summary>궁·책 종료 위치와 플레이어 근접 유닛 사이 직선에 목책(투사체 통과 · 이동 막힘)이 있는가.</summary>
static bool Covered(Unit u, BattleManager bm, GimmickLayer layer)
{
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
if (!UnitTypeInfo.IsMelee(p.Type)) continue;
if (Vector2.Distance(p.Position, u.Position) > SkillMods.SlingMax(p) + 2f) continue;
foreach (var g in layer.Items)
{
if (!g.BlocksMove || g.Def.projectile != GimmickProjectile.Pass || g.Zone == GimmickZone.River) continue;
if (g.Shape.SegmentTouches(u.Position, p.Position)) return true;
}
}
return false;
}
/// <summary>플레이어 기병의 관통 사정(슬링 + 반지름) 안이고 사이에 장애물이 없으면 관통선 위.</summary>
static bool OnCavalryLine(Unit u, BattleManager bm, GimmickLayer layer)
{
foreach (var c in bm.AliveUnits(Faction.Player))
{
if (c.Type != UnitType.Cavalry) continue;
if (Vector2.Distance(c.Position, u.Position) > SkillMods.SlingMax(c) + u.Radius) continue;
bool blocked = false;
if (layer != null)
{
foreach (var g in layer.Items)
{
if (g.BlocksMove && g.Shape.SegmentTouches(c.Position, u.Position)) blocked = true;
}
}
if (!blocked) return true;
}
return false;
}
/// <summary>이번 가상 실행으로 지워진 덤불 때문에 새로 열린 (적 측 유닛 → 플레이어 유닛) 직선 수(사거리·슬링 안 · 다른 장애물 없음).</summary>
static int OpenedRoutes(BattleManager bm, Unit shooter, GimmickLayer layer, Pre pre)
{
var cleared = new List<GimmickInstance>();
foreach (var g in layer.Items)
{
if (g.Removed && !pre.Removed.Contains(g) && g.Def.strategistClear) cleared.Add(g);
}
if (cleared.Count == 0) return 0;
int n = 0;
foreach (var a in bm.AliveUnits(shooter.Faction))
{
if (a == shooter) continue;
float reach = UnitTypeInfo.IsRanged(a.Type) ? SkillMods.Range(a) : SkillMods.SlingMax(a);
foreach (var p in bm.AliveUnits(Faction.Player))
{
if (ScenarioEvent.Absent(p)) continue; // 숨은 아군
if (Vector2.Distance(a.Position, p.Position) - a.Radius - p.Radius > reach) continue;
bool wasBlocked = false;
foreach (var g in cleared)
{
if (g.Shape.SegmentTouches(a.Position, p.Position, a.Radius * 0.8f)) wasBlocked = true;
}
if (!wasBlocked) continue;
bool stillBlocked = false;
foreach (var g in layer.Items)
{
if (g.BlocksMove && g.Shape.SegmentTouches(a.Position, p.Position, a.Radius * 0.8f)) stillBlocked = true;
}
if (!stillBlocked) n++;
}
}
return n;
}
}
}