using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace TKS
{
///
/// 연의 전기 서장(편 n_no 0 · 도원결의) = 연의 모드 전투 — 막(n_acts) 하나가 전투 하나(2026-11-18 PD 「연의 전기 스테이지와 일반 출정 스테이지는 별개」 ·
/// 「자동으로 1 → 2 → 3 페이즈 단위로 넘어가지 않고 버튼 형태로 이벤트를 감상」 = 상세 두루마리 아래 막 버튼으로 고름 · 막 승리 = 결과 화면).
/// 지도(배치 · 기믹 · 학습 안내) = 출정 n_spec_chapter 장 학습 판 Act 의 표를 빌려 씀(UsesTutorialPlan) + 막 덮어쓰기(ContentModes/scenario_layout.csv 의 ref 아닌 행 ·
/// Resources/Scenario/scenario_guide.csv 안내 문구) — 진행 기록 · 보상 = 연의 세이브(ScenarioModeRules · 막 진행 = ScenarioEpisode.acts · 보상 = 마지막 막).
/// 시나리오 연출 · 판 꾸밈 = s_battle_id + 막(출정 판에는 붙지 않음). 학습 안내는 서장에서 매번 보인다(TutorialRules.ForceFirstPlay).
///
public class PrologueRules : ModeBattleRules
{
public string BattleId = "";
public string TitleKo = "";
public int Chapter = 1;
public int Act = 1;
public int Acts = 1;
public override bool UsesTutorialPlan
{
get { return true; }
}
public override bool CanGiveUp
{
get { return true; }
}
public override string ScenarioBattleId
{
get { return BattleId; }
}
public override int ScenarioAct
{
get { return Act; }
}
/// 마지막 막인가(이기면 편 완료 · 보상).
public bool LastAct
{
get { return Act >= Acts; }
}
/// 막 a 의 판 정의 = 출정 (chapter, a) 정의의 사본(연출·기믹·배치 표 열쇠는 그대로 · 제목만 연의) — 없으면 null.
public BalanceConfig.StageDef MakeStage(BalanceConfig cfg, int a)
{
if (cfg == null || cfg.stages == null) return null;
foreach (var s in cfg.stages)
{
if (s.chapter != Chapter || s.stage != a) continue;
var c = JsonUtility.FromJson(JsonUtility.ToJson(s));
c.title = TitleKo + " " + a + "/" + Acts + "막";
c.subtitle = "연의 전기";
c.bgTheme = ""; // 바닥 = 판 꾸밈 표(scenario_props `_bg`) — 출정 배경 테마와 연동하지 않음
return c;
}
return null;
}
/// 막 이름(scenario_layout ref 행의 s_name_ko · 막 버튼 글자) — 없으면 빈칸.
public static string ActTitle(string battleId, int act)
{
foreach (var r in ContentTables.Rows("scenario_layout"))
if (r.S("s_battle") == battleId && r.I("n_act", 1) == act && r.S("e_side") == "ref") return r.S("s_name_ko");
return "";
}
/// 막 덮어쓰기 — scenario_layout 의 그 막 ref 아닌 행(슬롯 ≥ 1) = 학습 판 슬롯을 바꿈 · s_tag downed = 기절한 구출 대상 · 안내 문구 = scenario_guide.csv.
public override void AdjustTutorial(TutorialPlan plan)
{
if (plan == null) return;
gimmickRows.Clear();
holdSlots.Clear();
slingBySlot.Clear();
var foes = new List();
string artPre, namePre;
plan.EnemyBase(out artPre, out namePre);
foreach (var r in ContentTables.Rows("scenario_layout"))
{
if (r.S("s_battle") != BattleId || r.I("n_act", 1) != Act) continue;
var row = ContentLayoutRow.From(r);
if (row.side == "ref" || row.slot <= 0) continue;
if (row.tag == HoldTag) holdSlots.Add(row.slot);
float sm = r.F("f_sling_mult", 0f);
if (sm > 0f) slingBySlot[row.slot] = sm; // 그 막 그 유닛의 슬링 거리 배율(빈칸 = 1 · 2026-11-19 PD 2막 장비 최대 돌진 +10 %)
if (row.side == "ally") plan.OverrideSlot(row.slot, TutSide.Ally, row.unitId, row.pos, row.hpMult, row.atkMult, false);
else if (row.side == "npc") plan.OverrideSlot(row.slot, TutSide.Npc, row.unitId, row.pos, row.hpMult, row.atkMult, row.tag == DownedTag);
else if (row.side == "gimmick") gimmickRows.Add(row);
else if (row.side == "enemy") // 그 막의 적 전체(한 줄이라도 있으면 학습 판 적 대신 · 2026-11-18 PD 2막 다시 짬)
{
var t = row.UnitType;
foes.Add(new TutorialEnemy
{
slot = row.slot,
spawn = new BalanceConfig.EnemySpawn
{
type = t, position = row.pos, hpMult = row.hpMult, atkMult = row.atkMult,
name = row.nameKo.Length > 0 ? row.nameKo : (namePre.Length > 0 ? namePre + " " : "") + UnitTypeInfo.Korean(t),
art = artPre + "_" + UnitTypeInfo.Key(t),
},
});
}
}
if (foes.Count > 0) plan.ReplaceEnemies(foes);
var rows = ScenarioData.GuideRows(BattleId, Act);
if (rows != null)
{
foreach (var g in rows)
{
g.chapter = plan.Row.chapter;
g.stage = plan.Row.stage;
}
plan.ReplaceGuide(rows);
}
foreach (var g in ScenarioData.GuideTexts(BattleId, Act)) plan.OverrideGuideText(g.Key, g.Value);
}
public const string DownedTag = "downed";
/// s_tag hold = 첫 적 턴에는 움직이지 않는 적(1막 · 우두머리만 다가와 싸움 · 2026-11-18 PD).
public const string HoldTag = "hold";
readonly List gimmickRows = new List();
readonly HashSet holdSlots = new HashSet();
readonly Dictionary slingBySlot = new Dictionary();
/// 막 배치 표 f_sling_mult(유닛별 슬링 거리 배율 · 빈칸 = 1).
public override float SlingMult(Unit u)
{
float m;
if (u == null || Battle == null || Battle.Tutorial == null || slingBySlot.Count == 0) return 1f;
return slingBySlot.TryGetValue(Battle.Tutorial.SlotOf(u), out m) ? m : 1f;
}
public override bool EnemyActs(Unit e)
{
if (ScenarioEvent.Absent(e)) return false; // 연출이 숨긴(아직 나타나지 않은) 적 = 움직이지 않음(2026-11-19 PD 2막 포위군 · 잔당)
if (Battle == null || Battle.Tutorial == null || holdSlots.Count == 0 || Battle.TurnNumber > 1) return true;
return !holdSlots.Contains(Battle.Tutorial.SlotOf(e));
}
public override void OnBegin()
{
if (Battle.Gimmicks != null) // 막 기믹(scenario_layout gimmick 줄 · 2막 바위)
foreach (var g in gimmickRows) ContentLayout.SpawnGimmick(Battle.Gimmicks, g);
ScenarioEvent.FaceFrontAll(Battle);
// 연출이 없거나(꺼짐) 건너뛰어도 기절은 걸린 채로 — 연출이 있으면 stun 명령이 맞는 순간에 건다
if (!ScenarioEvent.Wants(Battle, Battle.Stage, "stage_start", false)) StunDowned();
}
/// 기절한 구출 대상에 기절 표시(GimmickLayer.Stun · 스턴 이펙트 · 행동불가 표) — 이미 걸려 있으면 그대로.
public void StunDowned()
{
if (Battle == null || Battle.Gimmicks == null) return;
foreach (var u in Battle.AliveUnits(Faction.Player))
if (u.Downed && !SkillStatus.Stunned(u))
{
Battle.Gimmicks.Stun(u, Mathf.Max(1, Mathf.RoundToInt(ScenarioData.EvCfg("downed_stun_turns"))), ""); // 글자 없이(연출 stun 명령은 s_text_ko)
if (u.View != null) u.View.Refresh(); // 기절 = 흐리게(2026-11-19 · 기절 전에는 밝게)
}
}
public override IEnumerator OnTurnStart(Faction f)
{
if (f == Faction.Player) StunDowned();
yield break;
}
/// 서장 앞 막 = 장수 액티브 스킬 잠김(content_modes_config scenario.prologue_skill_lock_act 막까지 · 글자 = prologue_skill_lock_text · 2026-11-19 PD 「1장 2막까지 영웅의 스킬은 잠김 상태로 제공」).
public override string SkillBlocked(Unit u)
{
if (u == null || u.Faction != Faction.Player) return null;
int upTo = ContentTables.Int("scenario", "prologue_skill_lock_act");
return Act <= upTo ? ContentTables.Str("scenario", "prologue_skill_lock_text") : null;
}
/// 기절한 구출 대상이 있는 막 = 적은 조작하는 아군 중 가장 가까운 유닛만 노린다(구출 대상은 지나침 · Unit.PassableFor).
public override Unit EnemyTarget(Unit e)
{
if (Battle == null || e == null) return null;
bool downed = false;
foreach (var u in Battle.AliveUnits(Faction.Player))
if (u.Downed || ScenarioEvent.Absent(u)) downed = true; // 숨은 아군이 있는 막도(2막 1턴 = 관우만 · 기병이 관우에게 정확히 돌진 · 2026-11-19 PD 「자연스러운 슬링샷 동작」)
if (!downed) return null;
Unit best = null;
float bd = float.MaxValue;
foreach (var u in Battle.AliveUnits(Faction.Player))
{
if (u.Npc || u.Downed || ScenarioEvent.Absent(u)) continue;
float d = (u.Position - e.Position).sqrMagnitude;
if (d < bd)
{
bd = d;
best = u;
}
}
return best;
}
}
}