using System; using System.Collections.Generic; using UnityEngine; namespace TKS.OutGame { /// 보급전 세이브(기기 세이브 모드 · 서버 모드는 서버 응답 · GET /tks/modes/supply 로 덮는다). [Serializable] public class SupplyBest { public string id = ""; public int tier; [Tooltip("등급 낱말(S · A …) 또는 별 수(병법 훈련)")] public string grade = ""; } [Serializable] public class SupplyState { public List best = new List(); [Tooltip("그날(서버 날짜 · 기기 = 현지 날짜) 끝낸 던전 · 그날 보너스를 받았는가")] public string doneDay = ""; public List doneIds = new List(); public bool doneBonus; [Tooltip("주간 도장(주 키 · 「일일 보급 완료」 날 · 받음)")] public string stampWeek = ""; public List stampDays = new List(); public bool stampClaimed; [Tooltip("서버 모드 = 서버가 알려 준 단계 해금(그 밖 = 기기가 스테이지 기록으로 판정)")] public List serverOpenTiers = new List(); public bool serverView; public string Best(string id, int tier) { foreach (var b in best) if (b.id == id && b.tier == tier) return b.grade; return ""; } public void SetBest(string id, int tier, string grade) { foreach (var b in best) if (b.id == id && b.tier == tier) { b.grade = grade; return; } best.Add(new SupplyBest { id = id, tier = tier, grade = grade }); } } /// 보급전 한 판(또는 소탕)의 결과 — 결과 화면 · 서버 응답 공용. public class SupplyResult { public string id; public int tier; public string grade = ""; public float pct; public bool sweep; public bool refunded; public bool dailyBonus; public bool stampBonus; public int gold, exp, iron, blueprint, skillBook; public List gearIds = new List(); public string shardHero; public int shards; } /// /// 보급전 규칙(기기 세이브 모드 · 서버 규칙 `ThreeKingdomsServer/src/functions/tks/domain/supply.rules.ts` 와 같은 판정 · 보상) — 값은 전부 표(SupplyData · content_modes_config supply.*). /// 입장 횟수 = 입장할 때 1 · 실패하면 돌려줌(supply.fail_refund) · 하루 무료 entries_per_day + 광고 ad_entries_per_day · 일일 키 = 서버와 같은 「supply:<던전>」 「supplyAd:<던전>」. /// public static class SupplyRules { public const string Kind = "supply"; public const string DailyPrefix = "supply:"; public const string AdPrefix = "supplyAd:"; // ---------- 날짜 · 해금 ---------- public static string Weekday(DateTime nowUtc) { return DungeonDb.Weekdays[(int)nowUtc.ToLocalTime().DayOfWeek]; } public static bool OpenToday(SupplyData.Dungeon d, DateTime nowUtc) { return d != null && d.weekdays.Contains(Weekday(nowUtc)); } static bool Cleared(SaveData d, string key) { int ch, st; if (!ArenaRules.ParseStageKey(key, out ch, out st)) return true; var s = d.Stage(ch, st, false); return s != null && s.clears > 0; } /// 보급전 해금(supply.unlock_stage 클리어). public static bool Unlocked(SaveData d) { if (d.supply.serverView) return true; // 서버 모드 = 서버가 판정(잠겼으면 입장 응답이 거절) return Cleared(d, ContentTables.Str(SupplyData.Mode, "unlock_stage")); } public static bool TierOpen(SaveData d, SupplyData.Tier t) { if (t == null) return false; if (d.supply.serverView) return d.supply.serverOpenTiers.Contains(t.tier); return Cleared(d, t.unlockStage); } // ---------- 횟수 ---------- static void Roll(OutGameData db, SaveData d, DateTime nowUtc) { ArenaRules.RollDaily(db, d, nowUtc); } public static int Used(OutGameData db, SaveData d, string id, DateTime nowUtc) { Roll(db, d, nowUtc); return d.dailyC.Dungeon(DailyPrefix + id); } public static int AdGot(OutGameData db, SaveData d, string id, DateTime nowUtc) { Roll(db, d, nowUtc); return d.dailyC.Dungeon(AdPrefix + id); } public static int Limit(OutGameData db, SaveData d, string id, DateTime nowUtc) { return ContentTables.Int(SupplyData.Mode, "entries_per_day") + AdGot(db, d, id, nowUtc); } public static int Left(OutGameData db, SaveData d, string id, DateTime nowUtc) { return Mathf.Max(0, Limit(db, d, id, nowUtc) - Used(db, d, id, nowUtc)); } /// 입장(또는 소탕) 가능 여부 — null = 가능 · 글 = 까닭. public static string Can(OutGameData db, SaveData d, string id, int tier, DateTime nowUtc) { ContentTables.Reload(); var dg = SupplyData.GetDungeon(id); var t = SupplyData.GetTier(tier); if (dg == null) return "없는 던전"; if (t == null) return "없는 단계"; if (!Unlocked(d)) return ContentTables.Str(SupplyData.Mode, "unlock_stage") + " 클리어 뒤 열림"; if (!OpenToday(dg, nowUtc)) return "오늘은 닫힘"; if (!TierOpen(d, t)) return t.unlockStage + " 클리어 뒤 열림"; if (Left(db, d, id, nowUtc) <= 0) return "오늘 입장 " + Limit(db, d, id, nowUtc) + "회 완료"; return null; } /// 입장 = 횟수 1 사용(실패하면 Result 가 돌려준다). public static string Enter(OutGameData db, SaveData d, string id, int tier, DateTime nowUtc) { var why = Can(db, d, id, tier, nowUtc); if (why != null) return why; d.dailyC.AddDungeon(DailyPrefix + id); return null; } /// 광고 추가 입장(던전마다 하루 supply.ad_entries_per_day). public static string Ad(OutGameData db, SaveData d, string id, DateTime nowUtc) { var dg = SupplyData.GetDungeon(id); if (dg == null) return "없는 던전"; if (!OpenToday(dg, nowUtc)) return "오늘은 닫힘"; if (AdGot(db, d, id, nowUtc) >= ContentTables.Int(SupplyData.Mode, "ad_entries_per_day")) return "오늘 광고 입장을 모두 받았습니다"; d.dailyC.AddDungeon(AdPrefix + id); return null; } // ---------- 결과 · 소탕 ---------- /// 전투 끝(기기 세이브 모드) — 판정 · 보상 · 최고 판정 · 그날 완료 · 주간 도장 · 실패 시 횟수 반환. public static SupplyResult Result(OutGameData db, SaveData d, string id, int tier, string grade, float pct, DateTime nowUtc, System.Random rng) { var dg = SupplyData.GetDungeon(id); var t = SupplyData.GetTier(tier); var r = new SupplyResult { id = id, tier = tier, grade = grade, pct = pct }; if (dg == null || t == null) return r; if (string.IsNullOrEmpty(grade)) { if (ContentTables.Int(SupplyData.Mode, "fail_refund") > 0 && d.dailyC.Dungeon(DailyPrefix + id) > 0) { Counts.Add(d.dailyC.dungeons, DailyPrefix + id, -1); r.refunded = true; } return r; } Pay(db, d, dg, t, r, nowUtc, rng); return r; } /// 소탕 — 그 단계 최고 판정이 소탕 등급(별) 이상 · 입장 횟수 1 · 전투 없이 그 판정의 보상. public static string Sweep(OutGameData db, SaveData d, string id, int tier, DateTime nowUtc, System.Random rng, out SupplyResult r) { r = null; var dg = SupplyData.GetDungeon(id); var sg = SupplyData.SweepGrade(dg, d.supply.Best(id, tier)); if (sg == null) return "소탕 = " + SweepNeed(dg) + " 을 받은 단계만"; var why = Enter(db, d, id, tier, nowUtc); if (why != null) return why; r = new SupplyResult { id = id, tier = tier, grade = sg.grade, pct = sg.pct, sweep = true }; Pay(db, d, dg, SupplyData.GetTier(tier), r, nowUtc, rng); return null; } public static string SweepNeed(SupplyData.Dungeon dg) { if (dg == null) return ""; return dg.gradeBy == "star" ? "★" + ContentTables.Int(SupplyData.Mode, "tactics_sweep_star") : ContentTables.Str(SupplyData.Mode, "sweep_grade") + " 등급"; } static void Pay(OutGameData db, SaveData d, SupplyData.Dungeon dg, SupplyData.Tier t, SupplyResult r, DateTime nowUtc, System.Random rng) { float ratio = r.pct / 100f; Func scaled = (n, mod) => Mathf.RoundToInt(n * ratio * mod); if (dg.rewardKinds.Contains("gold")) { r.gold = scaled(t.gold, DevRules.Mult(db, d, DevRules.GoldGain)); d.gold += r.gold; } if (dg.rewardKinds.Contains("exp")) { r.exp = scaled(t.exp, DevRules.Mult(db, d, DevRules.ExpGain)); // 출전한 유닛 1기마다(서버와 같음) var p = d.ActivePreset; if (p != null) foreach (var uid in p.slots) { var s = string.IsNullOrEmpty(uid) ? null : d.Level(uid); if (s != null) HeroRules.GrantExp(s, r.exp); } } if (dg.rewardKinds.Contains("iron")) { r.iron = scaled(t.iron, DevRules.Mult(db, d, DevRules.IronGain)); d.inv.iron += r.iron; } if (dg.rewardKinds.Contains("blueprint")) { r.blueprint = scaled(t.blueprint, 1f); d.inv.blueprint += r.blueprint; } if (dg.rewardKinds.Contains("skill_book")) { r.skillBook = scaled(t.skillBook, 1f); d.inv.books.skill += r.skillBook; } if (dg.rewardKinds.Contains("gear")) { float exact = t.gearCount * ratio * DevRules.Mult(db, d, DevRules.DungeonGear); int whole = Mathf.FloorToInt(exact + 1e-4f); int count = whole + (rng.NextDouble() < exact - whole ? 1 : 0); var pool = new List(); foreach (var it in db.Gear.items) if (it.grade == t.gearGrade) pool.Add(it); for (int k = 0; k < count && pool.Count > 0; k++) { var g = pool[rng.Next(pool.Count)]; d.inv.AddGear(g.id, 1); r.gearIds.Add(g.id); } } if (dg.rewardKinds.Contains("shard") && d.heroes.Count > 0) { int n = scaled(t.shard, 1f); if (n > 0) { var h = d.heroes[rng.Next(d.heroes.Count)]; h.shards += n; r.shardHero = h.id; r.shards = n; } } if (SupplyData.Rank(dg, r.grade) > SupplyData.Rank(dg, d.supply.Best(dg.id, t.tier))) d.supply.SetBest(dg.id, t.tier, r.grade); MarkDone(db, d, dg.id, nowUtc, rng, r); } /// 그날 열린 곳을 모두 끝냈으면 보너스(supply.daily_all_bonus · 한 번) · 그날을 주간 도장에 찍고 weekly_stamp_need 날이면 주간 보너스(한 번). static void MarkDone(OutGameData db, SaveData d, string id, DateTime nowUtc, System.Random rng, SupplyResult r) { var s = d.supply; string day = EconomyRules.DayKey(nowUtc), week = ArenaRules.WeekKey(nowUtc); if (s.doneDay != day) { s.doneDay = day; s.doneIds.Clear(); s.doneBonus = false; } if (!s.doneIds.Contains(id)) s.doneIds.Add(id); if (s.stampWeek != week) { s.stampWeek = week; s.stampDays.Clear(); s.stampClaimed = false; } var open = new List(); foreach (var dg in SupplyData.AllDungeons()) if (OpenToday(dg, nowUtc)) open.Add(dg.id); bool complete = open.Count > 0; foreach (var o in open) if (!s.doneIds.Contains(o)) complete = false; if (!complete || s.doneBonus) return; s.doneBonus = true; r.dailyBonus = true; GiveParts(db, d, ContentTables.Str(SupplyData.Mode, "daily_all_bonus"), rng); if (!s.stampDays.Contains(day)) s.stampDays.Add(day); int need = ContentTables.Int(SupplyData.Mode, "weekly_stamp_need"); if (need > 0 && !s.stampClaimed && s.stampDays.Count >= need) { s.stampClaimed = true; r.stampBonus = true; GiveParts(db, d, ContentTables.Str(SupplyData.Mode, "weekly_stamp_bonus"), rng); } } /// 「silver_chest:1;gem:20」 꾸러미 지급(상자 = 「<상자>_chest」 · 재화 = gem · gold). static void GiveParts(OutGameData db, SaveData d, string parts, System.Random rng) { foreach (var kv in ContentTables.ParseMap(parts)) { int n = Mathf.RoundToInt(kv.Value); if (kv.Key.EndsWith("_chest")) { string chest = kv.Key.Substring(0, kv.Key.Length - "_chest".Length); for (int i = 0; i < n; i++) TreasureRules.AddChest(db, d, chest, rng); } else if (kv.Key == "gem") d.gem += n; else if (kv.Key == "gold") d.gold += n; else Debug.LogWarning("[TKS] 보급전 보너스 낱말 모름: " + kv.Key); } } // ---------- 세이브 이전 ---------- /// /// 옛 일일 던전 id → 새 id(existing_tables_patch.csv 의 dungeons 줄 「id <새 id> · …」 · forge → bandit · shrine → tactics) — 오늘 입장 횟수 기록을 새 id 의 보급전 키로 옮긴다. /// public static void Migrate(SaveData d) { if (d == null || d.dailyC == null) return; if (d.supply == null) d.supply = new SupplyState(); foreach (var c in d.dailyC.dungeons) { if (c.id.StartsWith(DailyPrefix) || c.id.StartsWith(AdPrefix)) continue; c.id = DailyPrefix + NewId(c.id); } } static string NewId(string old) { foreach (var r in ContentTables.Rows("existing_tables_patch")) { if (r.S("s_table") != "dungeons" || r.S("s_key") != old) continue; var s = r.S("s_new"); if (s.StartsWith("id ")) { var rest = s.Substring(3).Trim(); int sp = rest.IndexOfAny(new[] { ' ', '·' }); return sp > 0 ? rest.Substring(0, sp).Trim() : rest; } } return old; } // ---------- 결과 줄 ---------- public static ModeResult ToMode(OutGameData db, SaveData d, SupplyResult r, List battleLines, DateTime nowUtc) { var dg = SupplyData.GetDungeon(r.id); var m = new ModeResult { kind = Kind, win = !string.IsNullOrEmpty(r.grade), title = (dg != null ? dg.nameKo : r.id) + " " + r.tier + "단계" + (r.sweep ? " 소탕" : "") }; if (battleLines != null) m.lines.AddRange(battleLines); if (!m.win) { m.lines.Add("판정 없음 — " + (r.refunded ? "입장 횟수를 돌려받았습니다" : "보상 없음")); return m; } m.lines.Add("판정 " + (dg != null && dg.gradeBy == "star" ? "★" + r.grade : r.grade) + " · 보상 " + Mathf.RoundToInt(r.pct) + "%"); if (r.gold > 0) m.lines.Add("골드 +" + r.gold.ToString("N0")); if (r.exp > 0) m.lines.Add("경험 +" + r.exp.ToString("N0") + " (출전 유닛마다)"); if (r.iron > 0) m.lines.Add("운철 +" + r.iron); if (r.blueprint > 0) m.lines.Add("도면 +" + r.blueprint); if (r.skillBook > 0) m.lines.Add("스킬서 +" + r.skillBook); foreach (var gid in r.gearIds) { var g = db.Gear.Get(gid); m.lines.Add("장비 " + (g != null ? g.nameKo + " (" + UiKit.GradeKo(g.grade) + ")" : gid)); } if (r.shards > 0) { var h = db.Heroes.Get(r.shardHero); m.lines.Add((h != null ? h.nameKo : r.shardHero) + " 조각 +" + r.shards); } if (r.dailyBonus) m.lines.Add("오늘 열린 곳 모두 완료 — 보너스 " + ContentTables.Str(SupplyData.Mode, "daily_all_bonus")); if (r.stampBonus) m.lines.Add("주간 도장 완성 — 보너스 " + ContentTables.Str(SupplyData.Mode, "weekly_stamp_bonus")); m.lines.Add("오늘 남은 입장 " + Left(db, d, r.id, nowUtc) + " / " + Limit(db, d, r.id, nowUtc)); return m; } } }