using System; using System.Collections.Generic; using System.Globalization; using UnityEngine; namespace TKS.OutGame { /// 스테이지 1회 결과(보상 · 별 · 조건) — 결과 화면·소탕 팝업 표시용. public class StageReward { public bool win; public bool sweep; public bool first; public bool boss; public int chapter; public int stage; public int gold; public int exp; public int gem; /// 전리품 상자의 장비(상자 1개 = 장비 1개 · 2026-11-23) — 앞에서 fixedChests 개 = 보스 첫 클리어 확정 상자. public List gearIds = new List(); public int fixedChests; /// 첫 장비(옛 한 개짜리 호출부 · 서버 응답 reward.gearId 용). public string gearId { get { return gearIds.Count > 0 ? gearIds[0] : null; } set { gearIds.Clear(); if (!string.IsNullOrEmpty(value)) gearIds.Add(value); } } /// 지역 특화(stage_drop s_region = gold · exp · gear) · 이번 판에 곱해진 지역 배율(결과 창 표시용). public string region = ""; public float goldMult = 1f; public float expMult = 1f; /// 보물 상자(stage_chest · stage_chest_pct · PD #1093 C) — 상자 등급 개발 반영 뒤 id. public string chest; public int stamina; public int stars; /// 별 조건 ① 클리어 ② 아군 전원 생존 ③ star_turns 턴 이내. public bool[] conds = new bool[3]; public int starTurns; public int turns; public int bestStars; public List expTo = new List(); } /// 출전할 때 미리 굴린 전리품(2026-11-23 스테이지 보상 드랍) — 상자 1개 = 장비 1개 · 앞의 fixedChests 개 = 보스 첫 클리어 확정 상자. public class StageLoot { public int chapter; public int stage; public bool sweep; public List gearIds = new List(); public int fixedChests; } /// 군량(§2) · 일일 횟수 · 스테이지 보상(§6) · 소탕 · 골드 장비 상점(S15). 수치 = economy.csv · stage_rewards.csv · gear_items.csv. public static class EconomyRules { // ---------- 일일 ---------- public static string DayKey(DateTime nowUtc) { return nowUtc.ToLocalTime().ToString("yyyyMMdd", CultureInfo.InvariantCulture); } /// 날짜가 바뀌었으면 광고·보옥 구매 횟수를 초기화. public static void RollDaily(SaveData d, DateTime nowUtc) { var day = DayKey(nowUtc); if (d.adsUsed.day == day) return; d.adsUsed = new AdsUsed { day = day }; } /// 다음 날 0시(현지)까지 남은 시간. public static TimeSpan UntilNextDay(DateTime nowUtc) { var local = nowUtc.ToLocalTime(); return local.Date.AddDays(1) - local; } // ---------- 군량 ---------- /// 군량 최대 = stamina_max + 농업 「군량 상한」(PD #1093 C) · stamina_max_limit 를 넘지 않는다. public static int StaminaMax(OutGameData db, SaveData d) { int max = db.Economy.StaminaMax + Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.FoodCap)); int limit = db.Economy.StaminaMaxLimit; // 내정 등으로 늘려도 넘지 못하는 상한(PD 2026-11-24 「기본 50 · 최대 200」) return limit > 0 ? Mathf.Min(max, limit) : max; } /// 군량 1 회복 초 = stamina_regen_sec − 농업 「군량 회복」(최소 1). public static int RegenSec(OutGameData db, SaveData d) { return Mathf.Max(1, db.Economy.StaminaRegenSec - Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.FoodRegen))); } /// 회복 계산(오프라인 포함): 최대 미만이면 stamina_regen_sec 마다 1 · 최대 이상(구매·광고로 넘침)이면 멈추고 기준 시각만 당긴다. public static void TickStamina(OutGameData db, SaveData d, DateTime nowUtc) { int max = StaminaMax(db, d); int regen = RegenSec(db, d); var at = SaveStore.ParseIso(d.staminaAt, nowUtc); if (at > nowUtc) at = nowUtc; // 기기 시각을 되돌린 경우 if (d.stamina >= max) { d.staminaAt = SaveStore.Iso(nowUtc); return; } long elapsed = (long)(nowUtc - at).TotalSeconds; long gained = elapsed / Mathf.Max(1, regen); if (gained <= 0) { d.staminaAt = SaveStore.Iso(at); return; } long next = d.stamina + gained; if (next >= max) { d.stamina = max; d.staminaAt = SaveStore.Iso(nowUtc); } else { d.stamina = (int)next; d.staminaAt = SaveStore.Iso(at.AddSeconds(gained * regen)); } } /// 다음 1 회복까지 초(최대 이상 = 0). public static int SecondsToNext(OutGameData db, SaveData d, DateTime nowUtc) { if (d.stamina >= StaminaMax(db, d)) return 0; int regen = RegenSec(db, d); var at = SaveStore.ParseIso(d.staminaAt, nowUtc); int left = regen - (int)(nowUtc - at).TotalSeconds; return Mathf.Clamp(left, 0, regen); } public static int StageCost(OutGameData db, BalanceConfig.StageDef s) { return s.kind == StageKind.Boss ? db.Economy.BossCost : db.Economy.StageCost; } /// 입장 군량 = 표 비용 − 농업 「군량 비용 할인」(누적 값의 정수 부분 · 최소 1 · PD 확인 대상). public static int StageCost(OutGameData db, SaveData d, BalanceConfig.StageDef s) { return Mathf.Max(1, StageCost(db, s) - Mathf.FloorToInt(DevRules.Mod(db, d, DevRules.FoodCost) + 1e-4f)); } public static bool SpendStamina(OutGameData db, SaveData d, int n, DateTime nowUtc) { TickStamina(db, d, nowUtc); if (d.stamina < n) return false; int max = StaminaMax(db, d); bool wasFull = d.stamina >= max; d.stamina -= n; if (wasFull && d.stamina < max) d.staminaAt = SaveStore.Iso(nowUtc); // 가득 찬 상태에서 쓰면 그때부터 회복 return true; } public static void AddStamina(OutGameData db, SaveData d, int n, DateTime nowUtc) { TickStamina(db, d, nowUtc); d.stamina += n; if (d.stamina >= StaminaMax(db, d)) d.staminaAt = SaveStore.Iso(nowUtc); } /// 보옥 gem_stamina_cost → 군량 gem_stamina_amount (gem_stamina_daily 회/일). null = 성공. public static string BuyStaminaWithGem(OutGameData db, SaveData d, DateTime nowUtc) { var e = db.Economy; RollDaily(d, nowUtc); if (d.adsUsed.gemStamina >= e.GemStaminaDaily) return "오늘 구매 " + e.GemStaminaDaily + "회를 모두 썼습니다"; if (d.gem < e.GemStaminaCost) return "보옥 부족 " + d.gem + " / " + e.GemStaminaCost; d.gem -= e.GemStaminaCost; d.adsUsed.gemStamina++; AddStamina(db, d, e.GemStaminaAmount, nowUtc); return null; } /// 광고 보상 군량 +ad_stamina (ad_stamina_daily 회/일) — 광고 SDK 미연동 스텁 = 즉시 지급. public static string AdStamina(OutGameData db, SaveData d, DateTime nowUtc) { var e = db.Economy; RollDaily(d, nowUtc); if (d.adsUsed.stamina >= e.AdStaminaDaily) return "오늘 광고 " + e.AdStaminaDaily + "회를 모두 봤습니다"; d.adsUsed.stamina++; AddStamina(db, d, e.AdStamina + Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.AdFood)), nowUtc); return null; } // ---------- 스테이지 보상(§6) ---------- /// /// 골드 = (gold_base + stage × gold_per_stage) × 첫 클리어 first_clear_gold_mult · 반복 repeat_reward_mult × 지역 배율(stage_drop f_gold_mult) · /// 경험 = 출전 전원 exp_base(반복 × repeat_reward_mult) × 지역 배율(f_exp_mult) · 보옥 = 첫 클리어 gem_first + 보스 gem_boss · /// 장비 = 전리품 상자(loot = 출전 때 미리 굴린 것 · 없거나 다른 스테이지 것이면 여기서 굴림 = 소탕) · /// 별 = 클리어 · 전원 생존 · star_turns 턴 이내. 소탕 = 반복 보상(별 조건 없음). /// public static StageReward Compute(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool win, bool allAlive, int turns, bool sweep, System.Random rng, StageLoot loot = null) { var e = db.Economy; var row = db.Rewards.For(s.chapter); var st = d.Stage(s.chapter, s.stage, false); var sd = StageDropOf(db, s); var r = new StageReward { win = win, sweep = sweep, chapter = s.chapter, stage = s.stage, boss = s.kind == StageKind.Boss, first = !sweep && (st == null || st.clears == 0), turns = turns, starTurns = row != null ? row.starTurns : 0, bestStars = st != null ? st.stars : 0, region = sd != null ? sd.region : "", goldMult = sd != null ? sd.goldMult : 1f, expMult = sd != null ? sd.expMult : 1f, }; if (!win || row == null) return r; // 개발 효과(PD #1093 C) = 골드 획득 · 경험 획득 · 첫 클리어 보옥 · 보옥 보너스 · 장비 드랍(%p) — 개발 0 이면 A 단계 값 그대로 StageGoldExp(db, d, s, r.first, out r.gold, out r.exp); r.gem = r.first ? Mathf.RoundToInt((row.gemFirst + (r.boss ? row.gemBoss : 0)) * DevRules.Mult(db, d, DevRules.FirstClearGem) * DevRules.Mult(db, d, DevRules.GemBonus)) : 0; if (loot == null || loot.chapter != s.chapter || loot.stage != s.stage || loot.sweep != sweep) loot = RollLoot(db, d, s, sweep, rng); r.gearIds.AddRange(loot.gearIds); r.fixedChests = loot.fixedChests; if (db.Chests != null && rng.NextDouble() < e.StageChestPct) r.chest = TreasureRules.RollTier(db, d, e.StageChest, rng); if (!sweep) { r.conds[0] = true; r.conds[1] = allAlive; r.conds[2] = turns <= row.starTurns; foreach (var c in r.conds) if (c) r.stars++; } return r; } /// 지역 특화 이름(stage_drop s_region) — 골드 지역 · 경험치 지역 · 장비 지역 · 없으면 빈 글자. public static string RegionKo(string region) { return region == GearDb.RegionGold ? "골드 지역" : region == GearDb.RegionExp ? "경험치 지역" : region == GearDb.RegionGear ? "장비 지역" : ""; } /// 지역 특화 한 줄(스테이지 정보 창 · 결과 창) — 「골드 지역 · 골드 ×1.5」 처럼 그 스테이지 배율을 붙인다(배율 1 = 이름만). public static string RegionLine(OutGameData db, SaveData d, BalanceConfig.StageDef s) { var sd = StageDropOf(db, s); if (sd == null) return ""; string name = RegionKo(sd.region); if (sd.region == GearDb.RegionGold && sd.goldMult != 1f) return name + " · 골드 ×" + sd.goldMult.ToString("0.##", CultureInfo.InvariantCulture); if (sd.region == GearDb.RegionExp && sd.expMult != 1f) return name + " · 경험 ×" + sd.expMult.ToString("0.##", CultureInfo.InvariantCulture); if (sd.region == GearDb.RegionGear) return name + " · 상자 확률 ↑"; return name; } /// 그 스테이지의 드랍 줄(stage_drop · 지역 특화 · 배율 · 지정 장비 · 없으면 null). public static GearDb.StageDrop StageDropOf(OutGameData db, BalanceConfig.StageDef s) { return db.Gear != null ? db.Gear.FocusFor(s.chapter, s.stage) : null; } /// 그 스테이지 1판의 골드 · 경험(영웅 1명) 총량 — 첫 클리어 · 반복 배율 · 지역 배율 · 개발 효과 포함(적 처치 몫을 다 더한 값). public static void StageGoldExp(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool first, out int gold, out int exp) { gold = 0; exp = 0; var e = db.Economy; var row = db.Rewards.For(s.chapter); if (row == null) return; var sd = StageDropOf(db, s); float baseGold = row.goldBase + s.stage * e.GoldPerStage; float mult = first ? e.FirstClearGoldMult : e.RepeatRewardMult; gold = Mathf.RoundToInt(baseGold * mult * (sd != null ? sd.goldMult : 1f) * DevRules.Mult(db, d, DevRules.GoldGain)); exp = Mathf.RoundToInt(row.expBase * (first ? 1f : e.RepeatRewardMult) * (sd != null ? sd.expMult : 1f) * DevRules.Mult(db, d, DevRules.ExpGain)); } /// 그 스테이지 1판의 상자 기대 개수 = gear_drop_pct(장) × f_gear_mult(스테이지 종류 × 지역) + 개발 「장비 드랍」(%p ÷ 100). public static float ChestExpect(OutGameData db, SaveData d, BalanceConfig.StageDef s) { var row = db.Rewards.For(s.chapter); if (row == null) return 0f; var sd = StageDropOf(db, s); return Mathf.Max(0f, row.gearDropPct * (sd != null ? sd.gearMult : 1f) + DevRules.Mod(db, d, DevRules.GearDrop) / 100f); } /// 한 판에 상자가 1개 이상 나올 확률(굴림 chest_rolls 회 · 1회 확률 = 기대 개수 ÷ 굴림 수). public static float ChestAnyPct(OutGameData db, SaveData d, BalanceConfig.StageDef s) { int rolls = Mathf.Max(1, db.Gear != null ? db.Gear.rules.chestRolls : 1); float p = Mathf.Clamp01(ChestExpect(db, d, s) / rolls); return 1f - Mathf.Pow(1f - p, rolls); } /// /// 전리품 굴림(출전 때 1번 · 소탕은 그 자리에서) — ① 보스 첫 클리어 = 확정 상자 boss_first_chest 개(그 장 가중치가 가장 큰 등급 · 지정 장비) /// ② 굴림 chest_rolls 회(1회 확률 = 상자 기대 개수 ÷ 굴림 수 · 최대 1) → 상자마다 RollGear. /// public static StageLoot RollLoot(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool sweep, System.Random rng) { var loot = new StageLoot { chapter = s.chapter, stage = s.stage, sweep = sweep }; if (db.Gear == null || db.Rewards.For(s.chapter) == null) return loot; var ru = db.Gear.rules; var st = d.Stage(s.chapter, s.stage, false); bool first = !sweep && (st == null || st.clears == 0); if (first && s.kind == StageKind.Boss) for (int i = 0; i < ru.bossFirstChest; i++) { var id = RollGear(db, s.chapter, s.stage, rng, true); if (id == null) continue; loot.gearIds.Add(id); loot.fixedChests++; } int rolls = Mathf.Max(1, ru.chestRolls); double p = Mathf.Clamp01(ChestExpect(db, d, s) / rolls); for (int i = 0; i < rolls; i++) { if (rng.NextDouble() >= p) continue; var id = RollGear(db, s.chapter, s.stage, rng); if (id != null) loot.gearIds.Add(id); } return loot; } /// 스테이지 정보 창 드랍 줄 — 그 장 드랍 등급 이름(gear_drop_chapters · 「고급 · 희귀」) · 가장 높은 등급(칸 색). public static string DropGradesText(OutGameData db, int chapter, out string top) { top = "white"; var row = db.Gear != null ? db.Gear.DropFor(chapter) : null; if (row == null) return ""; var names = new List(); int best = 0; foreach (var g in row.grades) { names.Add(UiKit.GearGradeKo(g)); int o = db.Gear.OrderOf(g); if (o > best) { best = o; top = g; } } return string.Join("·", names.ToArray()); } /// 그 스테이지의 지정 장비(한 병종의 부위 2개 · gear_kinds · 없으면 빈 목록). public static List FocusKinds(OutGameData db, int chapter, int stage) { var res = new List(); var f = db.Gear != null ? db.Gear.FocusFor(chapter, stage) : null; if (f == null) return res; foreach (var kind in f.kinds) foreach (var k in db.Gear.kinds) if (k.unitType == f.unitType && k.kind == kind) res.Add(k); return res; } /// 지정 장비 첫 번째(옛 호출부용 · 없으면 null). public static GearDb.Kind FocusKind(OutGameData db, int chapter, int stage) { var ks = FocusKinds(db, chapter, stage); return ks.Count > 0 ? ks[0] : null; } /// /// 상자 1개의 장비(2026-11-23 스테이지 보상 드랍 §2-1) — ① 등급 = gear_drop_chapters(그 장) 가중치(확정 상자 = 가중치가 가장 큰 등급) /// ② focus_pct % 로 그 스테이지 지정 장비(지정 병종의 부위 2개 중 하나 · 반반 · 확정 상자 = 항상) ③ 나머지 = 그 등급 장비 전부 중 균등(지정 포함 · 제한 아님). /// public static string RollGear(OutGameData db, int chapter, int stage, System.Random rng, bool fixedChest = false) { var g = db.Gear; var row = g.DropFor(chapter); if (row == null || row.grades.Length == 0) return null; string grade = row.grades[row.grades.Length - 1]; if (fixedChest) { float best = -1f; for (int i = 0; i < row.grades.Length && i < row.weights.Length; i++) if (row.weights[i] > best) { best = row.weights[i]; grade = row.grades[i]; } } else { float sum = 0f; foreach (var w in row.weights) sum += w; float at = (float)(rng.NextDouble() * sum); for (int i = 0; i < row.grades.Length && i < row.weights.Length; i++) { if (at < row.weights[i]) { grade = row.grades[i]; break; } at -= row.weights[i]; } } var focus = g.FocusFor(chapter, stage); if (focus != null && focus.kinds.Length > 0 && (fixedChest || rng.NextDouble() * 100.0 < g.rules.focusPct)) { var f = g.Find(focus.unitType, focus.kinds[rng.Next(focus.kinds.Length)], grade); if (f != null) return f.id; } var pool = new List(); foreach (var it in g.items) if (it.grade == grade) pool.Add(it.id); return pool.Count > 0 ? pool[rng.Next(pool.Count)] : null; } /// 적 1기의 처치 몫 가중치(골드 · 경험치 총량을 나누는 비율 · drop_rules kill_share_w_*) — 보스 · 무장 · 병사. public static float KillShare(OutGameData db, bool boss, bool general) { var ru = db.Gear.rules; return boss ? ru.shareBoss : general ? ru.shareGeneral : ru.shareSoldier; } /// 상자를 든 적을 고를 가중치(drop_rules chest_carrier_w_*). public static float CarrierWeight(OutGameData db, bool boss, bool general) { var ru = db.Gear.rules; return boss ? ru.carrierBoss : general ? ru.carrierGeneral : ru.carrierSoldier; } /// 보상을 세이브에 넣는다(재화 · 경험 = expTo 전원 · 장비 · 스테이지 기록 · 클리어 최고 챕터). public static void Apply(SaveData d, StageReward r, IEnumerable expTo) { if (!r.win) return; d.gold += r.gold; d.gem += r.gem; if (expTo != null) foreach (var id in expTo) { var s = d.Level(id); if (s == null || r.expTo.Contains(id)) continue; HeroRules.GrantExp(s, r.exp); r.expTo.Add(id); } foreach (var gid in r.gearIds) if (!string.IsNullOrEmpty(gid)) d.inv.AddGear(gid, 1); if (!string.IsNullOrEmpty(r.chest)) Counts.Add(d.inv.chests, r.chest, 1); var st = d.Stage(r.chapter, r.stage, true); st.clears++; st.stars = Mathf.Max(st.stars, r.stars); r.bestStars = st.stars; d.chapterMax = Mathf.Max(d.chapterMax, r.chapter); } public static int StarsOf(SaveData d, BalanceConfig.StageDef s) { var st = d.Stage(s.chapter, s.stage, false); return st != null ? st.stars : 0; } /// 소탕 = 별 3 스테이지만(최대 별 = 조건 수). public static bool CanSweep(SaveData d, BalanceConfig.StageDef s) { return StarsOf(d, s) >= 3; } // ---------- 골드 장비 상점 ---------- /// 날짜가 바뀌었거나 비었으면 shop_grades 장비 shop_slots 종(겹침 없음 · 가격 = sell_gold × shop_price_mult)을 새로 깐다. public static void EnsureShop(OutGameData db, SaveData d, DateTime nowUtc, System.Random rng) { var day = DayKey(nowUtc); if (d.shop.day == day && d.shop.items.Count > 0) return; d.shop.day = day; d.shop.refreshes = 0; Restock(db, d, rng); } static void Restock(OutGameData db, SaveData d, System.Random rng) { var e = db.Economy; var grades = new HashSet(e.ShopGrades); var pool = new List(); foreach (var it in db.Gear.items) if (grades.Contains(it.grade)) pool.Add(it); d.shop.items.Clear(); for (int i = 0; i < e.ShopSlots && pool.Count > 0; i++) { int k = rng.Next(pool.Count); var it = pool[k]; pool.RemoveAt(k); float discount = Mathf.Max(0f, 1f - DevRules.Mod(db, d, DevRules.TradeDiscount) / 100f); // 상업 「거래 할인」(PD #1093 C) d.shop.items.Add(new ShopItem { gearId = it.id, price = Mathf.RoundToInt(it.sellGold * e.ShopPriceMult * discount), sold = false }); } } /// 보옥 shop_refresh_gem 으로 다시 깔기. null = 성공. public static string RefreshShop(OutGameData db, SaveData d, System.Random rng) { int cost = FreeRefreshesLeft(db, d) > 0 ? 0 : db.Economy.ShopRefreshGem; // 시장 개설 = 하루 무료 새로고침(PD #1093 C) if (d.gem < cost) return "보옥 부족 " + d.gem + " / " + cost; d.gem -= cost; d.shop.refreshes++; Restock(db, d, rng); return null; } /// 오늘 남은 무료 새로고침(상업 「시장 개설」 Lv · 상점 refreshes = 그날 새로고침 수). public static int FreeRefreshesLeft(OutGameData db, SaveData d) { return Mathf.Max(0, Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.TradeFreeRefresh)) - d.shop.refreshes); } public static string BuyShop(SaveData d, int index) { if (index < 0 || index >= d.shop.items.Count) return "없는 칸"; var it = d.shop.items[index]; if (it.sold) return "품절"; if (d.gold < it.price) return "골드 부족 " + d.gold + " / " + it.price; d.gold -= it.price; it.sold = true; Sound.Play(SoundKeys.UiCoin); // 소리: 상점 구매(2026-11-20 사운드) d.inv.AddGear(it.gearId, 1); return null; } } }