677 lines
32 KiB
C#
677 lines
32 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Reflection;
|
||
using System.Text;
|
||
using NUnit.Framework;
|
||
using TKS.OutGame;
|
||
using UnityEngine;
|
||
using UnityEngine.SceneManagement;
|
||
using UnityEngine.TestTools;
|
||
using Debug = UnityEngine.Debug;
|
||
|
||
namespace TKS.Tests
|
||
{
|
||
/// <summary>
|
||
/// 레벨디자인 자동 플레이(2026-11-18 PD 「스테이지당 20~1000회 반복 플레이 · 최대 배속」).
|
||
/// 전투 전체를 가상 실행(Sim.Active · 연출 없음 · 한 프레임)으로 돌리되 피해 난수 · 확률 치명타는 진짜로 굴린다(Sim.LiveRolls).
|
||
/// 아군 = LevelBot(후보 행동을 같은 규칙으로 가상 실행해 점수가 높은 것 + 사람 손 오차) · 적 = 게임의 예측 AI(TacticalAI) 그대로.
|
||
/// 작업 = 환경 변수 TKS_LEVELSIM 의 JSON(LevelSimJob) · 결과 = 전투 1판 = CSV 1줄. 환경 변수가 없으면 건너뜀(평소 테스트 무관).
|
||
/// </summary>
|
||
public class LevelSimTests
|
||
{
|
||
[Serializable]
|
||
public class LevelSimJob
|
||
{
|
||
/// <summary>스테이지·기믹 표를 읽을 폴더(비면 Assets/Data 그대로 · 파일이 없으면 그 파일만 Assets 것).</summary>
|
||
public string dataDir = "";
|
||
public string outCsv = "";
|
||
public int turnCap = 15;
|
||
/// <summary>조준 방식(-1 = 그대로 · 0 = 게이지 거리 · 1 = 끌기 거리 + 판정 게이지 · TestOptions.AimModeOverride 로 이 실행 동안만).</summary>
|
||
public int aimMode = -1;
|
||
public int dirs = 12;
|
||
public float[] powers = { 0.45f, 0.75f, 0.95f };
|
||
public List<LevelSimItem> items = new List<LevelSimItem>();
|
||
}
|
||
|
||
[Serializable]
|
||
public class LevelSimItem
|
||
{
|
||
public string stage = "2-1";
|
||
public int runs = 20;
|
||
/// <summary>아군 능력치 배율(영웅 고유 배율 × 이 값 · 1 = 기준 스펙).</summary>
|
||
public float spec = 1f;
|
||
/// <summary>1 = 숙련 조작 · 0 = 보통 조작.</summary>
|
||
public int skill = 0;
|
||
/// <summary>적 전원 능력치 추가 배율(표 값 × 이 값 · 실험용).</summary>
|
||
public float eHp = 1f, eAtk = 1f, eDef = 1f;
|
||
public int seed = 1;
|
||
public string tag = "";
|
||
/// <summary>고정 편성(영웅 id 를 ; 로 · 비면 판마다 무작위 5명 · 병종당 최대 2).</summary>
|
||
public string lineup = "";
|
||
}
|
||
|
||
static readonly MethodInfo PlayerRoutine = typeof(BattleManager).GetMethod("PlayerActionRoutine", BindingFlags.NonPublic | BindingFlags.Instance);
|
||
static readonly MethodInfo EnemyRoutine = typeof(BattleManager).GetMethod("EnemyTurnRoutine", BindingFlags.NonPublic | BindingFlags.Instance);
|
||
static readonly FieldInfo ForceMoveOnly = typeof(BattleManager).GetField("forceMoveOnly", BindingFlags.NonPublic | BindingFlags.Instance);
|
||
|
||
BattleManager bm;
|
||
|
||
[UnityTest, Category("LevelSim"), Timeout(86400000)]
|
||
public IEnumerator LevelSim_Run()
|
||
{
|
||
string jobPath = Environment.GetEnvironmentVariable("TKS_LEVELSIM");
|
||
if (string.IsNullOrEmpty(jobPath) || !File.Exists(jobPath))
|
||
{
|
||
Assert.Ignore("레벨디자인 자동 플레이 = 환경 변수 TKS_LEVELSIM(작업 JSON) 이 있을 때만");
|
||
yield break;
|
||
}
|
||
LogAssert.ignoreFailingMessages = true;
|
||
var job = JsonUtility.FromJson<LevelSimJob>(File.ReadAllText(jobPath, Encoding.UTF8));
|
||
int prevAim = TestOptions.AimModeOverride;
|
||
if (job.aimMode >= 0) TestOptions.AimModeOverride = job.aimMode;
|
||
AimRules.Refresh();
|
||
|
||
WorldProgress.Reset();
|
||
SaveStore.UseMemory(true);
|
||
SceneManager.LoadScene("Battle");
|
||
yield return null;
|
||
yield return null;
|
||
bm = BattleManager.Instance;
|
||
Assert.IsNotNull(bm);
|
||
var wm = WorldMapScreen.Instance;
|
||
if (wm != null && wm.HasData) wm.EnterStage(0, 0);
|
||
yield return null;
|
||
|
||
string err = LoadData(job.dataDir);
|
||
var outPath = string.IsNullOrEmpty(job.outCsv) ? Path.Combine(Application.dataPath, "../Logs/levelsim/out.csv") : job.outCsv;
|
||
Directory.CreateDirectory(Path.GetDirectoryName(outPath));
|
||
using (var w = new StreamWriter(outPath, false, new UTF8Encoding(true)))
|
||
{
|
||
w.WriteLine("tag,stage,kind,run,skill,spec,e_hp,e_atk,e_def,win,end,turns,actions,allies,lost,ally_hp_pct,min_team_hp_pct,enemies,enemies_left,enemy_hp_pct,crits,skills_used,gimmick_hits,ms,misses,aim,lineup");
|
||
if (err != null)
|
||
{
|
||
w.WriteLine("ERROR," + err.Replace(',', ' ').Replace('\n', ' '));
|
||
w.Flush();
|
||
Assert.Fail(err);
|
||
}
|
||
var session = OutGameSession.Current;
|
||
var pool = new List<HeroDb.Hero>();
|
||
if (session != null && session.Db != null && session.Db.Heroes != null)
|
||
foreach (var h in session.Db.Heroes.heroes)
|
||
if (!h.isSoldier) pool.Add(h);
|
||
|
||
var sw = Stopwatch.StartNew();
|
||
foreach (var it in job.items)
|
||
{
|
||
int idx = StageIndex(it.stage);
|
||
if (idx < 0)
|
||
{
|
||
w.WriteLine("ERROR,stage " + it.stage + " 없음");
|
||
continue;
|
||
}
|
||
for (int run = 0; run < it.runs; run++)
|
||
{
|
||
string line;
|
||
try
|
||
{
|
||
line = RunOne(job, it, idx, run, pool, session);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Sim.Active = false;
|
||
Sim.LiveRolls = false;
|
||
line = it.tag + "," + it.stage + ",EXC," + run + "," + ex.GetType().Name + " " + (ex.Message ?? "").Replace(',', ' ').Replace('\n', ' ');
|
||
}
|
||
w.WriteLine(line);
|
||
w.Flush();
|
||
yield return null; // 프레임을 넘겨 지운 오브젝트 정리
|
||
}
|
||
}
|
||
w.WriteLine("DONE," + sw.Elapsed.TotalSeconds.ToString("0.0", CultureInfo.InvariantCulture));
|
||
}
|
||
TestOptions.AimModeOverride = prevAim;
|
||
}
|
||
|
||
int StageIndex(string key)
|
||
{
|
||
var st = bm.Config.stages;
|
||
for (int i = 0; i < st.Length; i++)
|
||
if (st[i].chapter + "-" + st[i].stage == key) return i;
|
||
return -1;
|
||
}
|
||
|
||
/// <summary>dataDir 의 스테이지 표(5) · 기믹 배치 표를 읽어 이 실행의 설정 자산(메모리)에 반영. 오류 = 문구 · 성공 = null.</summary>
|
||
string LoadData(string dataDir)
|
||
{
|
||
if (string.IsNullOrEmpty(dataDir)) return null;
|
||
string Read(string sub, string file)
|
||
{
|
||
var p = Path.Combine(dataDir, file);
|
||
if (!File.Exists(p)) p = Path.Combine(Application.dataPath, sub, file);
|
||
return File.Exists(p) ? File.ReadAllText(p, Encoding.UTF8) : null;
|
||
}
|
||
var texts = new string[StageTable.Files.Length];
|
||
for (int i = 0; i < texts.Length; i++) texts[i] = Read(StageTable.Folder, StageTable.Files[i]);
|
||
var t = StageTable.Parse(texts);
|
||
if (t.errors.Count > 0) return "스테이지 표 오류: " + string.Join(" / ", t.errors.GetRange(0, Mathf.Min(8, t.errors.Count)).ToArray());
|
||
StageTable.Apply(bm.Config, t);
|
||
var gt = new string[GimmickTables.Files.Length];
|
||
for (int i = 0; i < gt.Length; i++) gt[i] = Read(GimmickTables.Folder, GimmickTables.Files[i]);
|
||
var g = GimmickTables.Parse(gt);
|
||
if (g.errors.Count > 0) return "기믹 표 오류: " + string.Join(" / ", g.errors.GetRange(0, Mathf.Min(8, g.errors.Count)).ToArray());
|
||
if (GimmickTables.Table != null) GimmickTables.Table.rows = g.rows;
|
||
return null;
|
||
}
|
||
|
||
List<LineupEntry> BuildLineup(LevelSimItem it, System.Random rng, List<HeroDb.Hero> pool, OutGameSession session)
|
||
{
|
||
var picked = new List<HeroDb.Hero>();
|
||
if (!string.IsNullOrEmpty(it.lineup))
|
||
{
|
||
foreach (var id in it.lineup.Split(';'))
|
||
{
|
||
var h = pool.Find(x => x.id == id.Trim());
|
||
if (h != null) picked.Add(h);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var perType = new int[UnitTypeInfo.Count];
|
||
var bag = new List<HeroDb.Hero>(pool);
|
||
while (picked.Count < 5 && bag.Count > 0)
|
||
{
|
||
var h = bag[rng.Next(bag.Count)];
|
||
bag.Remove(h);
|
||
if (perType[(int)h.type] >= 2) continue;
|
||
perType[(int)h.type]++;
|
||
picked.Add(h);
|
||
}
|
||
}
|
||
picked.Sort((a, b) => UnitTypeInfo.IsRanged(a.type).CompareTo(UnitTypeInfo.IsRanged(b.type))); // 근접 = 전열 자리 0~2 · 원거리 = 후열
|
||
var res = new List<LineupEntry>();
|
||
for (int i = 0; i < picked.Count; i++)
|
||
{
|
||
var h = picked[i];
|
||
var e = new LineupEntry
|
||
{
|
||
slot = i, id = h.id, name = h.nameKo, type = h.type, art = h.art,
|
||
hpMult = h.hpMult * it.spec, atkMult = h.atkMult * it.spec, defMult = h.defMult * it.spec,
|
||
};
|
||
if (session != null) SkillRules.FillLineup(session.Db, session.Save, h, e);
|
||
res.Add(e);
|
||
}
|
||
return res;
|
||
}
|
||
|
||
string RunOne(LevelSimJob job, LevelSimItem it, int idx, int run, List<HeroDb.Hero> pool, OutGameSession session)
|
||
{
|
||
var rng = new System.Random(it.seed * 100003 + run * 7919 + idx * 31);
|
||
var lineup = BuildLineup(it, rng, pool, session);
|
||
var stageDef = bm.Config.stages[idx];
|
||
bm.LineupProvider = () => lineup;
|
||
bm.StageClearedProvider = (c, s) => true;
|
||
bm.ResultHandler = r => { };
|
||
TutorialRules.Mode = stageDef.chapter == 1 ? TutorialMode.ForceOn : TutorialMode.Auto;
|
||
bm.StartStage(idx);
|
||
BossIntro.Abort();
|
||
if (bm.Phase == BattlePhase.Setup) bm.ForcePhase(BattlePhase.PlayerTurn);
|
||
|
||
int enemies = 0;
|
||
foreach (var e in bm.AliveUnits(Faction.Enemy))
|
||
{
|
||
enemies++;
|
||
if (!Mathf.Approximately(it.eHp, 1f)) { e.MaxHp = Mathf.Max(1, Mathf.RoundToInt(e.MaxHp * it.eHp)); e.Hp = e.MaxHp; }
|
||
if (!Mathf.Approximately(it.eAtk, 1f)) e.Atk = Mathf.Max(1, Mathf.RoundToInt(e.Atk * it.eAtk));
|
||
if (!Mathf.Approximately(it.eDef, 1f)) e.Def = Mathf.Max(0, Mathf.RoundToInt(e.Def * it.eDef));
|
||
}
|
||
var allies = Players();
|
||
int allyCount = allies.Count;
|
||
float minTeam = 1f;
|
||
var sw = Stopwatch.StartNew();
|
||
var bot = new LevelBot(bm, rng, it.skill, job.dirs, job.powers);
|
||
string end = "?";
|
||
int actions = 0;
|
||
Sim.Active = true;
|
||
Sim.LiveRolls = true;
|
||
try
|
||
{
|
||
for (int guard = 0; guard < 600; guard++)
|
||
{
|
||
var ph = bm.Phase;
|
||
if (ph == BattlePhase.StageClear) { end = "clear"; break; }
|
||
if (ph == BattlePhase.Defeat) { end = "defeat"; break; }
|
||
if (bm.Tutorial != null && bm.Tutorial.NpcLost) { end = "npc_lost"; break; }
|
||
if (bm.TurnNumber > job.turnCap) { end = "cap"; break; }
|
||
if (ph != BattlePhase.PlayerTurn) { end = "stuck_" + ph; break; }
|
||
minTeam = Mathf.Min(minTeam, TeamHp(allies));
|
||
if (bot.UseInstantSkills()) continue;
|
||
var plan = bot.Decide();
|
||
if (plan == null)
|
||
{
|
||
foreach (var u in bm.AliveUnits(Faction.Player))
|
||
{
|
||
if (u.ActedThisTurn) continue;
|
||
u.MarkActed();
|
||
bm.Skills.ClearBonus(u);
|
||
}
|
||
bm.ForcePhase(BattlePhase.Resolving);
|
||
Sim.Run((IEnumerator)EnemyRoutine.Invoke(bm, null));
|
||
continue;
|
||
}
|
||
bm.ForcePhase(BattlePhase.Resolving);
|
||
ForceMoveOnly.SetValue(bm, plan.Miss); // 끌기 조준 · 원거리 빈 칸 = 이동만(RequestPlayerAction 과 같게)
|
||
Sim.Run((IEnumerator)PlayerRoutine.Invoke(bm, new object[] { plan.U, plan.Target, plan.Crit }));
|
||
actions++;
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
Sim.Active = false;
|
||
Sim.LiveRolls = false;
|
||
}
|
||
minTeam = Mathf.Min(minTeam, TeamHp(allies));
|
||
int lost = 0;
|
||
foreach (var u in allies) if (!u.IsAlive) lost++;
|
||
int eLeft = 0;
|
||
float eHpNow = 0f, eHpMax = 0f;
|
||
foreach (var u in bm.Units)
|
||
{
|
||
if (u == null || u.Faction != Faction.Enemy || SkillSystem.IsSummon(u)) continue;
|
||
eHpMax += u.MaxHp;
|
||
if (u.IsAlive) { eLeft++; eHpNow += u.Hp; }
|
||
}
|
||
var ids = new List<string>();
|
||
foreach (var l in lineup) ids.Add(l.id);
|
||
var ic = CultureInfo.InvariantCulture;
|
||
return string.Join(",", new[]
|
||
{
|
||
it.tag, it.stage, stageDef.kind.ToString(), run.ToString(), it.skill.ToString(), it.spec.ToString("0.###", ic),
|
||
it.eHp.ToString("0.###", ic), it.eAtk.ToString("0.###", ic), it.eDef.ToString("0.###", ic),
|
||
end == "clear" ? "1" : "0", end, bm.TurnNumber.ToString(), actions.ToString(), allyCount.ToString(), lost.ToString(),
|
||
(TeamHp(allies) * 100f).ToString("0", ic), (minTeam * 100f).ToString("0", ic), enemies.ToString(), eLeft.ToString(),
|
||
(eHpMax > 0f ? eHpNow / eHpMax * 100f : 0f).ToString("0", ic), bot.Crits.ToString(), bot.SkillsUsed.ToString(), bot.GimmickHits.ToString(),
|
||
sw.ElapsedMilliseconds.ToString(), bot.Misses.ToString(), AimRules.Mode.ToString(), string.Join(";", ids.ToArray()),
|
||
});
|
||
}
|
||
|
||
List<Unit> Players()
|
||
{
|
||
var res = new List<Unit>();
|
||
foreach (var u in bm.AliveUnits(Faction.Player))
|
||
if (!u.Npc && !SkillSystem.IsSummon(u)) res.Add(u);
|
||
return res;
|
||
}
|
||
|
||
static float TeamHp(List<Unit> allies)
|
||
{
|
||
float now = 0f, max = 0f;
|
||
foreach (var u in allies)
|
||
{
|
||
max += u.MaxHp;
|
||
now += Mathf.Max(0, u.Hp);
|
||
}
|
||
return max > 0f ? now / max : 0f;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 레벨디자인 자동 플레이의 아군 조작: 행동할 수 있는 아군 전원의 후보(방위 × 게이지 + 적을 겨눈 것)를 같은 규칙으로 가상 실행 → 점수 최고(숙련) 또는 상위 몇 개 중(보통) →
|
||
/// 사람 손 오차(게이지 타이밍 · 방향)를 더해 확정. 게이지 치명타 구간(aimGaugeCritFrom 이상)에서 놓으면 치명타.
|
||
/// </summary>
|
||
public class LevelBot
|
||
{
|
||
readonly BattleManager bm;
|
||
readonly System.Random rng;
|
||
readonly int skill;
|
||
readonly int dirs;
|
||
readonly float[] powers;
|
||
public int Crits, SkillsUsed, GimmickHits, Misses;
|
||
|
||
public class Plan
|
||
{
|
||
public Unit U;
|
||
public Vector2 Dir;
|
||
public float Power;
|
||
public Vector2 Target;
|
||
public bool Crit;
|
||
public bool UseSkill;
|
||
public float Score;
|
||
/// <summary>가상 실행에서 적이 기믹(독 · 불 · 바위 · 강 · 폭약 …)에 걸린 수.</summary>
|
||
public int Gimmick;
|
||
/// <summary>끌기 조준 · 원거리가 판정 게이지 빈 칸에 놓음 = 공격 없이 이동.</summary>
|
||
public bool Miss;
|
||
}
|
||
|
||
int lastGimmick;
|
||
/// <summary>판단 직전 부술 수 있는 장애물(성문 · 목책 · 수레 …)의 내구.</summary>
|
||
readonly Dictionary<GimmickInstance, int> gimHp = new Dictionary<GimmickInstance, int>();
|
||
|
||
/// <summary>a → b 직선이 아직 서 있는 막는 지형에 걸리는가.</summary>
|
||
static bool Blocked(Vector2 a, Vector2 b)
|
||
{
|
||
var layer = GimmickLayer.Current;
|
||
if (layer == null) return false;
|
||
foreach (var g in layer.Items)
|
||
if (g.BlocksMove && !g.Broken && !g.Removed && g.Shape.SegmentTouches(a, b, 0.2f)) return true;
|
||
return false;
|
||
}
|
||
|
||
/// <summary>접근 거리 = 가장 가까운 적까지 직선 거리 + 길이 막혔으면 우회 비용.</summary>
|
||
float ApproachMetric(Vector2 p)
|
||
{
|
||
float best = float.MaxValue;
|
||
foreach (var e in bm.AliveUnits(Faction.Enemy))
|
||
{
|
||
float d = Vector2.Distance(p, e.Position);
|
||
if (d > best) continue;
|
||
if (Blocked(p, e.Position)) d += 6f;
|
||
best = Mathf.Min(best, d);
|
||
}
|
||
return best;
|
||
}
|
||
|
||
public LevelBot(BattleManager bm, System.Random rng, int skill, int dirs, float[] powers)
|
||
{
|
||
this.bm = bm;
|
||
this.rng = rng;
|
||
this.skill = skill;
|
||
this.dirs = Mathf.Max(4, dirs);
|
||
this.powers = powers != null && powers.Length > 0 ? powers : new[] { 0.45f, 0.75f, 0.95f };
|
||
}
|
||
|
||
// 사람 손 오차: 게이지 타이밍 표준편차(초) · 방향(도) · 최고 점수 선택 확률 · 그 밖 = 상위 n 중 무작위
|
||
float TimingSigma { get { return skill >= 1 ? 0.04f : 0.09f; } }
|
||
float AngleSigma { get { return skill >= 1 ? 1.5f : 4f; } }
|
||
float BestProb { get { return skill >= 1 ? 0.92f : 0.55f; } }
|
||
int TopN { get { return skill >= 1 ? 2 : 4; } }
|
||
|
||
/// <summary>즉시형 액티브(준비됨 · 교전 거리 안 적이 있을 때) 1개 사용 → true(다시 판단).</summary>
|
||
public bool UseInstantSkills()
|
||
{
|
||
foreach (var u in bm.AliveUnits(Faction.Player))
|
||
{
|
||
if (u.Npc) continue;
|
||
var s = bm.Skills.Of(u);
|
||
if (s == null || !s.HasActive || s.Active.Trigger == SkillTrigger.NextAction) continue;
|
||
if (bm.Skills.StateOf(u) != SkillSystem.ActiveState.Ready) continue;
|
||
if (s.Active.First(SkillKeys.Teleport) != null) continue;
|
||
if (NearestEnemy(u.Position) > SkillMods.SlingMax(u) * 1.6f + 2f) continue; // 아직 교전 전 = 아낌
|
||
bm.ForcePhase(BattlePhase.Resolving);
|
||
Sim.Run(bm.Skills.Instant(s));
|
||
SkillsUsed++;
|
||
if (!bm.CheckBattleEnd()) bm.ForcePhase(BattlePhase.PlayerTurn);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
float NearestEnemy(Vector2 p)
|
||
{
|
||
float best = float.MaxValue;
|
||
foreach (var e in bm.AliveUnits(Faction.Enemy)) best = Mathf.Min(best, Vector2.Distance(p, e.Position));
|
||
return best;
|
||
}
|
||
|
||
/// <summary>다음 행동 1개(null = 행동할 유닛이 없거나 남은 추가 이동이 쓸모없음 → 턴 넘김).</summary>
|
||
public Plan Decide()
|
||
{
|
||
var actors = new List<Unit>();
|
||
foreach (var u in bm.AliveUnits(Faction.Player))
|
||
if (!u.Npc && bm.CanAct(u)) actors.Add(u);
|
||
if (actors.Count == 0) return null;
|
||
var snap = Sim.Take(bm);
|
||
gimHp.Clear();
|
||
var layer0 = GimmickLayer.Current;
|
||
if (layer0 != null)
|
||
foreach (var g in layer0.Items)
|
||
if (g.BlocksMove && g.MaxHp > 0 && !g.Broken && !g.Removed) gimHp[g] = g.Hp;
|
||
var resolver = new ActionResolver(bm.Config, bm, new System.Random(rng.Next()));
|
||
var list = new List<Plan>();
|
||
foreach (var u in actors)
|
||
{
|
||
var sk = bm.Skills.Of(u);
|
||
bool canSkill = sk != null && sk.HasActive && sk.Active.Trigger == SkillTrigger.NextAction && bm.Skills.StateOf(u) == SkillSystem.ActiveState.Ready;
|
||
foreach (var c in Candidates(u))
|
||
{
|
||
for (int s = 0; s < (canSkill ? 2 : 1); s++)
|
||
{
|
||
var p = new Plan { U = u, Dir = c.Key, Power = c.Value, UseSkill = s == 1 };
|
||
p.Target = TargetOf(u, p.Dir, p.Power);
|
||
p.Crit = CritOf(u, p.Power);
|
||
p.Score = Eval(resolver, p, snap);
|
||
p.Gimmick = lastGimmick;
|
||
list.Add(p);
|
||
}
|
||
}
|
||
}
|
||
if (list.Count == 0) return null;
|
||
list.Sort((a, b) => b.Score.CompareTo(a.Score));
|
||
if (list[0].U.BonusMoveAvailable && list[0].Score < 1f && bm.OnlyBonusMovesRemain()) return null; // 쓸모없는 추가 이동 = 건너뜀
|
||
var pick = rng.NextDouble() < BestProb ? list[0] : list[rng.Next(Mathf.Min(TopN, list.Count))];
|
||
// 사람 손 오차
|
||
var res = new Plan { U = pick.U, UseSkill = pick.UseSkill, Score = pick.Score, Gimmick = pick.Gimmick };
|
||
if (pick.Gimmick > 0) GimmickHits++;
|
||
float cycle = SkillMods.GaugeCycle(pick.U);
|
||
float power = pick.Power;
|
||
bool drag = AimRules.DragMode;
|
||
if (drag) power = Mathf.Clamp(power * (1f + Gauss() * DragSigma), 0.05f, 1f); // 끌기 조준 = 끈 거리 오차(게이지와 무관)
|
||
else if (cycle > 0f) power = Mathf.Clamp(power + Gauss() * TimingSigma / cycle, 0.05f, 1f);
|
||
float ang = Gauss() * AngleSigma * Mathf.Deg2Rad;
|
||
var d = pick.Dir;
|
||
res.Dir = new Vector2(d.x * Mathf.Cos(ang) - d.y * Mathf.Sin(ang), d.x * Mathf.Sin(ang) + d.y * Mathf.Cos(ang));
|
||
res.Power = power;
|
||
res.Target = TargetOf(pick.U, res.Dir, power);
|
||
if (drag)
|
||
{
|
||
bool crit, miss;
|
||
DragGaugeOutcome(pick.U, out crit, out miss);
|
||
res.Crit = crit;
|
||
res.Miss = miss;
|
||
if (miss) Misses++;
|
||
}
|
||
else res.Crit = CritOf(pick.U, power);
|
||
if (res.Crit) Crits++;
|
||
if (res.UseSkill)
|
||
{
|
||
bm.Skills.Of(res.U).Reserved = true;
|
||
SkillsUsed++;
|
||
}
|
||
return res;
|
||
}
|
||
|
||
bool CritOf(Unit u, float power)
|
||
{
|
||
if (AimRules.DragMode) return false; // 끌기 조준 = 치명타는 판정 게이지 타이밍(DragGaugeOutcome) · 후보 평가는 일반 피해로
|
||
return SkillMods.GaugeCycle(u) > 0f && power >= bm.Config.aimGaugeCritFrom;
|
||
}
|
||
|
||
/// <summary>끌기 조준에서 끈 거리의 상대 오차(표준편차).</summary>
|
||
float DragSigma { get { return skill >= 1 ? 0.05f : 0.10f; } }
|
||
|
||
/// <summary>
|
||
/// 끌기 조준 판정 게이지(게임 SlingshotInput.RollZones · DragGauge 와 같은 표 값): 칸을 무작위로 놓고, 사람이 빨간 칸 가운데를 노려 놓을 때
|
||
/// 타이밍 오차(TimingSigma 초) ÷ 한 방향 시간 = 표시선 위치 오차 → 빨강 = 치명타 · 원거리 명중 칸 밖 = 빈 칸(이동만).
|
||
/// </summary>
|
||
void DragGaugeOutcome(Unit u, out bool crit, out bool miss)
|
||
{
|
||
float c = Mathf.Clamp(IbUi.Num("crit_zone_size", 0.15f), 0.02f, 1f);
|
||
bool ranged = UnitTypeInfo.IsRanged(u.Type);
|
||
float hitLo = 0f, hitHi = 1f, critLo;
|
||
if (ranged)
|
||
{
|
||
float g = Mathf.Clamp(IbUi.Num("hit_zone_ranged", 0.45f), c, 1f);
|
||
hitLo = (float)rng.NextDouble() * (1f - g);
|
||
hitHi = hitLo + g;
|
||
critLo = hitLo + (float)rng.NextDouble() * (g - c);
|
||
}
|
||
else
|
||
{
|
||
float min = Mathf.Clamp(IbUi.Num("crit_zone_min", 0.15f), 0f, 1f - c);
|
||
critLo = min + (float)rng.NextDouble() * (1f - c - min);
|
||
}
|
||
float sweep = IbUi.Num("crit_sweep_sec", 0.45f);
|
||
if (u.GaugeCycleSec > 0f) sweep *= Mathf.Max(0.1f, SkillMods.GaugeCycle(u) / u.GaugeCycleSec);
|
||
float pos = critLo + c * 0.5f + Gauss() * TimingSigma / Mathf.Max(0.05f, sweep);
|
||
pos = Mathf.PingPong(Mathf.Abs(pos), 1f); // 막대 끝에서 되돌아옴
|
||
crit = pos >= critLo && pos <= critLo + c;
|
||
miss = ranged && (pos < hitLo || pos > hitHi);
|
||
}
|
||
|
||
Vector2 TargetOf(Unit u, Vector2 dir, float power)
|
||
{
|
||
float g = SkillMods.GaugeCycle(u) > 0f ? Mathf.Clamp01(power) : 1f;
|
||
float dist = Mathf.Max(bm.Config.minDragDistance, SkillMods.SlingMax(u) * g);
|
||
return bm.Board.ClampInside(u.Position + dir.normalized * dist, u.Radius);
|
||
}
|
||
|
||
/// <summary>후보 = (방향, 게이지): 방위 dirs × powers + 적을 겨눈 것(근접 = 중심까지 · 가득 / 원거리 = 적 중심 거리).</summary>
|
||
List<KeyValuePair<Vector2, float>> Candidates(Unit u)
|
||
{
|
||
var res = new List<KeyValuePair<Vector2, float>>();
|
||
float max = SkillMods.SlingMax(u);
|
||
for (int i = 0; i < dirs; i++)
|
||
{
|
||
float a = (i + 0.5f * (u.GetInstanceID() & 1)) * Mathf.PI * 2f / dirs;
|
||
var d = new Vector2(Mathf.Cos(a), Mathf.Sin(a));
|
||
foreach (var k in powers) res.Add(new KeyValuePair<Vector2, float>(d, k));
|
||
}
|
||
bool ranged = UnitTypeInfo.IsRanged(u.Type);
|
||
float reach = ranged ? SkillMods.Range(u) : max;
|
||
int aimed = 0;
|
||
var foes = bm.AliveUnits(Faction.Enemy);
|
||
foes.Sort((a, b) => Vector2.Distance(u.Position, a.Position).CompareTo(Vector2.Distance(u.Position, b.Position)));
|
||
foreach (var e in foes)
|
||
{
|
||
if (aimed >= 8) break;
|
||
var v = e.Position - u.Position;
|
||
float dist = v.magnitude;
|
||
if (dist < 1e-3f || dist - e.Radius - u.Radius > reach * 1.25f) continue;
|
||
aimed++;
|
||
var d = v / dist;
|
||
res.Add(new KeyValuePair<Vector2, float>(d, Mathf.Clamp01(dist / max)));
|
||
if (!ranged) res.Add(new KeyValuePair<Vector2, float>(d, 0.95f));
|
||
}
|
||
if (!ranged) // 부술 수 있는 장애물(성문 · 목책)을 겨눈 것
|
||
foreach (var g in gimHp.Keys)
|
||
{
|
||
var v = g.Shape.Center - u.Position;
|
||
float dist = v.magnitude;
|
||
if (dist < 1e-3f || dist - g.Shape.BoundingRadius > max * 1.1f) continue;
|
||
res.Add(new KeyValuePair<Vector2, float>(v / dist, 0.95f));
|
||
}
|
||
return res;
|
||
}
|
||
|
||
float Eval(ActionResolver resolver, Plan p, Sim.Snapshot snap)
|
||
{
|
||
bool wasActive = Sim.Active, wasLive = Sim.LiveRolls;
|
||
Sim.Active = true;
|
||
Sim.LiveRolls = false;
|
||
var u = p.U;
|
||
float score;
|
||
try
|
||
{
|
||
if (p.UseSkill) bm.Skills.Of(u).Reserved = true;
|
||
u.GaugeCrit = p.Crit;
|
||
bool moveOnly = u.BonusMoveAvailable && !bm.Skills.BonusCanAttack(u);
|
||
var o = new ActionOutcome();
|
||
Sim.Run(resolver.Resolve(u, p.Target, moveOnly, o));
|
||
u.GaugeCrit = false;
|
||
Sim.Run(bm.ApplyOverwatch(u, o));
|
||
score = Score(u, snap, o, p.UseSkill);
|
||
}
|
||
finally
|
||
{
|
||
u.GaugeCrit = false;
|
||
Sim.Active = wasActive;
|
||
Sim.LiveRolls = wasLive;
|
||
Sim.Restore(bm, snap);
|
||
}
|
||
return score;
|
||
}
|
||
|
||
float Score(Unit u, Sim.Snapshot snap, ActionOutcome o, bool useSkill)
|
||
{
|
||
float s = 0f, dealt = 0f;
|
||
Vector2 start = u.Position;
|
||
foreach (var x in snap.Units)
|
||
{
|
||
var v = x.U;
|
||
if (v == null) continue;
|
||
if (v == u) start = x.Pos;
|
||
if (x.Hp <= 0) continue;
|
||
int dmg = Mathf.Max(0, x.Hp - v.Hp);
|
||
if (v.Faction == Faction.Enemy)
|
||
{
|
||
if (SkillSystem.IsSummon(v)) continue;
|
||
dealt += dmg;
|
||
s += dmg * (v.IsBoss ? 1.2f : 1f);
|
||
if (v.Hp <= 0) s += 30f + v.Atk * 1.5f;
|
||
}
|
||
else
|
||
{
|
||
s -= dmg * (v.Npc ? 3f : 1.3f);
|
||
if (v.Hp <= 0) s -= 60f + v.Atk * 2f;
|
||
}
|
||
}
|
||
var layer = GimmickLayer.Current;
|
||
lastGimmick = 0;
|
||
if (layer != null)
|
||
foreach (var a in layer.Affected)
|
||
{
|
||
if (a.Unit == null) continue;
|
||
float val = 8f + a.Value;
|
||
s += a.Unit.Faction == Faction.Enemy ? val : -val;
|
||
if (a.Unit.Faction == Faction.Enemy) lastGimmick++;
|
||
}
|
||
if (o.Chains > 0) s += 6f * o.Chains;
|
||
// 막는 지형 부수기(성문 · 목책): 적에게 가는 길을 막고 있으면 크게 · 부서지면 길이 열림
|
||
foreach (var kv in gimHp)
|
||
{
|
||
var g = kv.Key;
|
||
int d = Mathf.Max(0, kv.Value - g.Hp);
|
||
bool broke = g.Broken || g.Removed;
|
||
if (d == 0 && !broke) continue;
|
||
bool inWay = false;
|
||
foreach (var e in bm.AliveUnits(Faction.Enemy))
|
||
if (g.Shape.SegmentTouches(start, e.Position, 0.3f)) { inWay = true; break; }
|
||
s += d * (inWay ? 10f : 2f) + (broke ? (inWay ? 25f : 5f) : 0f);
|
||
}
|
||
if (!u.IsAlive) return s;
|
||
// 다음 적 턴 위협(닿을 수 있는 적의 공격 × 상성 · 원거리 유닛은 더 조심)
|
||
float threat = 0f;
|
||
foreach (var e in bm.AliveUnits(Faction.Enemy))
|
||
{
|
||
float gap = Vector2.Distance(e.Position, u.Position) - e.Radius - u.Radius;
|
||
float reach = UnitTypeInfo.IsRanged(e.Type) ? SkillMods.Range(e) : SkillMods.SlingMax(e);
|
||
if (gap <= reach) threat += e.Atk * bm.Config.Matchup(e.Type, u.Type) * 0.6f;
|
||
}
|
||
float w = UnitTypeInfo.IsRanged(u.Type) ? 0.5f : 0.3f;
|
||
s -= Mathf.Min(threat, u.Hp) * w;
|
||
if (threat >= u.Hp) s -= 25f;
|
||
if (dealt <= 0f)
|
||
{
|
||
float before = ApproachMetric(start), after = ApproachMetric(u.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 += 3f * gain;
|
||
}
|
||
if (useSkill) s -= 15f; // 피해 없는 액티브 = 낭비
|
||
}
|
||
return s;
|
||
}
|
||
|
||
float Gauss()
|
||
{
|
||
double u1 = 1.0 - rng.NextDouble(), u2 = rng.NextDouble();
|
||
return (float)(Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Cos(2.0 * Math.PI * u2));
|
||
}
|
||
}
|
||
}
|