ThreeKingdomsSlingshot/Assets/Scripts/OutGame/OutGameSession.cs

595 lines
22 KiB
C#

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;
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);
s.lastGold = save.gold;
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);
lastGold = Save.gold;
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();
}
// ---------- 조회 ----------
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 || HeroRules.CanEvolve(Db, 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);
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;
HeroRules.Equip(Db, Save, h, s, slot);
Commit();
return null;
}
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);
Commit();
return null;
}
public virtual string Evolve(string id)
{
var h = Def(id);
var s = Save.Hero(id);
var why = HeroRules.CanEvolve(Db, h, s);
if (why != null) return why;
HeroRules.Evolve(Db, h, s);
Commit();
return null;
}
/// <summary>스킬 i(0 = 액티브 · 1 = 패시브) 레벨업 → 성공(null)이면 저장.</summary>
public virtual string SkillUp(string id, int i)
{
var why = SkillRules.LevelUp(Db, Save, Def(id), Save.Hero(id), i);
if (why == null) Commit();
return why;
}
// ---------- 편성 ----------
/// <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)
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 (!EconomyRules.SpendStamina(Db, Save, EconomyRules.StageCost(Db, Save, s), Now)) return false;
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); // 보물 조건 효과(전투 · 보스 처치)
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);
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);
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(() => TrainingRules.Level(Db, Save, t, stat));
}
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(() => TreasureRules.Enhance(Db, Save, id));
}
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>우편 · 쿠폰을 쓸 수 있는가(서버 모드만).</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;
}
ArenaRules.CountBattle(Save, bm);
LastMode = r;
Mode = null;
Commit();
return r;
}
}
}