ThreeKingdomsSlingshot/Assets/Scripts/OutGame/OutGameSession.cs

879 lines
36 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;
using System.Collections.Generic;
using UnityEngine;
namespace TKS.OutGame
{
/// <summary>
/// 아웃게임 실행 상태 = 표(OutGameData) + 세이브(SaveData). 바꾸는 동작은 전부 여기를 거쳐 즉시 저장(Commit)한다.
/// 전투 연결 = 출전 편성(BuildLineup → BattleManager.LineupProvider) · 결과 보상(OnBattleEnd) · 군량(TryPayEntry) · 월드맵 진행(SyncWorldProgress).
/// </summary>
public class OutGameSession
{
public static OutGameSession Current { get; private set; }
/// <summary>세션을 만드는 곳(null = 기기 세이브만 쓰는 기본 세션) — 서버 모드는 Net/ServerLink 가 ServerSession 을 연결한다.</summary>
public static Func<OutGameData, BalanceConfig, SaveData, OutGameSession> Factory;
public readonly OutGameData Db;
public readonly BalanceConfig Cfg;
public SaveData Save;
public System.Random Rng = new System.Random(Environment.TickCount);
public Func<DateTime> Clock = () => DateTime.UtcNow;
public StageReward LastReward;
public bool IsNewUser { get; protected set; }
/// <summary>전투 보상이 뒤늦게 정해졌을 때(서버 모드 = 서버 응답 도착) — 결과 화면이 이 값으로 채운다.</summary>
public event Action<StageReward> RewardReady;
protected void RaiseRewardReady(StageReward r)
{
if (RewardReady != null) RewardReady(r);
}
/// <summary>마지막 연무장 결과(PD #1093 C).</summary>
public ModeResult LastMode;
/// <summary>연무장 결과가 뒤늦게 정해졌을 때(서버 모드 = 서버 응답 도착) — 결과 화면이 이 값으로 채운다.</summary>
public event Action<ModeResult> ModeReady;
protected void RaiseModeReady(ModeResult r)
{
if (ModeReady != null) ModeReady(r);
}
int lastGold;
int lastGem;
public event Action Changed;
public OutGameSession(OutGameData db, BalanceConfig cfg, SaveData save)
{
Db = db;
Cfg = cfg;
Save = save;
}
public DateTime Now
{
get { return Clock(); }
}
public int FormationSlots
{
get { return Cfg.playerSpawnPoints.Length; }
}
/// <summary>세이브를 읽어(없으면 신규 유저) 오프라인 군량 회복 · 일일 초기화 · 월드맵 진행 반영.</summary>
public static OutGameSession Start(OutGameData db, BalanceConfig cfg)
{
var now = DateTime.UtcNow;
var save = SaveStore.Load();
bool isNew = save == null;
if (isNew) save = HeroRules.NewSave(db, cfg.playerSpawnPoints.Length, now);
var s = Factory != null ? Factory(db, cfg, save) : new OutGameSession(db, cfg, save);
s.IsNewUser = isNew;
HeroRules.Sanitize(db, save, s.FormationSlots);
EconomyRules.TickStamina(db, save, now);
EconomyRules.RollDaily(save, now);
ArenaRules.RollDaily(db, save, now);
if (s.EventAvailable) EventRules.Tick(save, now); // 이벤트 접속 반영(출석 칸 · 오늘 카운터 · PD 2026-11-19)
MissionRules.Roll(db, save, now, s.Rng); // 임무 기간 맞춤 · 그날 첫 접속(2026-11-20)
s.lastGold = save.gold;
s.lastGem = save.gem;
s.SyncWorldProgress();
s.Commit();
Current = s;
return s;
}
public void Commit()
{
// 보물 조건 효과 「골드 사용」 = 저장 사이에 줄어든 골드(쓰는 동작은 각자 Commit · PD #1093 C)
if (Save.gold < lastGold)
{
TreasureRules.AddCount(Save, BattleEvents.GoldSpent, lastGold - Save.gold);
EventRules.Count(Save, EventRules.KGoldUse, lastGold - Save.gold, Now); // 이벤트 미션 「금화 n 사용」(같은 기준)
MissionRules.Count(Db, Save, "gold_spent", lastGold - Save.gold, Now, Rng); // 임무 카운터(2026-11-20)
}
if (Save.gem < lastGem) MissionRules.Count(Db, Save, "gem_spent", lastGem - Save.gem, Now, Rng); // 보옥 사용 = 저장 사이에 줄어든 보옥(골드와 같은 방식)
lastGold = Save.gold;
lastGem = Save.gem;
SaveStore.Write(Save, Now);
if (Changed != null) Changed();
}
/// <summary>군량 회복만 반영(화면 갱신 주기 · 저장은 값이 바뀔 때만).</summary>
public void TickStamina()
{
int before = Save.stamina;
EconomyRules.TickStamina(Db, Save, Now);
if (Save.stamina != before) Commit();
}
// ---------- 임무(2026-11-20 · 임무 메뉴) ----------
/// <summary>임무 카운터 +n 후 저장(화면의 성장 · 수확 · 등용 · 소탕 … 이 성공한 뒤 부른다).</summary>
public void CountMission(string key, int n = 1)
{
if (n <= 0) return;
MissionRules.Count(Db, Save, key, n, Now, Rng);
Commit();
}
/// <summary>임무 기간 맞춤(초기화 · 그날 첫 접속) — 바뀌었으면 저장.</summary>
public bool MissionRoll()
{
if (!MissionRules.Roll(Db, Save, Now, Rng)) return false;
Commit();
return true;
}
// ---------- 조회 ----------
public HeroDb.Hero Def(string id)
{
return Db.Heroes.Get(id);
}
public HeroRules.Stats StatsOf(string id)
{
return HeroRules.Compute(Db, Cfg, Def(id), Save.Level(id), Save); // 훈련 · 보물 포함(PD #1093 C)
}
/// <summary>보유 목록(장수 = 영웅 · 병사 = 병사 유닛) · 표 순서.</summary>
public List<HeroDb.Hero> Owned(bool soldiers)
{
var res = new List<HeroDb.Hero>();
foreach (var h in Db.Heroes.heroes)
if (h.isSoldier == soldiers && Save.Owns(h.id)) res.Add(h);
return res;
}
/// <summary>지금 할 수 있는 성장(레벨업 · 장착 · 승급 · 진화)이 있는가 — 목록 카드 알림 점.</summary>
public bool CanGrowAny(string id)
{
var h = Def(id);
var lv = Save.Level(id);
if (h == null || lv == null) return false;
if (HeroRules.CanLevelUp(Db, Save, lv) == null) return true;
var hs = Save.Hero(id);
if (hs == null) return false;
if (HeroRules.CanPromote(Db, h, hs) == null || AwakenRules.CanEvolve(Db, Save, h, hs) == null) return true;
for (int i = 0; i < hs.gear.Count; i++)
if (HeroRules.CanEquip(Db, Save, h, hs, i) == null) return true;
return false;
}
public bool InActivePreset(string id)
{
var p = Save.ActivePreset;
return p != null && p.slots.Contains(id);
}
// ---------- 성장 ----------
public virtual string LevelUp(string id)
{
var s = Save.Level(id);
var why = HeroRules.CanLevelUp(Db, Save, s);
if (why != null) return why;
HeroRules.LevelUp(Db, Save, s);
EventRules.Count(Save, EventRules.KHeroLevelUp, 1, Now);
Commit();
return null;
}
public virtual string Equip(string id, int slot)
{
var h = Def(id);
var s = Save.Hero(id);
var why = HeroRules.CanEquip(Db, Save, h, s, slot);
if (why != null) return why;
int open = AwakenRules.OpenSlots(Db, s);
HeroRules.Equip(Db, Save, h, s, slot);
// 6칸째 장비로 각성 칸이 열리면 그 칸 무료 1회 굴림(2차 §5-1-2) → 「각성 칸 열림」 창
LastSlotOpen = -1;
LastSlotFresh = false;
if (AwakenRules.OpenSlots(Db, s) > open)
{
LastSlotFresh = AwakenRules.Sync(Db, s, Rng).Count > 0;
LastSlotOpen = AwakenRules.OpenSlots(Db, s) - 1;
}
Commit();
return null;
}
/// <summary>마지막 장착으로 열린 각성 칸(0부터 · 없으면 −1) · Fresh = 새 줄 무료 굴림(아니면 보관 줄이 다시 보임).</summary>
public int LastSlotOpen = -1;
public bool LastSlotFresh;
public virtual string Promote(string id)
{
var h = Def(id);
var s = Save.Hero(id);
var why = HeroRules.CanPromote(Db, h, s);
if (why != null) return why;
HeroRules.Promote(Db, h, s);
EventRules.Count(Save, EventRules.KPromote, 1, Now);
Commit();
return null;
}
/// <summary>진화(2026-11-20 · 진영 비서 + 골드 · 지금 ★ 최대 레벨 도달 · 각성 칸과 상관없음).</summary>
public virtual string Evolve(string id)
{
var h = Def(id);
var s = Save.Hero(id);
var why = AwakenRules.CanEvolve(Db, Save, h, s);
if (why != null) return why;
AwakenRules.Evolve(Db, Save, h, s);
EventRules.Count(Save, EventRules.KEvolve, 1, Now); // 이벤트 미션 「진화」(PD 2026-11-19)
Commit();
return null;
}
// ---------- 각성 · 비서 교환(2026-11-20) ----------
/// <summary>열린 칸만큼 각성 줄을 채움(새 칸 무료 굴림) — 각성 창을 열 때 · 바뀌었으면 저장.</summary>
public void AwakenSync(string id)
{
var h = Def(id);
var s = Save.Hero(id);
if (h == null || s == null || h.isSoldier) return;
if (AwakenRules.Sync(Db, s, Rng).Count > 0) Commit();
}
public string AwakenRoll(string id)
{
var h = Def(id);
var s = Save.Hero(id);
var why = AwakenRules.CanRoll(Db, Save, h, s);
if (why != null) return why;
AwakenRules.Roll(Db, Save, h, s, Rng);
Commit();
return null;
}
public string AwakenLock(string id, int line)
{
var why = AwakenRules.ToggleLock(Db, Save.Hero(id), line);
if (why == null) Commit();
return why;
}
public string TomeExchange(AwakenDb.Item it, bool byPoint)
{
var why = AwakenRules.CanExchange(Db, Save, it, byPoint, Now);
if (why != null) return why;
AwakenRules.Exchange(Db, Save, it, byPoint, Now);
Commit();
return null;
}
/// <summary>스킬 i(0 = 액티브 · 1 = 패시브) 강화 → 성공(null)이면 저장 · 만능 조각이 필요하면 SkillRules.NeedUniv(창이 확인 팝업).</summary>
public virtual string SkillUp(string id, int i)
{
var why = EventRules.Counted(SkillRules.LevelUp(Db, Save, Def(id), Save.Hero(id), i, skillUnivOk), Save, EventRules.KSkillUp, 1, Now); // 이벤트 미션 「스킬 강화」(PD 2026-11-19)
if (why == null) Commit();
return why;
}
bool skillUnivOk;
// ---------- 외형(코스튬 · 2026-11-20) ----------
/// <summary>착용 저장(보유한 것만 · 미보유가 있으면 「unowned」) → 성공(null)이면 저장.</summary>
public string CostumeApply(string heroId, Dictionary<string, string> map)
{
var why = CostumeRules.Apply(Db.Costume, Save, Save.Hero(heroId), map);
if (why == null) Commit();
return why;
}
/// <summary>테스트 옵션 지급(얻는 곳 = PD 결정 대기) — all = 전부 · 아니면 다음 하나 · 반환 = 지급 수.</summary>
public int CostumeGrant(bool all)
{
if (Db.Costume == null) return 0;
int n = all ? CostumeRules.GrantAll(Db.Costume, Save) : (CostumeRules.GrantNext(Db.Costume, Save) != null ? 1 : 0);
if (n > 0) Commit();
return n;
}
/// <summary>강화 — allowUniv = 만능 조각 확인 팝업에서 「강화」(모자란 몫만 만능 조각).</summary>
public string SkillUp(string id, int i, bool allowUniv)
{
skillUnivOk = allowUniv;
try
{
return SkillUp(id, i);
}
finally
{
skillUnivOk = false;
}
}
// ---------- 편성 ----------
/// <summary>프리셋 idx 저장 + 출전 프리셋으로 지정(빈 칸 허용 · 최소 1).</summary>
public virtual string SavePreset(int idx, List<string> slots)
{
if (idx < 0 || idx >= Save.presets.Count) return "없는 프리셋";
int filled = 0;
foreach (var id in slots)
{
if (string.IsNullOrEmpty(id)) continue;
if (!Save.Owns(id)) return "미보유 " + id;
filled++;
}
if (filled == 0) return "최소 1명은 출전해야 합니다";
var p = Save.presets[idx];
p.slots.Clear();
for (int i = 0; i < FormationSlots; i++) p.slots.Add(i < slots.Count && slots[i] != null ? slots[i] : "");
Save.presetIdx = idx;
Commit();
return null;
}
/// <summary>출전 편성 = 출전 프리셋의 자리 순서(0~2 전열 · 3~4 후열 → playerSpawnPoints) · 스탯 = §3-2 공식.</summary>
public List<LineupEntry> BuildLineup()
{
var res = new List<LineupEntry>();
var p = Save.ActivePreset;
if (p == null) return res;
for (int i = 0; i < p.slots.Count && i < FormationSlots; i++)
{
var id = p.slots[i];
var h = Def(id);
if (h == null || !Save.Owns(id)) continue;
var st = StatsOf(id);
var entry = new LineupEntry
{
slot = i, id = h.id, name = h.nameKo, type = h.type, art = h.art,
hpMult = h.hpMult * st.GrowthOf("hp"), atkMult = h.atkMult * st.GrowthOf("atk"), defMult = h.defMult * st.GrowthOf("def"),
};
SkillRules.FillLineup(Db, Save, h, entry); // 스킬 id·레벨·★ 패시브 배율(PD #1093 B)
if (!h.isSoldier && Db.Awaken != null) entry.extraEffects = AwakenRules.Effects(Db, Save.Hero(h.id)); // 각성 능력치(공·체·방 % 는 위 배율에 이미 · 2026-11-20)
res.Add(entry);
}
return res;
}
// ---------- 군량 ----------
public int StaminaSecondsToNext()
{
return EconomyRules.SecondsToNext(Db, Save, Now);
}
/// <summary>스테이지 입장 비용 지불(부족 = false · 세이브 그대로).</summary>
public virtual bool TryPayEntry(BalanceConfig.StageDef s)
{
if (TestOptions.UnlockAllStages) return true; // 플레이 테스트 전용(전 스테이지 열기 = 군량 면제 · 2026-11-18)
int cost = EconomyRules.StageCost(Db, Save, s);
if (!EconomyRules.SpendStamina(Db, Save, cost, Now)) return false;
EventRules.Count(Save, EventRules.KStaminaUse, cost, Now);
Commit();
return true;
}
public virtual string BuyStamina()
{
var why = EconomyRules.BuyStaminaWithGem(Db, Save, Now);
if (why == null) Commit();
return why;
}
public virtual string AdStamina()
{
var why = EconomyRules.AdStamina(Db, Save, Now);
if (why == null) Commit();
return why;
}
// ---------- 전투 결과 · 소탕 ----------
/// <summary>전투 종료(승리·패배) → 보상 계산·반영·저장. 경험 = 출전 전원(Deployed).</summary>
public virtual StageReward OnBattleEnd(BattleManager bm, bool win)
{
var stage = bm.Stage;
int alive = 0;
foreach (var u in bm.AliveUnits(Faction.Player))
if (!u.Npc) alive++; // 구출 대상(학습 판)은 출전 인원이 아니다
bool allAlive = bm.Deployed.Count > 0 && alive >= bm.Deployed.Count;
var r = EconomyRules.Compute(Db, Save, stage, win, allAlive, bm.TurnNumber, false, Rng);
r.stamina = EconomyRules.StageCost(Db, Save, stage);
var ids = new List<string>();
foreach (var e in bm.Deployed) ids.Add(e.id);
EconomyRules.Apply(Save, r, ids);
ArenaRules.CountBattle(Save, bm); // 보물 조건 효과(전투 · 보스 처치)
if (win) EventRules.Count(Save, EventRules.KStageClear, 1, Now); // 이벤트 미션 「출정 스테이지 n회 클리어」
LastReward = r;
Commit();
return r;
}
/// <summary>소탕(별 3 · 군량만 · 전투 없음) = 반복 보상 · 경험 = 출전 프리셋. null = 군량 부족·불가.</summary>
public StageReward Sweep(BalanceConfig.StageDef s)
{
if (!EconomyRules.CanSweep(Save, s)) return null;
int cost = EconomyRules.StageCost(Db, Save, s);
if (!EconomyRules.SpendStamina(Db, Save, cost, Now)) return null;
var r = EconomyRules.Compute(Db, Save, s, true, true, 0, true, Rng);
r.stamina = cost;
var ids = new List<string>();
foreach (var e in BuildLineup()) ids.Add(e.id);
EconomyRules.Apply(Save, r, ids);
EventRules.Count(Save, EventRules.KStageClear, 1, Now); // 소탕도 클리어 · 군량 사용으로 셈
EventRules.Count(Save, EventRules.KStaminaUse, cost, Now);
LastReward = r;
Commit();
return r;
}
/// <summary>월드맵 진행(챕터별 앞에서부터 연속으로 깬 노드 수) = 세이브 스테이지 기록.</summary>
public void SyncWorldProgress()
{
WorldProgress.Reset();
for (int ch = 0; ch < Cfg.chapters.Length; ch++)
{
var list = Cfg.StagesOfChapter(Cfg.chapters[ch].no);
int n = 0;
while (n < list.Count)
{
var st = Cfg.stages[list[n]];
var ss = Save.Stage(st.chapter, st.stage, false);
if (ss == null || ss.clears == 0) break;
n++;
}
if (n > 0) WorldProgress.MarkCleared(ch, n - 1);
}
}
// ---------- 거래 ----------
public List<GachaPull> Draw(GachaConfig.Banner banner, int count)
{
var res = GachaRules.Draw(Db, Save, banner, count, Rng, Now);
EventRules.Count(Save, EventRules.KGacha, res.Count, Now);
if (res.Count > 0) Commit();
return res;
}
public virtual void EnsureShop()
{
var day = Save.shop.day;
int n = Save.shop.items.Count;
EconomyRules.EnsureShop(Db, Save, Now, Rng);
if (Save.shop.day != day || Save.shop.items.Count != n) Commit();
}
public virtual string BuyShop(int index)
{
var why = EconomyRules.BuyShop(Save, index);
if (why == null) Commit();
return why;
}
public string RefreshShop()
{
var why = EconomyRules.RefreshShop(Db, Save, Rng);
if (why == null) Commit();
return why;
}
// ---------- 내정 · 보물 · 연무장(PD #1093 C) ----------
/// <summary>규칙 호출 → 성공(null)이면 저장 · 반환 = 실패 사유.</summary>
public string Do(Func<string> action)
{
var why = action();
if (why == null) Commit();
return why;
}
// 내정 · 보물 · 교역 동작 — 화면은 이 함수들을 부른다(서버 모드에서는 같은 동작이 서버로도 간다 · Net/ServerSession)
public virtual string DevUpgrade(string id)
{
return Do(() => DevRules.Upgrade(Db, Save, id));
}
public virtual string DevReset()
{
return Do(() => DevRules.Reset(Db, Save));
}
public virtual string TrainLevel(UnitType t, int stat)
{
return Do(() => EventRules.Counted(TrainingRules.Level(Db, Save, t, stat), Save, EventRules.KTrain, 1, Now));
}
public virtual string TrainPromote(UnitType t)
{
return Do(() => TrainingRules.Promote(Db, Save, t));
}
/// <summary>내정 파견 — heroId 가 비면 그 자리를 비운다.</summary>
public virtual string Dispatch(string slot, string heroId)
{
return Do(() => string.IsNullOrEmpty(heroId) ? DispatchRules.Clear(Save, slot) : DispatchRules.Assign(Db, Save, slot, heroId));
}
public virtual string EnhanceTreasure(string id)
{
return Do(() => EventRules.Counted(TreasureRules.Enhance(Db, Save, id), Save, EventRules.KTreasure, 1, Now));
}
public virtual string BuyChest(string id, string currency)
{
return Do(() => TreasureRules.Buy(Db, Save, id, currency));
}
// 결과에 주사위가 들어가는 동작 — 서버 모드에서는 서버가 결과를 정하므로 응답을 기다린 뒤 done 을 부른다. 기본 세션은 바로 부른다.
public virtual void DrawAsync(GachaConfig.Banner banner, int count, Action<List<GachaPull>> done)
{
done(Draw(banner, count));
}
public virtual void HarvestAsync(bool ad, Action<PatrolYield, string> done)
{
string why;
var y = Harvest(ad, out why);
done(y, why);
}
public virtual void InstantHarvestAsync(Action<PatrolYield, string> done)
{
string why;
var y = InstantHarvest(out why);
done(y, why);
}
public virtual void OpenChestAsync(string id, Action<ChestResult> done)
{
done(OpenChest(id));
}
public virtual void RefreshShopAsync(Action<string> done)
{
done(RefreshShop());
}
public virtual void SweepAsync(BalanceConfig.StageDef s, Action<StageReward> done)
{
done(Sweep(s));
}
/// <summary>출전 프리셋 id(순찰 경험 대상).</summary>
public List<string> PresetIds()
{
var ids = new List<string>();
foreach (var e in BuildLineup()) ids.Add(e.id);
return ids;
}
public PatrolYield Harvest(bool ad, out string why)
{
var y = PatrolRules.Harvest(Db, Save, Now, PresetIds(), ad, Rng, out why);
if (y != null) Commit();
return y;
}
public PatrolYield InstantHarvest(out string why)
{
var y = PatrolRules.Instant(Db, Save, PresetIds(), Rng, out why);
if (y != null) Commit();
return y;
}
public ChestResult OpenChest(string id)
{
var r = TreasureRules.Open(Db, Save, id, Rng);
if (r != null) Commit();
return r;
}
// ---------- 연무장 · 우편 — 화면은 이 함수들을 부른다(서버 모드에서는 같은 동작이 서버로도 간다 · Net/ServerSession) ----------
/// <summary>연무장 화면을 열 때 — 일일 횟수 · 시즌 · 이번 주 보스를 지금 시각에 맞춘다.</summary>
public virtual void ArenaEnter()
{
Do(() =>
{
ArenaRules.RollDaily(Db, Save, Now);
ArenaRules.EnsureSeason(Db, Save, Now, Rng);
ArenaRules.RaidBoss(Db, Save, Now);
return null;
});
}
public virtual string TowerAd()
{
return Do(() => ArenaRules.TowerAd(Db, Save, Now));
}
public virtual string EnterTower()
{
return Do(() => ArenaRules.EnterTower(Db, Save, Now));
}
public virtual string BuyArenaShards(string heroId)
{
return Do(() => ArenaRules.BuyShards(Db, Save, heroId, Now));
}
/// <summary>연무장 전투 시작(문맥 기록) — 서버 모드는 여기서 서버 입장(세션 발급)을 보낸다.</summary>
public virtual void BeginMode(string kind, string id, int index)
{
Mode = new ModeCtx { kind = kind, id = id, index = index };
}
/// <summary>이벤트(출석 · 미션 · 룰렛)를 쓸 수 있는가 — 기기 세이브 모드만(PD 2026-11-19 결정 ① · 서버 모드는 서버가 계정 값을 덮어 기기 지급이 사라짐 · 서버 API = 따로).</summary>
public virtual bool EventAvailable
{
get { return true; }
}
/// <summary>우편 · 쿠폰을 쓸 수 있는가(서버 모드만).</summary>
public virtual bool MailAvailable
{
get { return false; }
}
const string MailNeedsServer = "우편은 서버에 연결했을 때만 쓸 수 있습니다";
/// <summary>우편함 목록 — done(목록, 실패 사유).</summary>
public virtual void MailListAsync(Action<List<MailItem>, string> done)
{
done(null, MailNeedsServer);
}
/// <summary>우편 보상 받기 — done(화면에 보여 줄 말, 성공 여부).</summary>
public virtual void MailClaimAsync(List<int> ids, Action<string, bool> done)
{
done(MailNeedsServer, false);
}
/// <summary>쿠폰 사용 — done(화면에 보여 줄 말, 성공 여부).</summary>
public virtual void CouponAsync(string code, Action<string, bool> done)
{
done(MailNeedsServer, false);
}
/// <summary>공지사항 목록(지금 기간 안의 것 · 최근 것부터) — done(목록, 실패 사유). 서버 모드만.</summary>
public virtual void NoticeListAsync(Action<List<NoticeItem>, string> done)
{
done(null, "공지사항은 서버에 연결했을 때만 볼 수 있습니다");
}
/// <summary>
/// 진행 단계 보고(게임 로그) — 서버가 알 수 없는 단계(튜토리얼 시작/전투/끝 …)를 그 단계에 처음 왔을 때 부른다.
/// 이름은 서버의 단계 표(data/server/funnel_steps.csv)에 있는 것만 남는다. 서버 모드만(기기 세이브 모드에서는 아무 일도 하지 않는다).
/// </summary>
public virtual void ReportStep(string step)
{
}
/// <summary>순위 표를 볼 수 있는가(서버 모드만 — 실제 유저 사이의 순위).</summary>
public virtual bool RankAvailable
{
get { return false; }
}
/// <summary>순위 표 — board = ArenaRules.Arena · Tower · Raid · done(순위 표, 실패 사유).</summary>
public virtual void RankBoardAsync(string board, Action<RankBoard, string> done)
{
done(null, "순위 표는 서버에 연결했을 때만 볼 수 있습니다");
}
/// <summary>연무장 전투 문맥(결과 계산용) — kind · 대상(층 · 던전 id · 샘플 번호 · 보스 id).</summary>
public class ModeCtx
{
public string kind;
public string id;
public int index;
}
public ModeCtx Mode;
/// <summary>연무장 전투 끝 → 보상·기록·저장(결과 패널 표시용). 서버 모드 = null 을 돌려주고 응답이 오면 ModeReady 로 알린다.</summary>
public virtual ModeResult OnModeEnd(BattleManager bm, bool win)
{
var m = Mode;
if (m == null) return null;
ModeResult r = null;
switch (m.kind)
{
case ArenaRules.Tower: r = ArenaRules.TowerResult(Db, Save, m.index, win, Rng); break;
case ArenaRules.Dungeon: r = ArenaRules.DungeonResult(Db, Save, m.id, win, Now, Rng); break;
case ArenaRules.Arena: r = ArenaRules.ArenaResult(Db, Save, m.index, win, Now); break;
case ArenaRules.Raid:
int dmg = 0;
bool killed = false;
foreach (var u in bm.Units)
{
if (u == null || u.Faction != Faction.Enemy || !u.IsBoss) continue;
dmg += u.MaxHp - u.Hp;
killed |= !u.IsAlive;
}
r = ArenaRules.RaidResult(Db, Save, m.id, dmg, killed, Now, Rng);
break;
case SupplyRules.Kind:
{
string grade;
float pct;
var lines = new List<string>();
SupplyVerdict(bm, win, out grade, out pct, lines);
var sr = SupplyRules.Result(Db, Save, m.id, m.index, grade, pct, Now, Rng);
r = SupplyRules.ToMode(Db, Save, sr, lines, Now);
break;
}
case LeagueRules.Kind:
{
var lines = new List<string>();
r = LeagueRules.Result(Db, Save, m.index, win, lines, Now);
if (win) EventRules.Count(Save, EventRules.KArenaWin, 1, Now);
break;
}
case ScenarioModeRules.Kind:
{
var sr = bm.Mode != null ? bm.Mode.rules as ScenarioRules : null;
var pr = bm.Mode != null ? bm.Mode.rules as PrologueRules : null;
var lines = new List<string>();
if (sr != null) sr.Summarize(lines);
if (pr != null) r = ScenarioModeRules.ActResult(Db, Save, m.id, pr.Act, pr.Acts, win, lines, Now, Rng); // 서장 = 막 하나씩(마지막 막 = 편 결과)
else r = ScenarioModeRules.Result(Db, Save, m.id, sr != null && sr.Hard, win, sr != null ? sr.Challenges(win) : null, lines, Now, Rng);
break;
}
case RaidRules.Kind:
{
var rr = bm.Mode != null ? bm.Mode.rules as RaidBattleRules : null;
var lines = new List<string>();
if (rr != null) rr.Summarize(lines);
r = RaidRules.Result(Db, Save, rr != null ? rr.Slot : RaidData.Main, rr != null && rr.Practice, m.id, rr != null ? rr.Damage : 0, lines, Now, Rng);
break;
}
}
ArenaRules.CountBattle(Save, bm);
LastMode = r;
Mode = null;
Commit();
return r;
}
// ---------- 보급전(컨텐츠 모드 ① · 2026-11-17) ----------
/// <summary>전투 규칙의 판정(등급 · 비율) + 결과 줄(과제 · 부순 수 …).</summary>
protected static void SupplyVerdict(BattleManager bm, bool win, out string grade, out float pct, List<string> lines)
{
grade = "";
pct = 0f;
var rules = bm != null && bm.Mode != null ? bm.Mode.rules as SupplyRulesBase : null;
if (rules == null) return;
rules.Verdict(win, out grade, out pct);
rules.Summarize(lines);
}
/// <summary>보급전 화면 상태 새로 받기(서버 모드 = GET /tks/modes/supply) — 끝나면 done.</summary>
public virtual void SupplyRefresh(Action done)
{
Do(() =>
{
ArenaRules.RollDaily(Db, Save, Now);
return null;
});
if (done != null) done();
}
/// <summary>보급전 입장(횟수 1 · 전투는 화면이 시작) — null = 가능.</summary>
public virtual string SupplyEnter(string id, int tier)
{
return Do(() =>
{
var why = SupplyRules.Enter(Db, Save, id, tier, Now);
if (why == null) EventRules.Count(Save, EventRules.KSupplyTry, id, 1, Now); // 이벤트 미션 「<던전> n회 도전」
return why;
});
}
public virtual string SupplyAd(string id)
{
return Do(() => SupplyRules.Ad(Db, Save, id, Now));
}
// ---------- 등급 투기장(컨텐츠 모드 ④ · 2026-11-18) ----------
public virtual void LeagueRefreshView(Action done)
{
if (done != null) done();
}
public virtual string LeagueEnter(int k)
{
return Do(() => EventRules.Counted(LeagueRules.Enter(Db, Save, k, Now), Save, EventRules.KArenaTry, 1, Now));
}
/// <summary>상대 새로고침 — done(실패 사유 · null = 성공).</summary>
public virtual void LeagueRefresh(Action<string> done)
{
done(Do(() => LeagueRules.Refresh(Db, Save, Now)));
}
/// <summary>입장 구매(보옥) — done(실패 사유 · null = 성공).</summary>
public virtual void LeagueBuy(Action<string> done)
{
done(Do(() => LeagueRules.BuyEntry(Db, Save, Now)));
}
// ---------- 연의 전기(컨텐츠 모드 ② · 2026-11-18) ----------
/// <summary>화면 상태 새로 받기(서버 모드 = GET /tks/modes/scenario).</summary>
public virtual void ScenarioRefresh(Action done)
{
if (done != null) done();
}
/// <summary>입장(군량) — null = 가능.</summary>
public virtual string ScenarioEnter(string id, bool hard)
{
return Do(() => ScenarioModeRules.Enter(Db, Save, id, hard, Now));
}
// ---------- 맹장 토벌전(컨텐츠 모드 ③ · 2026-11-18) ----------
/// <summary>화면 상태 새로 받기(서버 모드 = GET /tks/modes/raid).</summary>
public virtual void RaidRefresh(Action done)
{
Do(() =>
{
RaidRules.BossOf(Save, RaidData.Main, Now);
return null;
});
if (done != null) done();
}
/// <summary>입장(기록 도전 = 자리 횟수 1 · 연습 = 없음) — null = 가능.</summary>
public virtual string RaidEnter(string slot, bool practice)
{
return Do(() => practice ? RaidRules.Enter(Save, slot, practice, Now) : EventRules.Counted(RaidRules.Enter(Save, slot, practice, Now), Save, EventRules.KRaidTry, 1, Now));
}
/// <summary>훈장 상점 구매 — done(실패 사유 · null = 성공).</summary>
public virtual void RaidBuy(string item, string pick, Action<string> done)
{
done(Do(() => RaidRules.Buy(Db, Save, item, pick, Now, Rng)));
}
/// <summary>소탕 — done(결과 · 실패 사유).</summary>
public virtual void SupplySweep(string id, int tier, Action<ModeResult, string> done)
{
SupplyResult r = null;
var why = Do(() =>
{
var w = SupplyRules.Sweep(Db, Save, id, tier, Now, Rng, out r);
if (w == null) EventRules.Count(Save, EventRules.KSupplyTry, id, 1, Now); // 소탕도 도전으로 셈
return w;
});
done(why == null ? SupplyRules.ToMode(Db, Save, r, null, Now) : null, why);
}
}
}