using System;
using System.Collections.Generic;
using UnityEngine;
namespace TKS.OutGame
{
/// 연의 전기 편 1개의 진행(연의 = normal · 열전 = hard · [승리, 도전 1, 도전 2]).
[Serializable]
public class ScenarioEpisode
{
public string id = "";
public bool[] normal = new bool[3];
public bool[] hard = new bool[3];
public bool allStar;
[Tooltip("여러 막인 편(서장)에서 이긴 가장 높은 막(0 = 없음) — 상세 두루마리 막 버튼의 열림 · 2026-11-18 PD 「버튼 형태로 이벤트를 감상」")]
public int acts;
[Tooltip("클리어 도장 연출을 본 편(처음 한 번만 찍히는 연출 · 그 뒤 = 찍힌 채) — 2026-11-18 PD 「옥새 컨셉의 클리어 도장」")]
public bool stamped;
}
[Serializable]
public class ScenarioState
{
public List episodes = new List();
[Tooltip("보유하지 않은 영웅의 조각(주역 조각 · 모아서 획득 · 필요 수 = 추후)")]
public List heroShards = new List();
public bool serverView;
public List serverUnlocked = new List();
public ScenarioEpisode Get(string id, bool create)
{
foreach (var e in episodes)
if (e.id == id) return e;
if (!create) return null;
var n = new ScenarioEpisode { id = id };
episodes.Add(n);
return n;
}
}
///
/// 연의 전기 규칙(기기 세이브 모드 · 서버 `/tks/modes/scenario` 와 같은 보상) — 입장 군량 scenario.stamina_cost · 지면 refund_on_lose_pct 환급 ·
/// 첫 승리 reward_normal / reward_hard · 도전 조건마다 *_challenge_gem · 6개 모두 reward_all_star · 주역 조각 = 보유 여부와 관계없이(reward_hero_shard always).
///
public static class ScenarioModeRules
{
public const string Kind = "scenario";
const string M = "scenario";
/// 연의 전기 화면 글자 표(scn_screen texts 와 같은 경로).
public const string TextTable = "UI/Scenario/scn_text";
public static List Battles()
{
var res = new List(ContentTables.Rows("scenario_battles"));
res.Sort((a, b) => a.I("n_no").CompareTo(b.I("n_no")));
return res;
}
public static bool Unlocked(SaveData d, ContentRow b)
{
if (d.scenario.serverView) return d.scenario.serverUnlocked.Contains(b.S("s_id"));
if (TestOpen) return true; // 플레이 테스트 「전 스테이지 열기」 = 연의 전기 편도 모두 열림(2026-11-18 PD 「이 PC 에서 연의전기가 실행이 안돼」)
int ch, st;
if (!ArenaRules.ParseStageKey(b.S("s_unlock_stage"), out ch, out st)) return true;
var s = d.Stage(ch, st, false);
return s != null && s.clears > 0;
}
public static bool HardOpen(SaveData d, string id)
{
if (TestOpen) return true; // 플레이 테스트 「전 스테이지 열기」 = 열전도 열림(2026-11-19 PD 「연의 전기가 잠긴 상태이므로 테스트 편의를 위해 모두 개방」)
var e = d.scenario.Get(id, false);
return e != null && e.normal[0];
}
public static string Can(OutGameData db, SaveData d, string id, bool hard, DateTime nowUtc)
{
var b = ContentTables.Find("scenario_battles", "s_id", id);
if (b == null) return "없는 편";
if (!Unlocked(d, b)) return b.S("s_unlock_ko") + " 뒤 열림";
if (hard && !HardOpen(d, id)) return "열전 = 연의를 이긴 뒤";
EconomyRules.TickStamina(db, d, nowUtc);
int cost = Cost;
if (cost > 0 && d.stamina < cost) return "군량이 부족합니다 — 필요 " + cost;
return null;
}
///
/// 입장 군량(content_modes_config scenario.stamina_cost · 0 = 군량 없이 도전 — 2026-11-18 PD 「군량을 소모하지 않고 도전할 수 있는 컨텐츠로 변경」) ·
/// 시험 메뉴 「군량 면제」면 0.
///
public static int Cost
{
get { return FreeEntry ? 0 : Mathf.Max(0, ContentTables.Int(M, "stamina_cost")); }
}
///
/// 플레이 테스트 「TKS/테스트/전 스테이지 열기 (군량 면제)」가 켜져 있으면 연의 전기도 군량을 보지도 쓰지도 않는다(지면 환급도 없음)
/// — 2026-11-18 PD 「연의 전기를 진행하려는데 입장 재화가 없어 진행할 수 없어 · 입장 재화 소진 문제를 해결해줘」(그 면제가 출정에만 걸려 있었음).
///
static bool FreeEntry
{
get { return TestOpen; }
}
/// 시험 메뉴는 실제 저장(PD Play)에서만 — 메모리 저장(자동 테스트 · 검증 캡처)은 PC 의 시험 설정과 무관하게 실제 규칙.
static bool TestOpen
{
get { return TestOptions.UnlockAllStages && !SaveStore.MemoryOnly; }
}
/// 입장 = 군량 사용.
public static string Enter(OutGameData db, SaveData d, string id, bool hard, DateTime nowUtc)
{
var why = Can(db, d, id, hard, nowUtc);
if (why != null) return why;
if (Cost > 0) EconomyRules.SpendStamina(db, d, Cost, nowUtc);
return null;
}
/// 여러 막인 편(서장)에서 이긴 가장 높은 막(0 = 없음).
public static int ActsCleared(SaveData d, string id)
{
var e = d != null ? d.scenario.Get(id, false) : null;
return e != null ? Mathf.Max(e.acts, e.normal[0] ? int.MaxValue / 2 : 0) : 0; // 예전 세이브(막 기록 전에 편을 이김) = 모든 막 열림
}
/// 막 a 를 할 수 있는가 — 1막 · 앞 막을 이긴 막 · 시험 메뉴 「전 스테이지 열기」.
public static bool ActOpen(SaveData d, string id, int a)
{
return a <= 1 || TestOpen || ActsCleared(d, id) >= a - 1;
}
/// 출전 버튼이 고르는 막 = 아직 안 이긴 첫 막(모두 이겼으면 1막).
public static int NextAct(SaveData d, string id, int acts)
{
int c = ActsCleared(d, id);
return c >= acts ? 1 : Mathf.Clamp(c + 1, 1, Mathf.Max(1, acts));
}
///
/// 여러 막인 편(서장)의 막 하나 끝(기기 세이브 모드) — 이기면 막 기록 · 마지막 막 = 편 결과(보상 · Result) · 중간 막 = 보상 없이 「n막 완료」.
/// 2026-11-18 PD 「연의 전기를 자동으로 1 → 2 → 3 페이즈 단위로 넘어가지 않고 버튼 형태로」.
///
public static ModeResult ActResult(OutGameData db, SaveData d, string id, int act, int acts, bool win, List lines, DateTime nowUtc, System.Random rng)
{
if (win)
{
var e = d.scenario.Get(id, true);
e.acts = Mathf.Max(e.acts, act);
}
if (!win || act >= acts) return Result(db, d, id, false, win, null, lines, nowUtc, rng);
UiText.Use(TextTable); // 연의 전기 화면을 거치지 않은 결과(테스트)도 글자 표
var b = ContentTables.Find("scenario_battles", "s_id", id);
var m = new ModeResult { kind = Kind, win = true, title = (b != null ? b.S("s_title_ko") : id) + " " + UiText.F("scn_act_short", new[] { act.ToString(System.Globalization.CultureInfo.InvariantCulture) }) };
if (lines != null) m.lines.AddRange(lines);
m.lines.Add(UiText.F("scn_act_done", new[] { act.ToString(System.Globalization.CultureInfo.InvariantCulture), (act + 1).ToString(System.Globalization.CultureInfo.InvariantCulture) }));
return m;
}
/// 끝(기기 세이브 모드) — 보상 · 진행 기록 · 지면 군량 환급.
public static ModeResult Result(OutGameData db, SaveData d, string id, bool hard, bool win, bool[] challenges, List lines, DateTime nowUtc, System.Random rng)
{
var b = ContentTables.Find("scenario_battles", "s_id", id);
var m = new ModeResult { kind = Kind, win = win, title = (b != null ? b.S("s_title_ko") : id) + (hard ? " (열전)" : " (연의)") };
if (lines != null) m.lines.AddRange(lines);
if (!win)
{
int back = Mathf.RoundToInt(Cost * ContentTables.Num(M, "refund_on_lose_pct") / 100f);
if (back > 0)
{
EconomyRules.AddStamina(db, d, back, nowUtc);
m.lines.Add("패배 — 군량 " + back + " 환급"); // 입장 군량 0 = 환급 줄 없음
}
else
{
UiText.Use(TextTable);
m.lines.Add(UiText.T("scn_lose")); // 결과 창이 비지 않게(포기 · 패배)
}
return m;
}
var e = d.scenario.Get(id, true);
var st = hard ? e.hard : e.normal;
var got = new List();
// 서장(n_no 0) 첫 승리 = reward_prologue 꾸러미(주역 영웅 획득 · PD 2026-11-24) · 줄이 없으면 다른 편과 같은 reward_normal
bool prologue = !hard && b != null && b.I("n_no") == 0 && ContentTables.Has(M, "reward_prologue");
if (!st[0]) GiveParts(db, d, b, ContentTables.Str(M, prologue ? "reward_prologue" : hard ? "reward_hard" : "reward_normal"), rng, got);
else if (ContentTables.Str(M, "reward_hero_shard") == "always") // 다시 이겨도 주역 조각(보유 여부 무관 · 양 = 첫 승리 꾸러미의 shard)
foreach (var kv in ContentTables.ParseMap(ContentTables.Str(M, hard ? "reward_hard" : "reward_normal")))
if (kv.Key == "shard") GiveShard(d, b, Mathf.RoundToInt(kv.Value), db, got);
st[0] = true;
// 도전 조건 보옥 · 조건 6개 꾸러미 = 표에 줄이 있을 때만(PD 2026-11-24 ⑦ 로 줄 삭제 = 기록만 남는다)
string gemKey = hard ? "reward_hard_challenge_gem" : "reward_normal_challenge_gem";
int gem = ContentTables.Has(M, gemKey) ? ContentTables.Int(M, gemKey) : 0;
for (int i = 0; i < 2 && challenges != null && i < challenges.Length; i++)
if (challenges[i] && !st[i + 1])
{
st[i + 1] = true;
if (gem <= 0) continue;
d.gem += gem;
got.Add("도전 " + (i + 1) + " 보옥 +" + gem);
}
if (!e.allStar && Array.TrueForAll(e.normal, x => x) && Array.TrueForAll(e.hard, x => x))
{
e.allStar = true;
if (ContentTables.Has(M, "reward_all_star")) GiveParts(db, d, b, ContentTables.Str(M, "reward_all_star"), rng, got);
}
if (got.Count > 0) m.lines.Add(string.Join(" · ", got.ToArray()));
return m;
}
static void GiveParts(OutGameData db, SaveData d, ContentRow b, string parts, System.Random rng, List got)
{
foreach (var kv in ContentTables.ParseMap(parts))
{
int n = Mathf.RoundToInt(kv.Value);
if (kv.Key == "gem")
{
d.gem += n;
got.Add("보옥 +" + n);
}
else if (kv.Key == "gold")
{
d.gold += n;
got.Add("골드 +" + n);
}
else if (kv.Key == "shard") GiveShard(d, b, n, db, got);
else if (kv.Key == "hero") GiveHero(d, b, n, db, got);
else if (kv.Key.EndsWith("_chest"))
for (int i = 0; i < n; i++)
{
var c = TreasureRules.AddChest(db, d, kv.Key.Substring(0, kv.Key.Length - "_chest".Length), rng);
if (c != null) got.Add(db.Chests.Get(c).nameKo);
}
}
}
/// 그 편 주역(s_reward_hero) 영웅을 얻는다(★ = 태생 희귀도 · Lv 1) — 이미 보유 = 조각 n 개(GiveShard).
static void GiveHero(SaveData d, ContentRow b, int n, OutGameData db, List got)
{
var def = b != null ? db.Heroes.Get(b.S("s_reward_hero")) : null;
if (def == null) return;
if (!HeroRules.Grant(db, d, def, HeroRules.GearSlotCount(db)))
{
GiveShard(d, b, n, db, got);
return;
}
UiText.Use(TextTable);
got.Add(UiText.F("scn_reward_hero", new[] { def.nameKo, new string('★', Mathf.Clamp(def.rarity, 1, 5)) }));
}
static void GiveShard(SaveData d, ContentRow b, int n, OutGameData db, List got)
{
if (b == null || n <= 0) return;
string hero = b.S("s_reward_hero");
GoodsRules.AddHeroShards(d, hero, n); // 보유 = 그 영웅 조각 · 미보유 = 영입 조각으로 쌓인다(hero_unlock)
var def = db.Heroes.Get(hero);
got.Add((def != null ? def.nameKo : hero) + " 조각 +" + n);
}
}
}