ThreeKingdomsSlingshot/Assets/Scripts/OutGame/FirstFlow/FirstFlowSortie.cs

451 lines
19 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame
{
/// <summary>
/// 출정 첫 스테이지의 스킬 튜토리얼(첫 실행 흐름 · PD 2026-11-24 3차 「유비와 간옹만으로는 클리어가 어려운 편 → 튜토리얼을 제공해 적들을 섬멸」) —
/// 그 스테이지를 처음 깨기 전의 판에서: 적 셋을 유비 앞에 모아 놓고(표 sortie_cluster) 첫 아군 차례에
/// ① 적 하나 「오~ 손님이 오셨군…」 → 유비 「너희들의 악행을 끝내주겠다.」 → 안내 카드(유비의 「이도류 검법」) → 안내 띠: 유비 고르기 → 스킬 버튼 → 모여 있는 적 공격
/// ② 모여 있는 적 가운데 하나라도 맞으면 셋이 한 번에 쓰러짐 · 유비 체력을 표의 비율(50 %)로 낮춤(「반격 피해」)
/// ③ 그 행동이 끝나 다시 아군 차례가 되면 가신 「주공 무리하시면 안됩니다.」 → 안내 카드(간옹의 유세) → 안내 띠: 가신 고르기 → 스킬 버튼 → 유비 쪽으로 쏘기(회복)
/// ④ 그 뒤 = 자유 플레이 · 적을 모두 쓰러뜨리면 지금 규칙대로 승리 · 결과 화면 → (흐름) 가신의 진언 · 군영 안내.
/// 조건 = 출정(컨텐츠 모드 아님) · 일반 난이도 · 표의 스테이지(sortie_stage) · 그 스테이지 클리어 기록 없음 · 유비(서장 보상 영웅)와 가신이 판에 있음 — 아니면 아무것도 하지 않는다.
/// 값 = 표 first_flow_config sortie_* · 문구 = first_flow_text ff_sortie_*(C45). 그림 · 소리 = 다시 씀(연의 말풍선 ScenarioUi.Say · 학습 안내 UI TutorialGuideUI 의 카드 · 띠 · 테 · 손가락).
/// (같은 날 2차의 「복병 궁수 → 간옹 회복」 이벤트는 PD 지시로 뺌 = 시나리오 변경.)
/// </summary>
[DefaultExecutionOrder(1000)] // 학습 안내(TutorialDirector.Update 가 매 프레임 강조를 지우고 다시 그림) 뒤에 그리게
public class FirstFlowSortie : MonoBehaviour
{
static readonly Color EnemyTag = new Color(0.75f, 0.16f, 0.12f);
static readonly Color AllyTag = new Color(0.16f, 0.36f, 0.72f);
public enum Step
{
Off,
Intro, // 시작 대사 · 안내 카드(조작 잠금)
SkillGuide, // 유비 스킬 안내(띠 · 강조)
AfterAttack, // 모여 있던 적이 쓰러짐 → 그 행동이 끝나기를 기다림
RetainerTalk, // 가신 대사 · 안내 카드(조작 잠금)
HealGuide, // 가신 회복 스킬 안내(띠 · 강조)
Done,
}
OutGameRoot root;
FirstFlow flow;
BattleManager battle;
readonly List<Unit> cluster = new List<Unit>();
int hpAtHeal;
string lastBar;
float clock;
bool barPlaced;
GameObject ui;
RectTransform uiRoot;
RectTransform fx;
TalkState talk;
/// <summary>지금 단계 · 유비(서장 보상 영웅) · 가신 · 모아 놓은 적(테스트 · 확인).</summary>
public Step State { get; private set; }
public Unit Victim { get; private set; }
public Unit Retainer { get; private set; }
public IList<Unit> Cluster { get { return cluster; } }
/// <summary>지금 안내 띠 글자(테스트).</summary>
public string Bar { get { return lastBar ?? ""; } }
/// <summary>대사 · 안내 카드가 떠 있어 조작이 잠긴 때.</summary>
public bool Talking { get { return State == Step.Intro || State == Step.RetainerTalk; } }
public static FirstFlowSortie Create(OutGameRoot root, FirstFlow flow)
{
var a = flow.gameObject.AddComponent<FirstFlowSortie>();
a.root = root;
a.flow = flow;
a.battle = root.Battle;
a.battle.StageStarted += a.OnStageStarted;
a.battle.PhaseChanged += a.OnPhase;
return a;
}
void OnDestroy()
{
if (battle == null) return;
battle.StageStarted -= OnStageStarted;
battle.PhaseChanged -= OnPhase;
}
static float At(string[] a, int i, float def)
{
return ScreenTable.At(a, i, def);
}
Unit Ally(string heroId)
{
if (string.IsNullOrEmpty(heroId)) return null;
foreach (var u in battle.AliveUnits(Faction.Player))
if (!u.Npc && u.HeroId == heroId) return u;
return null;
}
/// <summary>판이 놓인 직후 — 조건이 맞으면 유비 앞에 적 셋을 모아 놓고 첫 아군 차례를 기다린다.</summary>
void OnStageStarted()
{
Abort();
if (flow == null || !flow.Available || Sim.Active || battle.Mode != null) return;
int ch, st;
if (!FirstFlowData.ParseStage(FirstFlowData.Str("sortie_stage"), out ch, out st)) return;
var s = battle.Stage;
if (s == null || s.chapter != ch || s.stage != st || root.Session.Hard) return;
var rec = root.Session.Save.Stage(ch, st, false);
if (rec != null && rec.clears > 0) return; // 그 스테이지를 처음 깨기 전에만
Victim = Ally(flow.VictimId);
Retainer = Ally(flow.RetainerId);
if (Victim == null || Retainer == null || Victim == Retainer)
{
Victim = Retainer = null;
return;
}
// 유비에게 가까운 적부터 표의 자리(유비 기준)로 모은다
var foes = battle.AliveUnits(Faction.Enemy);
foes.Sort((a, b) => (a.Position - Victim.Position).sqrMagnitude.CompareTo((b.Position - Victim.Position).sqrMagnitude));
var spots = FirstFlowData.List("sortie_cluster"); // x:y | x:y | x:y (유비에서 · 칸)
for (int i = 0; i < spots.Length && i < foes.Count; i++)
{
var xy = spots[i].Split(':');
if (xy.Length < 2) continue;
var p = Victim.Position + new Vector2(ScreenTable.F(xy[0]), ScreenTable.F(xy[1]));
foes[i].Position = battle.Board != null ? battle.Board.ClampInside(p, foes[i].Radius) : p;
Face(foes[i], Victim.Position);
cluster.Add(foes[i]);
}
if (cluster.Count == 0)
{
Victim = Retainer = null;
return;
}
Face(Victim, cluster[0].Position);
State = Step.Intro;
}
void OnPhase(BattlePhase p)
{
if (p == BattlePhase.StageClear || p == BattlePhase.Defeat) Abort();
}
/// <summary>판이 다시 놓이거나 끝남 — 연출 · 안내를 거둠.</summary>
void Abort()
{
StopAllCoroutines();
running = false;
var gui = GuideUi;
if (gui != null && Talking) gui.SetCard(null);
DestroyUi();
ClearBar();
State = Step.Off;
cluster.Clear();
Victim = Retainer = null;
}
bool running;
bool Ready
{
get { return battle.Phase == BattlePhase.PlayerTurn && !ScenarioEvent.Running && Victim != null && Retainer != null; }
}
void Update()
{
if (State == Step.Off || State == Step.Done) return;
if (Victim == null || Retainer == null || !Victim.IsAlive)
{
Finish();
return;
}
clock += Time.unscaledDeltaTime;
switch (State)
{
case Step.Intro:
if (!running && Ready) StartCoroutine(Intro());
break;
case Step.SkillGuide:
if (ClusterHit()) FellCluster();
else DrawSkillGuide();
break;
case Step.AfterAttack:
if (!running && Ready) StartCoroutine(RetainerTalk());
break;
case Step.HealGuide:
DrawHealGuide();
break;
}
}
// ---------- ① 시작 대사 · 유비 스킬 안내 ----------
IEnumerator Intro()
{
running = true;
battle.ForcePhase(BattlePhase.Resolving); // 대사 동안 조작 잠금(전투 화면 그대로)
var cam = FindFirstObjectByType<CameraController>();
BuildUi(cam);
var tm = FirstFlowData.List("sortie_timing"); // 시작 전 뜸 | 카메라가 옮겨 간 뒤 뜸
yield return Wait(At(tm, 0, 0.4f));
var speaker = cluster.Count > 1 ? cluster[1] : cluster[0]; // 가운데 적
if (cam != null && speaker != null) cam.FocusOn(speaker.Position);
yield return Wait(At(tm, 1, 0.4f));
yield return Say(cam, speaker, FirstFlowData.T("ff_sortie_enemy"), EnemyTag);
if (cam != null && Victim != null) cam.FocusOn(Victim.Position);
yield return Wait(At(tm, 1, 0.4f));
yield return Say(cam, Victim, FirstFlowData.T("ff_sortie_victim"), AllyTag);
yield return Card(FirstFlowData.T("ff_sortie_tip_skill"));
DestroyUi();
if (State != Step.Intro || Victim == null)
{
running = false;
yield break;
}
battle.ForcePhase(BattlePhase.PlayerTurn);
if (battle.Sling != null) battle.Sling.Select(Victim);
lastBar = null;
State = Step.SkillGuide;
running = false;
}
/// <summary>모아 놓은 적 가운데 하나라도 맞았는가(체력이 줄었거나 쓰러짐).</summary>
bool ClusterHit()
{
foreach (var e in cluster)
if (e == null || !e.IsAlive || e.Hp < e.MaxHp) return true;
return false;
}
/// <summary>② 하나가 맞으면 셋이 한 번에 쓰러짐 · 유비 체력을 표의 비율로 낮춤(「반격 피해」).</summary>
void FellCluster()
{
foreach (var e in cluster)
if (e != null && e.IsAlive) e.TakeDamage(e.MaxHp * 10);
int to = Mathf.Max(1, Mathf.RoundToInt(Victim.MaxHp * FirstFlowData.Num("sortie_hp_pct", 0.5f)));
if (Victim.Hp > to)
{
Fx.Popup(Victim.Position, "-" + (Victim.Hp - to), EnemyTag);
Victim.Hp = to;
if (Victim.View != null)
{
Victim.View.OnHit();
Victim.View.Refresh();
}
}
ClearBar();
State = Step.AfterAttack;
}
void DrawSkillGuide()
{
var gui = GuideUi;
if (gui == null) return;
float pulse = 1f + 0.06f * Mathf.Sin(clock * 6f), press = 0.5f + 0.5f * Mathf.Sin(clock * 6f);
var sk = battle.Skills.Of(Victim);
bool canAct = battle.Phase == BattlePhase.PlayerTurn && battle.CanAct(Victim);
bool skillReady = sk != null && !sk.Reserved && sk.ReadyTurn <= battle.TurnNumber;
string bar;
gui.BeginFrame();
if (!canAct) bar = "";
else if (battle.Sling != null && battle.Sling.Selected != Victim)
{
bar = FirstFlowData.T("ff_sortie_bar_select").Replace("{0}", Victim.DisplayName);
gui.Frame(gui.WorldRect(Victim.Position, Vector2.one * (Victim.Radius * 1.6f)), true, pulse);
gui.Finger(gui.ToCanvas(Victim.Position), press, 1f);
}
else if (skillReady)
{
bar = FirstFlowData.T("ff_sortie_bar_skill");
DrawSkillButton(gui, pulse, press);
}
else
{
bar = FirstFlowData.T("ff_sortie_bar_attack");
foreach (var e in cluster)
if (e != null && e.IsAlive) gui.Frame(gui.WorldRect(e.Position, Vector2.one * (e.Radius * 1.6f)), true, pulse);
}
gui.EndFrame();
SetBar(gui, bar);
}
void DrawSkillButton(TutorialGuideUI gui, float pulse, float press)
{
var rt = battle.Hud != null ? battle.Hud.transform.Find("Info/SkillButton") as RectTransform : null;
if (rt == null || !rt.gameObject.activeInHierarchy) return;
var r = gui.UiRect(rt);
gui.Frame(r, false, pulse);
gui.Finger(r.center, press, 1f);
}
// ---------- ③ 가신 대사 · 회복 스킬 안내 ----------
IEnumerator RetainerTalk()
{
running = true;
State = Step.RetainerTalk;
battle.ForcePhase(BattlePhase.Resolving);
var cam = FindFirstObjectByType<CameraController>();
BuildUi(cam);
if (cam != null && Retainer != null) cam.FocusOn(Retainer.Position);
yield return Wait(At(FirstFlowData.List("sortie_timing"), 1, 0.4f));
yield return Say(cam, Retainer, FirstFlowData.T("ff_sortie_retainer"), AllyTag);
yield return Card(FirstFlowData.T("ff_sortie_tip_heal"));
DestroyUi();
if (State != Step.RetainerTalk || Retainer == null || !Retainer.IsAlive)
{
running = false;
if (State == Step.RetainerTalk) Finish();
yield break;
}
// 가신이 이번 턴에 이미 움직였어도 회복 스킬을 써 볼 수 있게 — 다시 행동 가능 · 스킬 바로 사용 가능
if (!battle.CanAct(Retainer)) Retainer.ResetForNewTurn();
var sk = battle.Skills.Of(Retainer);
if (sk != null && !sk.Reserved) sk.ReadyTurn = battle.TurnNumber;
hpAtHeal = Victim != null ? Victim.Hp : 0;
battle.ForcePhase(BattlePhase.PlayerTurn);
if (battle.Sling != null) battle.Sling.Select(Retainer);
lastBar = null;
State = Step.HealGuide;
running = false;
}
void DrawHealGuide()
{
var sk = Retainer.IsAlive ? battle.Skills.Of(Retainer) : null;
bool healed = Victim.Hp > hpAtHeal;
bool canHeal = sk != null && !healed && battle.Phase == BattlePhase.PlayerTurn && battle.CanAct(Retainer);
if (healed || sk == null || (battle.Phase == BattlePhase.PlayerTurn && !battle.CanAct(Retainer)))
{
Finish(); // 회복했거나 가신이 다른 행동을 함 = 안내 끝(자유 플레이)
return;
}
var gui = GuideUi;
if (gui == null) return;
float pulse = 1f + 0.06f * Mathf.Sin(clock * 6f), press = 0.5f + 0.5f * Mathf.Sin(clock * 6f);
string bar;
gui.BeginFrame();
if (!canHeal) bar = "";
else if (sk.Reserved)
{
bar = FirstFlowData.T("ff_sortie_bar_aim").Replace("{0}", Victim.DisplayName);
gui.Frame(gui.WorldRect(Victim.Position, Vector2.one * (Victim.Radius * 1.6f)), true, pulse);
}
else if (battle.Sling != null && battle.Sling.Selected == Retainer)
{
bar = FirstFlowData.T("ff_sortie_bar_skill");
DrawSkillButton(gui, pulse, press);
}
else
{
bar = FirstFlowData.T("ff_sortie_bar_select").Replace("{0}", Retainer.DisplayName);
gui.Frame(gui.WorldRect(Retainer.Position, Vector2.one * (Retainer.Radius * 1.6f)), true, pulse);
gui.Finger(gui.ToCanvas(Retainer.Position), press, 1f);
}
gui.EndFrame();
SetBar(gui, bar);
}
/// <summary>④ 안내 끝 = 자유 플레이(적을 모두 쓰러뜨리면 지금 규칙대로 승리).</summary>
void Finish()
{
ClearBar();
State = Step.Done;
}
// ---------- 안내 띠 · 말풍선 · 카드 ----------
void SetBar(TutorialGuideUI gui, string bar)
{
if (bar == lastBar) return;
lastBar = bar;
if (!barPlaced)
{
gui.PlaceBar(true); // 띠 = 화면 위쪽(아래 유닛 정보 · 스킬 설명을 가리지 않게)
barPlaced = true;
}
gui.SetBar(bar.Length > 0 ? bar : null);
}
void ClearBar()
{
var gui = GuideUi;
if (gui != null && (lastBar != null || barPlaced))
{
gui.SetBar(null);
if (barPlaced) gui.PlaceBar(false);
}
lastBar = null;
barPlaced = false;
}
static TutorialGuideUI GuideUi
{
get { return TutorialDirector.Current != null ? TutorialDirector.Current.Ui : null; }
}
static void Face(Unit u, Vector2 at)
{
if (u != null && u.View != null) u.View.SetFacing(at - u.Position);
}
static IEnumerator Wait(float sec)
{
for (float t = 0f; t < sec; t += Time.unscaledDeltaTime) yield return null;
}
IEnumerator Say(CameraController cam, Unit who, string text, Color tag)
{
if (who == null || !who.IsAlive || cam == null || uiRoot == null) yield break;
talk.Taps = 0;
yield return ScenarioUi.Say(fx, uiRoot, cam.Cam, () => who != null ? ScenarioUi.Head(who) : Vector2.zero, who.DisplayName, tag, text, talk);
}
/// <summary>안내 카드(화면을 누르면 닫힘).</summary>
IEnumerator Card(string text)
{
var gui = GuideUi;
if (gui == null || talk == null) yield break;
gui.PlaceCard(0);
gui.SetCard(text);
talk.Taps = 0;
while (talk != null && talk.Taps == 0 && Talking) yield return null;
gui.SetCard(null);
}
/// <summary>말풍선 층 + 화면 누름 받기(보스 등장 연출 BossIntro 와 같은 구성 · 대사 동안만).</summary>
void BuildUi(CameraController cam)
{
DestroyUi();
talk = new TalkState();
if (cam == null) return;
ui = new GameObject("FirstFlowSortieUI");
UiLayer.Root(ui, cam.Cam, 460, 0.38f, UiLayer.Reference, UiRate.Event);
uiRoot = (RectTransform)ui.transform;
var catcher = UiKit.Fill("Tap", uiRoot).gameObject.AddComponent<Image>();
catcher.color = new Color(0f, 0f, 0f, 0f);
catcher.raycastTarget = true;
var b = catcher.gameObject.AddComponent<Button>();
b.transition = Selectable.Transition.None;
b.onClick.AddListener(() => { if (talk != null) talk.Taps++; });
fx = UiLayer.Group("Fx", uiRoot, UiRate.Frame);
}
void DestroyUi()
{
if (ui != null) Destroy(ui);
ui = null;
uiRoot = null;
fx = null;
}
/// <summary>테스트: 화면 누름 1회(말풍선 · 안내 카드 넘김).</summary>
public void TapForTest()
{
if (talk != null) talk.Taps++;
}
}
}