using System; using System.Collections.Generic; using System.Globalization; using UnityEngine; namespace TKS.OutGame { /// 거래 글자 표(로컬라이징 키 · Resources/UI/Trade/trade_text.csv) — 키 → 지금 언어 글자 · {0} {1} 자리. public static class TradeText { public static string T(string key) { UiText.Use(TradeData.TextTable); return UiText.T(key).Replace("\\n", "\n"); // 표 = 한 줄 · 줄 바꿈 = 「\n」 글자(다른 글자 표와 같음) } public static string F(string key, params object[] args) { UiText.Use(TradeData.TextTable); var a = new List(); if (args != null) foreach (var x in args) a.Add(x is int ? ((int)x).ToString("N0", CultureInfo.InvariantCulture) : Convert.ToString(x, CultureInfo.InvariantCulture)); return UiText.F(key, a).Replace("\\n", "\n"); } /// 원화 표시(₩1,300 · 글자 표 「trade_krw」). public static string Krw(int krw) { return F("trade_krw", krw); } /// 광고 보상 버튼 낱말 — 광고 제거 산 계정 = 「바로」(시청 없이 바로 · 횟수 한도 그대로 · PD 2026-11-26) · 아니면 「광고」. public static string AdWord(SaveData d) { return T(TradeRules.AdFree(d) ? "trade_ad_word_free" : "trade_ad_word"); } /// 광고 보상 실행 버튼(「보기」 / 광고 제거 = 「받기」). public static string AdGo(SaveData d) { return T(TradeRules.AdFree(d) ? "trade_ad_go_free" : "trade_ad_go"); } } /// /// 거래 상품 규칙(PD 2026-11-26 결정 8건 · 기획서 2판 · 요청서 `개발요청_거래상품_2026-11-26.md`) — 기기 세이브 모드. /// 패키지(첫 결제 3일 · 광고 제거 · 일일 · 주간 단계 · 월간 · 챕터 정복 72시간 · 다시 안 나옴) · 월정액(30일 · 안 받은 날 소멸 · 연장 최대 180일) · /// 성장 패스(첫 클리어 스테이지 진행 · 무료 / 유료 줄 · 구매 = 지난 칸 소급) · 누적 결제 보상 · 오늘의 상점 9칸(무게 · 칸마다 갱신 전 1번 · 새로고침 한도) · /// 보옥 6종(상품마다 첫 구매 2배) · 골드 3종(도달 챕터 순찰 시간당 골드 × 시간 · 하루 한도). 값 = 표(TradeData · C45). /// 서버 모드 규칙(영수증 검증 · 지급 · 한도 · 타이머 = 서버 시각) = 후속. /// public static class TradeRules { static readonly DateTime Epoch = new DateTime(2000, 1, 1); /// 현지 날짜 번호(2000-01-01 = 0) — 월정액 · 첫 결제 날짜 계산. public static int DayNum(DateTime nowUtc) { return (int)Math.Floor((nowUtc.ToLocalTime().Date - Epoch).TotalDays); } public static TradeState St(SaveData d) { if (d.trade == null) d.trade = new TradeState(); var t = d.trade; if (t.pays == null) t.pays = new List(); if (t.buys == null) t.buys = new List(); if (t.gemFirst == null) t.gemFirst = new List(); if (t.monthly == null) t.monthly = new List(); if (t.passes == null) t.passes = new List(); if (t.chapters == null) t.chapters = new List(); if (t.spendClaimed == null) t.spendClaimed = new List(); if (t.shop == null) t.shop = new TradeShop(); if (t.shop.slots == null) t.shop.slots = new List(); return t; } // ---------- 기간 · 한도 ---------- /// 초기화 기간 키 — none = 1회(평생) · daily = 날 · weekly = 임무 주간 경계(상점과 같음) · monthly = 달. public static string PeriodKey(OutGameData db, string reset, DateTime nowUtc) { switch (reset) { case TradeData.RDaily: return "D" + EconomyRules.DayKey(nowUtc); case TradeData.RWeekly: return ShopRules.WeekKey(db, nowUtc); case TradeData.RMonthly: return "M" + nowUtc.ToLocalTime().ToString("yyyyMM", CultureInfo.InvariantCulture); } return "once"; } /// 그 상품을 이번 기간에 산 수. public static int Bought(OutGameData db, SaveData d, string id, string reset, DateTime nowUtc) { string key = PeriodKey(db, reset, nowUtc); int n = 0; foreach (var b in St(d).buys) if (b.id == id && b.period == key) n += b.n; return n; } static void AddBuy(OutGameData db, SaveData d, string id, string reset, DateTime nowUtc) { string key = PeriodKey(db, reset, nowUtc); var t = St(d); t.buys.RemoveAll(b => b.id == id && b.period != key); // 지난 기간 기록은 버림(한도 = 지금 기간만) foreach (var b in t.buys) if (b.id == id) { b.n++; return; } t.buys.Add(new TradeBuy { id = id, period = key, n = 1 }); } /// 초기화까지 남은 시간(일일 = 현지 자정 · 주간 = 임무 주간 경계 · 월간 = 다음 달 1일). public static TimeSpan UntilReset(OutGameData db, string reset, DateTime nowUtc) { switch (reset) { case TradeData.RDaily: return EconomyRules.UntilNextDay(nowUtc); case TradeData.RWeekly: var start = MissionRules.WeekStartFor(db.Missions.Value("weekly_reset"), nowUtc); // 현지 시각 return start.AddDays(7) - nowUtc.ToLocalTime(); case TradeData.RMonthly: var local = nowUtc.ToLocalTime(); return new DateTime(local.Year, local.Month, 1).AddMonths(1) - local; } return TimeSpan.Zero; } // ---------- 결제 이력 · 누적 금액 ---------- public static bool HasPaid(SaveData d) { return St(d).pays.Count > 0; } static void RecordPay(SaveData d, string sid, int krw, DateTime nowUtc, bool test) { var t = St(d); t.pays.Add(new TradePay { product = TradeData.ProductId(sid), krw = krw, at = SaveStore.Iso(nowUtc), test = test }); t.spentKrw += krw; } // ---------- 챕터 정복(그 챕터 마지막 스테이지 첫 클리어 · 72시간 · 다시 안 나옴 · PD 2026-11-26) ---------- /// 그 장의 마지막 스테이지를 깼는가(장마다 판 수가 다름 → 스테이지 표의 마지막 판). public static bool Conquered(BalanceConfig cfg, SaveData d, int chapter) { if (chapter <= 0) return true; var last = ContentEnemyRef.LastStage(cfg, chapter); if (last == null) return false; var s = d.Stage(chapter, last.stage, false); return s != null && s.clears > 0; } public static TradeChapter ChapterSt(SaveData d, string id) { foreach (var c in St(d).chapters) if (c.id == id) return c; return null; } public static float ChapterHours { get { return TradeData.Cfg("chapter_pack_hours", 72f); } } /// /// 챕터 정복 상품 열기 — 정복했는데 기록이 없는 상품: 가장 높은 장 1개만 지금 열고(72시간) 그 아래 장은 지나감(다시 안 나옴) · /// 새 상품이 열리면 이전 장 상품은 닫힘(「다음 챕터에서 다시 안 나옴」). 반환 = 바뀜. /// public static bool SyncChapters(OutGameData db, BalanceConfig cfg, SaveData d, DateTime nowUtc) { var t = St(d); ContentRow top = null; var fresh = new List(); foreach (var r in TradeData.Rows(TradeData.Packages)) { if (r.S("s_group") != TradeData.GChapter || ChapterSt(d, r.S("s_id")) != null) continue; if (!Conquered(cfg, d, r.I("n_open_chapter"))) continue; fresh.Add(r); if (top == null || r.I("n_open_chapter") > top.I("n_open_chapter")) top = r; } if (top == null) return false; foreach (var c in t.chapters) if (!string.IsNullOrEmpty(c.openAt)) c.closed = true; foreach (var r in fresh) t.chapters.Add(new TradeChapter { id = r.S("s_id"), openAt = r == top ? SaveStore.Iso(nowUtc) : "" }); return true; } /// 지금 팔고 있는 챕터 정복 상품인가 · 남은 시간. public static bool ChapterLive(SaveData d, string id, DateTime nowUtc, out TimeSpan left) { left = TimeSpan.Zero; var c = ChapterSt(d, id); if (c == null || c.bought || c.closed || string.IsNullOrEmpty(c.openAt)) return false; var end = SaveStore.ParseIso(c.openAt, nowUtc).AddHours(ChapterHours); left = end - nowUtc; return left > TimeSpan.Zero; } /// 다음에 열릴 챕터 정복 상품(아직 정복 안 한 가장 낮은 장 · 없으면 null). public static ContentRow NextChapter(BalanceConfig cfg, SaveData d) { ContentRow best = null; foreach (var r in TradeData.Rows(TradeData.Packages)) { if (r.S("s_group") != TradeData.GChapter || ChapterSt(d, r.S("s_id")) != null || Conquered(cfg, d, r.I("n_open_chapter"))) continue; if (best == null || r.I("n_open_chapter") < best.I("n_open_chapter")) best = r; } return best; } // ---------- 패키지 ---------- /// 패키지 화면에 보이는가(첫 결제 = 결제 이력 0 · 안 삼 / 챕터 정복 = 판매 중 / 그 밖 = 늘). public static bool PackageVisible(OutGameData db, BalanceConfig cfg, SaveData d, ContentRow r, DateTime nowUtc) { string g = r.S("s_group"), id = r.S("s_id"); if (g == TradeData.GFirst) return !HasPaid(d) && St(d).firstPayDay < 0; if (g == TradeData.GChapter) { TimeSpan left; return ChapterLive(d, id, nowUtc, out left); } return true; } /// 살 수 없는 까닭(null = 살 수 있음) — 한도 · 열림(앞 단계 · 장 클리어 · 챕터 판매 시간) · 첫 결제 = 결제 이력 0. public static string PackageBlock(OutGameData db, BalanceConfig cfg, SaveData d, ContentRow r, DateTime nowUtc) { string g = r.S("s_group"), id = r.S("s_id"); if (Bought(db, d, id, r.S("s_reset"), nowUtc) >= Mathf.Max(1, r.I("n_limit"))) return TradeText.T("trade_sold_out"); if (g == TradeData.GFirst && (HasPaid(d) || St(d).firstPayDay >= 0)) return TradeText.T("trade_first_only"); if (g == TradeData.GAdFree && St(d).adFree) return TradeText.T("trade_applied"); if (g == TradeData.GChapter) { TimeSpan left; if (!ChapterLive(d, id, nowUtc, out left)) return TradeText.T("trade_not_on_sale"); } else if (r.I("n_open_chapter") > 0 && !Conquered(cfg, d, r.I("n_open_chapter"))) return TradeText.F("trade_open_chapter", r.I("n_open_chapter")); int step = r.I("n_step"); if (step > 1) { var prev = PrevStep(r); if (prev != null && Bought(db, d, prev.S("s_id"), prev.S("s_reset"), nowUtc) <= 0) return TradeText.F("trade_open_step", step - 1); } return null; } /// 같은 묶음의 앞 단계(n_step − 1). public static ContentRow PrevStep(ContentRow r) { int step = r.I("n_step"); foreach (var x in TradeData.Rows(TradeData.Packages)) if (x.S("s_group") == r.S("s_group") && x.I("n_step") == step - 1) return x; return null; } static List GrantPackage(OutGameData db, BalanceConfig cfg, SaveData d, ContentRow r, Dictionary picks, DateTime nowUtc, System.Random rng) { var t = St(d); string g = r.S("s_group"), id = r.S("s_id"); AddBuy(db, d, id, r.S("s_reset"), nowUtc); if (g == TradeData.GFirst) { t.firstPayDay = DayNum(nowUtc); t.firstPayClaimed = 0; return ClaimFirstPay(db, d, nowUtc, picks, rng); } if (g == TradeData.GAdFree) t.adFree = true; if (g == TradeData.GChapter) { var c = ChapterSt(d, id); if (c != null) c.bought = true; } return GoodsRules.GiveParts(db, d, r.S("l_items"), rng, picks); } // ---------- 첫 결제 「출사표」(3일에 나눠 받기 · 1일째 = 즉시 · 2 · 3일째 = 다음 날 접속 때) ---------- public static ContentRow FirstPayRow() { foreach (var r in TradeData.Rows(TradeData.Packages)) if (r.S("s_group") == TradeData.GFirst) return r; return null; } /// 지금 받을 수 있는 첫 결제 날(1부터) · 없으면 0. public static int FirstPayDue(SaveData d, DateTime nowUtc) { var t = St(d); var r = FirstPayRow(); if (t.firstPayDay < 0 || r == null) return 0; int days = TradeData.Days(r.S("l_items")).Count; int next = t.firstPayClaimed + 1; if (next > days) return 0; return DayNum(nowUtc) - t.firstPayDay >= next - 1 ? next : 0; } /// 그 날 꾸러미(1부터 · 없으면 ""). public static string FirstPayParts(int day) { var r = FirstPayRow(); var days = r != null ? TradeData.Days(r.S("l_items")) : new List(); return day >= 1 && day <= days.Count ? days[day - 1] : ""; } /// 받을 수 있는 날을 모두 받음(지난 날이 밀려 있으면 함께) → 얻은 것. public static List ClaimFirstPay(OutGameData db, SaveData d, DateTime nowUtc, Dictionary picks, System.Random rng) { var res = new List(); var t = St(d); int day; while ((day = FirstPayDue(d, nowUtc)) > 0) { GoodsRules.AddAll(res, GoodsRules.GiveParts(db, d, FirstPayParts(day), rng, picks)); t.firstPayClaimed = day; } return res; } // ---------- 월정액(30일 · 매일 받기 · 안 받은 날 소멸 · 연장 = 남은 기간 + 30일 · 최대 180일) ---------- public static TradeMonthly Mon(SaveData d, string id, bool create) { var t = St(d); foreach (var m in t.monthly) if (m.id == id) return m; if (!create) return null; var n = new TradeMonthly { id = id }; t.monthly.Add(n); return n; } /// 남은 일수(오늘 포함 · 0 = 없음). public static int DaysLeft(SaveData d, string id, DateTime nowUtc) { var m = Mon(d, id, false); return m != null ? Mathf.Max(0, m.endDay - DayNum(nowUtc)) : 0; } public static int MonthlyMaxDays { get { return TradeData.CfgInt("monthly_max_days", 180); } } public static string MonthlyBlock(SaveData d, ContentRow r, DateTime nowUtc) { if (DaysLeft(d, r.S("s_id"), nowUtc) + r.I("n_days") > MonthlyMaxDays) return TradeText.F("trade_monthly_max", MonthlyMaxDays); return null; } static List GrantMonthly(OutGameData db, SaveData d, ContentRow r, DateTime nowUtc, System.Random rng) { var m = Mon(d, r.S("s_id"), true); int today = DayNum(nowUtc), left = DaysLeft(d, m.id, nowUtc); if (left > 0) m.endDay += r.I("n_days"); else { m.endDay = today + r.I("n_days"); m.lastClaimDay = -1; } return GoodsRules.GiveParts(db, d, r.S("l_instant"), rng); } public static bool MonthlyClaimable(SaveData d, string id, DateTime nowUtc) { var m = Mon(d, id, false); return m != null && DaysLeft(d, id, nowUtc) > 0 && m.lastClaimDay != DayNum(nowUtc); } /// 오늘 받기(안 받은 지난 날은 사라짐 = 오늘 몫만). public static List ClaimMonthly(OutGameData db, SaveData d, string id, DateTime nowUtc, System.Random rng) { var r = TradeData.MonthlyRow(id); if (r == null || !MonthlyClaimable(d, id, nowUtc)) return new List(); Mon(d, id, false).lastClaimDay = DayNum(nowUtc); return GoodsRules.GiveParts(db, d, r.S("l_daily"), rng); } /// 쓰고 있는 월정액의 혜택 값(같은 혜택 = 큰 값) · 없으면 0 — patrol_cap_hours · shop_free_refresh · patrol_instant_free. public static float Perk(SaveData d, string key, DateTime nowUtc) { if (d == null || d.trade == null) return 0f; float v = 0f; foreach (var r in TradeData.Rows(TradeData.Monthly)) { if (DaysLeft(d, r.S("s_id"), nowUtc) <= 0) continue; float x; if (TradeData.Map(r.S("l_perks")).TryGetValue(key, out x)) v = Mathf.Max(v, x); } return v; } public const string PerkPatrolCap = "patrol_cap_hours"; public const string PerkShopRefresh = "shop_free_refresh"; public const string PerkInstantFree = "patrol_instant_free"; /// 오늘 순찰 즉시 수확이 무료인가(명장 월정액 · 하루 1회). public static bool InstantFree(SaveData d, DateTime nowUtc) { return Perk(d, PerkInstantFree, nowUtc) > 0f && St(d).instantFreeDay != DayNum(nowUtc); } public static void UseInstantFree(SaveData d, DateTime nowUtc) { St(d).instantFreeDay = DayNum(nowUtc); } // ---------- 성장 패스(출정 첫 클리어 진행 · 무료 / 유료 줄 · 구매 = 지난 칸 소급 · 기간 없음) ---------- public static bool Hard(ContentRow p) { return p.S("s_mode") == "hard"; } public static int Cells(ContentRow p) { int step = Mathf.Max(1, p.I("n_step")); return (p.I("n_to_ch") - p.I("n_from_ch") + 1) * p.I("n_stages_per_ch") / step; } /// 칸 k(1부터) → 장 · 판(표 n_stages_per_ch · n_step 그대로 · 예 1권 = 1-2 · 1-4 … 5-10). public static void CellStage(ContentRow p, int k, out int chapter, out int stage) { int per = Mathf.Max(1, p.I("n_stages_per_ch")); int idx = k * Mathf.Max(1, p.I("n_step")); chapter = p.I("n_from_ch") + (idx - 1) / per; stage = (idx - 1) % per + 1; } public static bool Reached(SaveData d, ContentRow p, int k) { int ch, st; CellStage(p, k, out ch, out st); var s = d.Stage(ch, st, false, Hard(p)); return s != null && s.clears > 0; } /// 진행 = 다다른 칸 수. public static int Progress(SaveData d, ContentRow p) { int n = 0, cells = Cells(p); for (int k = 1; k <= cells; k++) if (Reached(d, p, k)) n++; return n; } /// 칸 종류 — 마지막 칸 = last · 5칸째마다 = m5 · 그 밖 = base(trade_pass_rewards s_when). public static string When(ContentRow p, int k) { if (k == Cells(p)) return "last"; return k % 5 == 0 ? "m5" : "base"; } public static string CellReward(string pass, string track, string when) { foreach (var r in TradeData.Rows(TradeData.PassRewards)) if (r.S("s_pass") == pass && r.S("s_track") == track && r.S("s_when") == when) return r.S("l_items"); return ""; } public static string CellReward(ContentRow p, int k, string track) { return CellReward(p.S("s_pass"), track, When(p, k)); } /// 권 열림 — s_open 빈칸 = 처음부터 · chapter:n = n장 진입 · hard:n = 하드 n장 열림. public static bool PassOpen(OutGameData db, SaveData d, ContentRow p) { var open = p.S("s_open"); if (string.IsNullOrEmpty(open)) return true; var kv = open.Split(':'); int n; if (kv.Length != 2 || !int.TryParse(kv[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) return true; if (kv[0] == "chapter") return d.chapterMax >= n; if (kv[0] == "hard") return EconomyRules.HardOpen(db, d, n); return true; } public static TradePass PassSt(SaveData d, string id) { var t = St(d); foreach (var p in t.passes) if (p.id == id) return p; var n = new TradePass { id = id }; t.passes.Add(n); return n; } public const string Free = "free"; public const string Paid = "paid"; public static bool Claimed(SaveData d, ContentRow p, int k, string track) { var ps = PassSt(d, p.S("s_pass")); return (track == Paid ? ps.paid : ps.free).Contains(k); } public static bool CanClaim(SaveData d, ContentRow p, int k, string track) { if (k < 1 || k > Cells(p) || !Reached(d, p, k) || Claimed(d, p, k, track)) return false; return track == Free || PassSt(d, p.S("s_pass")).bought; } public static int ClaimableCount(SaveData d, ContentRow p) { int n = 0, cells = Cells(p); for (int k = 1; k <= cells; k++) { if (CanClaim(d, p, k, Free)) n++; if (CanClaim(d, p, k, Paid)) n++; } return n; } /// 받을 칸 꾸러미(k = 0 → 받을 수 있는 칸 모두 · 아니면 그 칸 그 줄만). public static string ClaimParts(SaveData d, ContentRow p, int k, string track) { var parts = new List(); int cells = Cells(p); for (int i = 1; i <= cells; i++) { if (k > 0 && i != k) continue; foreach (var tr in new[] { Free, Paid }) if ((k == 0 || tr == track) && CanClaim(d, p, i, tr)) parts.Add(CellReward(p, i, tr)); } return string.Join(";", parts.ToArray()); } /// 받기(k = 0 = 모두 받기) → 얻은 것. public static List ClaimPass(OutGameData db, SaveData d, string id, int k, string track, Dictionary picks, System.Random rng) { var res = new List(); var p = TradeData.Pass(id); if (p == null) return res; var ps = PassSt(d, id); int cells = Cells(p); for (int i = 1; i <= cells; i++) { if (k > 0 && i != k) continue; foreach (var tr in new[] { Free, Paid }) { if (k > 0 && tr != track) continue; if (!CanClaim(d, p, i, tr)) continue; GoodsRules.AddAll(res, GoodsRules.GiveParts(db, d, CellReward(p, i, tr), rng, picks)); (tr == Paid ? ps.paid : ps.free).Add(i); } } return res; } static List GrantPass(OutGameData db, SaveData d, ContentRow p, Dictionary picks, System.Random rng) { var ps = PassSt(d, p.S("s_pass")); ps.bought = true; // 소급 = 이미 다다른 칸의 유료 줄을 바로 지급(PD 「늦게 사도 손해 없음」) var res = new List(); int cells = Cells(p); for (int k = 1; k <= cells; k++) { if (!CanClaim(d, p, k, Paid)) continue; GoodsRules.AddAll(res, GoodsRules.GiveParts(db, d, CellReward(p, k, Paid), rng, picks)); ps.paid.Add(k); } return res; } /// 구매 때 바로 받는 유료 줄 꾸러미(소급 · 고르기 팝업용). public static string RetroParts(SaveData d, ContentRow p) { var parts = new List(); int cells = Cells(p); for (int k = 1; k <= cells; k++) if (Reached(d, p, k) && !Claimed(d, p, k, Paid)) parts.Add(CellReward(p, k, Paid)); return string.Join(";", parts.ToArray()); } // ---------- 누적 결제 보상(초기화 없음 · 전용 꾸미기) ---------- public static bool SpendClaimed(SaveData d, int step) { return St(d).spendClaimed.Contains(step); } public static bool SpendClaimable(SaveData d, ContentRow r) { return St(d).spentKrw >= r.I("n_krw") && !SpendClaimed(d, r.I("n_step")); } public static List ClaimSpend(OutGameData db, SaveData d, int step, Dictionary picks, System.Random rng) { foreach (var r in TradeData.Rows(TradeData.Spend)) { if (r.I("n_step") != step || !SpendClaimable(d, r)) continue; St(d).spendClaimed.Add(step); return GoodsRules.GiveParts(db, d, r.S("l_items"), rng, picks); } return new List(); } // ---------- 오늘의 상점 9칸(무게 · 칸마다 갱신 전 1번 · 새로고침 = 1번 칸 제외 · 하루 한도) ---------- public static List SlotRows(int slot) { var res = new List(); foreach (var r in TradeData.Rows(TradeData.ShopDaily)) if (r.I("n_slot") == slot) res.Add(r); return res; } public static List SlotNumbers() { var res = new List(); foreach (var r in TradeData.Rows(TradeData.ShopDaily)) if (!res.Contains(r.I("n_slot"))) res.Add(r.I("n_slot")); res.Sort(); return res; } /// 그 칸의 무료 칸인가(값의 재화 = ad). public static bool IsFreeSlot(int slot) { var rows = SlotRows(slot); return rows.Count > 0 && rows[0].S("s_currency") == TradeData.CurAd; } public static ContentRow SlotRow(TradeSlot s) { var rows = SlotRows(s.slot); return s.row >= 0 && s.row < rows.Count ? rows[s.row] : null; } public static TradeSlot Slot(SaveData d, int slot) { foreach (var s in St(d).shop.slots) if (s.slot == slot) return s; return null; } /// ★1 · ★2 영웅 조각 = 굴릴 때 영웅을 정함(떠돌이 상인 방식) · ★3 조각 = 살 때 고름. static void RollSlot(OutGameData db, TradeSlot s, System.Random rng) { var rows = SlotRows(s.slot); float sum = 0f; foreach (var r in rows) sum += Mathf.Max(0f, r.F("n_weight")); double x = rng.NextDouble() * sum; s.row = rows.Count - 1; for (int i = 0; i < rows.Count; i++) { x -= Mathf.Max(0f, rows[i].F("n_weight")); if (x < 0) { s.row = i; break; } } s.bought = false; s.heroId = ""; var row = SlotRow(s); if (row == null) return; int rar = GoodsRules.ShardRarity(row.S("s_item")); if (rar > 0 && GoodsRules.PickKind(db, row.S("s_item")) == null) { var pool = WanderRules.Heroes(db, rar); if (pool.Count > 0) s.heroId = pool[rng.Next(pool.Count)].id; } } /// 날이 바뀌었거나 비었으면 9칸을 새로 굴림 · 반환 = 바뀜. public static bool EnsureShop(OutGameData db, SaveData d, DateTime nowUtc, System.Random rng) { var sh = St(d).shop; var day = EconomyRules.DayKey(nowUtc); var nums = SlotNumbers(); if (sh.day == day && sh.slots.Count == nums.Count) return false; sh.day = day; sh.refreshes = 0; sh.slots.Clear(); foreach (int n in nums) { var s = new TradeSlot { slot = n }; RollSlot(db, s, rng); sh.slots.Add(s); } return true; } public static int RefreshLimit { get { return TradeData.CfgInt("shop_refresh_daily", 5); } } /// 오늘 무료 새로고침 수 = 내정 「시장 개설」 + 명장 월정액(+1). public static int FreeRefreshes(OutGameData db, SaveData d, DateTime nowUtc) { return Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.TradeFreeRefresh)) + Mathf.RoundToInt(Perk(d, PerkShopRefresh, nowUtc)); } public static int FreeRefreshLeft(OutGameData db, SaveData d, DateTime nowUtc) { return Mathf.Max(0, Mathf.Min(FreeRefreshes(db, d, nowUtc), RefreshLimit) - St(d).shop.refreshes); } public static int RefreshLeft(SaveData d) { return Mathf.Max(0, RefreshLimit - St(d).shop.refreshes); } /// 새로고침(무료 횟수 먼저 · 그다음 보옥 economy shop_refresh_gem · 하루 한도 · 1번 무료 칸은 그대로). null = 성공. public static string Refresh(OutGameData db, SaveData d, DateTime nowUtc, System.Random rng) { EnsureShop(db, d, nowUtc, rng); var sh = St(d).shop; if (RefreshLeft(d) <= 0) return TradeText.F("trade_refresh_limit", RefreshLimit); int cost = FreeRefreshLeft(db, d, nowUtc) > 0 ? 0 : db.Economy.ShopRefreshGem; if (d.gem < cost) return TradeText.F("trade_short_gem", d.gem, cost); d.gem -= cost; sh.refreshes++; foreach (var s in sh.slots) if (!IsFreeSlot(s.slot)) RollSlot(db, s, rng); return null; } /// 칸 값 — 상자 칸(골드 · 보옥) = 내정 「거래 할인」 적용(보물 상자 탭에서 옮김 · PD 2026-11-26 제안 반영). public static int SlotPrice(OutGameData db, SaveData d, ContentRow r) { int p = r.I("n_price"); if (p <= 0 || GoodsRules.ChestOf(r.S("s_item")) == null || r.S("s_currency") == TradeData.CurAd) return p; return Mathf.Max(1, Mathf.RoundToInt(p * Mathf.Max(0f, 1f - DevRules.Mod(db, d, DevRules.TradeDiscount) / 100f))); } public static string SlotBlock(OutGameData db, SaveData d, int slot, DateTime nowUtc) { var s = Slot(d, slot); var r = s != null ? SlotRow(s) : null; if (r == null || St(d).shop.day != EconomyRules.DayKey(nowUtc)) return TradeText.T("trade_not_on_sale"); if (s.bought) return TradeText.T("trade_sold_out"); int price = SlotPrice(db, d, r); string cur = r.S("s_currency"); if (cur == TradeData.CurGem && d.gem < price) return TradeText.F("trade_short_gem", d.gem, price); if (cur == TradeData.CurGold && d.gold < price) return TradeText.F("trade_short_gold", d.gold, price); return null; } /// 칸 사기(pick = ★3 조각 영웅 · 진영 비서 진영) — 무료 칸 = 광고 1회(광고 SDK 미연동 = 바로 · 광고 제거 = 바로). null = 성공. public static string BuySlot(OutGameData db, SaveData d, int slot, string pick, DateTime nowUtc, System.Random rng, List gains) { var why = SlotBlock(db, d, slot, nowUtc); if (why != null) return why; var s = Slot(d, slot); var r = SlotRow(s); int price = SlotPrice(db, d, r); string cur = r.S("s_currency"); if (cur == TradeData.CurGem) d.gem -= price; else if (cur == TradeData.CurGold) d.gold -= price; s.bought = true; string item = r.S("s_item"); string p = !string.IsNullOrEmpty(s.heroId) ? s.heroId : pick; var got = GoodsRules.Give(db, d, item, r.I("n_amount"), rng, p); if (gains != null) GoodsRules.AddAll(gains, got); return null; } /// 무료 칸을 아직 안 받았는가(상점 빨간 점). public static bool FreeSlotReady(SaveData d, DateTime nowUtc) { var sh = St(d).shop; if (sh.day != EconomyRules.DayKey(nowUtc)) return SlotNumbers().Exists(IsFreeSlot); // 오늘 아직 안 굴림 = 새 무료 칸 foreach (var s in sh.slots) if (IsFreeSlot(s.slot) && !s.bought) return true; return false; } // ---------- 보옥 6종(첫 구매 2배) · 골드 3종(보옥으로 · 하루 한도) ---------- public static bool GemFirst(SaveData d, string id) { return !St(d).gemFirst.Contains(id); } public static int GemAmount(SaveData d, ContentRow g) { return g.I("n_gem") + (GemFirst(d, g.S("s_id")) ? g.I("n_first_bonus") : 0); } static List GrantGem(OutGameData db, SaveData d, ContentRow g, System.Random rng) { int n = GemAmount(d, g); St(d).gemFirst.Add(g.S("s_id")); return GoodsRules.Give(db, d, "gem", n, rng); } /// 골드 양 = 도달 챕터 순찰 시간당 골드(PatrolRules.GoldPerHour · patrol.csv) × 시간. public static int GoldAmount(OutGameData db, SaveData d, ContentRow g) { return Mathf.RoundToInt(PatrolRules.GoldPerHour(db, d) * g.F("n_hours")); } public static string GoldBlock(OutGameData db, SaveData d, ContentRow g, DateTime nowUtc) { if (Bought(db, d, g.S("s_id"), TradeData.RDaily, nowUtc) >= g.I("n_daily_limit")) return TradeText.T("trade_sold_out"); if (d.gem < g.I("n_gem")) return TradeText.F("trade_short_gem", d.gem, g.I("n_gem")); return null; } public static string BuyGold(OutGameData db, SaveData d, string id, DateTime nowUtc, System.Random rng, List gains) { var g = TradeData.Gold(id); if (g == null) return TradeText.T("trade_not_on_sale"); var why = GoldBlock(db, d, g, nowUtc); if (why != null) return why; d.gem -= g.I("n_gem"); AddBuy(db, d, id, TradeData.RDaily, nowUtc); var got = GoodsRules.Give(db, d, "gold", GoldAmount(db, d, g), rng); if (gains != null) GoodsRules.AddAll(gains, got); return null; } // ---------- 결제 상품 공통(패키지 · 월정액 · 성장 패스 · 보옥) ---------- /// 결제 전에 막는 까닭(null = 결제 가능 — 결제 뒤 지급이 막히는 일이 없게 먼저 본다). public static string CanPurchase(OutGameData db, BalanceConfig cfg, SaveData d, string sid, DateTime nowUtc) { switch (TradeData.KindOf(sid)) { case "pkg": return PackageBlock(db, cfg, d, TradeData.Package(sid), nowUtc); case "monthly": return MonthlyBlock(d, TradeData.MonthlyRow(sid), nowUtc); case "pass": var p = TradeData.Pass(sid); if (PassSt(d, sid).bought) return TradeText.T("trade_applied"); if (!PassOpen(db, d, p)) return TradeText.T("trade_pass_locked"); return null; case "gem": return null; } return TradeText.T("trade_not_on_sale"); } /// 결제가 끝난 상품 지급(결제 이력 · 누적 금액 기록 포함) → 얻은 것(gains). null = 성공. public static string Purchase(OutGameData db, BalanceConfig cfg, SaveData d, string sid, Dictionary picks, DateTime nowUtc, System.Random rng, List gains, bool test) { var why = CanPurchase(db, cfg, d, sid, nowUtc); if (why != null) return why; List got; switch (TradeData.KindOf(sid)) { case "pkg": got = GrantPackage(db, cfg, d, TradeData.Package(sid), picks, nowUtc, rng); break; case "monthly": got = GrantMonthly(db, d, TradeData.MonthlyRow(sid), nowUtc, rng); break; case "pass": got = GrantPass(db, d, TradeData.Pass(sid), picks, rng); break; default: got = GrantGem(db, d, TradeData.Gem(sid), rng); break; } RecordPay(d, sid, TradeData.PriceKrw(sid), nowUtc, test); if (gains != null) GoodsRules.AddAll(gains, got); return null; } /// 구매 · 받기 때 바로 지급되는 꾸러미(고르기 팝업 = 이 안의 고르는 낱말). public static string GrantParts(SaveData d, string sid) { switch (TradeData.KindOf(sid)) { case "pkg": var r = TradeData.Package(sid); return r.S("s_group") == TradeData.GFirst ? FirstPayParts(1) : r.S("l_items"); case "monthly": return TradeData.MonthlyRow(sid).S("l_instant"); case "pass": return RetroParts(d, TradeData.Pass(sid)); } return ""; } /// 꾸러미 안의 고르는 낱말(겹침 없음 · 표 순서) — 화면이 낱말마다 한 번 고르게 한다. public static List PickKeys(OutGameData db, string parts) { var res = new List(); foreach (var kv in TradeData.Items(parts)) if (GoodsRules.PickKind(db, kv.Key) != null && !res.Contains(kv.Key)) res.Add(kv.Key); return res; } /// 상품의 가치 배수(패키지 = 모든 날 · 월정액 = 즉시 + 매일 × 일수 · 성장 패스 = 유료 줄 전체 · 보옥 = 첫 구매 제외). public static float ValueMult(string sid) { float v = 0f; switch (TradeData.KindOf(sid)) { case "pkg": v = TradeData.GemValue(TradeData.Package(sid).S("l_items")); break; case "monthly": var m = TradeData.MonthlyRow(sid); v = TradeData.GemValue(m.S("l_instant")) + TradeData.GemValue(m.S("l_daily")) * m.I("n_days"); break; case "pass": var p = TradeData.Pass(sid); for (int k = 1, n = Cells(p); k <= n; k++) v += TradeData.GemValue(CellReward(p, k, Paid)); break; case "gem": v = TradeData.Gem(sid).I("n_gem"); break; } return TradeData.ValueMult(v, TradeData.PriceKrw(sid)); } /// 꾸러미 안의 보물 상자(확률 정보 링크 대상). public static List ChestsIn(string parts) { var res = new List(); foreach (var kv in TradeData.Items(parts)) { var c = GoodsRules.ChestOf(kv.Key); if (c != null && !res.Contains(c)) res.Add(c); } return res; } // ---------- 빨간 점(패키지 = 새 챕터 정복 · 상점 = 무료 칸 · 패스 = 받을 칸 · 월정액 = 오늘 받기) ---------- public static bool DotPackage(SaveData d, DateTime nowUtc) { foreach (var c in St(d).chapters) { TimeSpan left; if (!c.seen && ChapterLive(d, c.id, nowUtc, out left)) return true; } return false; } public static void SeeChapters(SaveData d) { foreach (var c in St(d).chapters) c.seen = true; } public static bool DotPassGrowth(OutGameData db, SaveData d) { foreach (var p in TradeData.Rows(TradeData.PassGrowth)) if (PassOpen(db, d, p) && ClaimableCount(d, p) > 0) return true; return false; } public static bool DotMonthly(SaveData d, DateTime nowUtc) { foreach (var r in TradeData.Rows(TradeData.Monthly)) if (MonthlyClaimable(d, r.S("s_id"), nowUtc)) return true; return false; } public static bool DotSpend(SaveData d) { foreach (var r in TradeData.Rows(TradeData.Spend)) if (SpendClaimable(d, r)) return true; return false; } public static bool AnyDot(OutGameData db, SaveData d, DateTime nowUtc) { return DotPackage(d, nowUtc) || DotSpend(d) || FreeSlotReady(d, nowUtc) || DotPassGrowth(db, d) || DotMonthly(d, nowUtc) || FirstPayDue(d, nowUtc) > 0; } /// 광고 제거를 샀는가(광고 보상 = 시청 없이 바로 · 횟수 한도 그대로). public static bool AdFree(SaveData d) { return d != null && d.trade != null && d.trade.adFree; } // ---------- 표 검사(테스트) ---------- public static List Validate(OutGameData db) { var e = new List(); foreach (var t in TradeData.Tables) if (TradeData.Rows(t).Count == 0) e.Add(t + ".csv: 줄 없음"); Action parts = (where, s) => { foreach (var kv in TradeData.Items(s)) if (!GoodsRules.Known(db, kv.Key) || kv.Value <= 0) e.Add(where + ": 낱말 「" + kv.Key + ":" + kv.Value + "」 모름"); }; foreach (var r in TradeData.Rows(TradeData.Packages)) { if (TradeData.Krw(r.S("s_tier")) <= 0) e.Add("packages " + r.S("s_id") + ": 가격 단계 없음"); parts("packages " + r.S("s_id"), r.S("l_items")); } foreach (var r in TradeData.Rows(TradeData.Monthly)) { if (TradeData.Krw(r.S("s_tier")) <= 0) e.Add("monthly " + r.S("s_id") + ": 가격 단계 없음"); parts("monthly " + r.S("s_id"), r.S("l_instant") + ";" + r.S("l_daily")); } foreach (var p in TradeData.Rows(TradeData.PassGrowth)) { if (TradeData.Krw(p.S("s_tier")) <= 0) e.Add("pass " + p.S("s_pass") + ": 가격 단계 없음"); foreach (var tr in new[] { Free, Paid }) foreach (var w in new[] { "base", "m5", "last" }) if (CellReward(p.S("s_pass"), tr, w).Length == 0) e.Add("pass " + p.S("s_pass") + " " + tr + " " + w + ": 보상 줄 없음"); else parts("pass " + p.S("s_pass"), CellReward(p.S("s_pass"), tr, w)); } foreach (var r in TradeData.Rows(TradeData.Spend)) parts("spend " + r.I("n_step"), r.S("l_items")); foreach (var r in TradeData.Rows(TradeData.ShopDaily)) { if (!GoodsRules.Known(db, r.S("s_item"))) e.Add("shop_daily " + r.I("n_slot") + ": 낱말 「" + r.S("s_item") + "」 모름"); var cur = r.S("s_currency"); if (cur != TradeData.CurAd && cur != TradeData.CurGem && cur != TradeData.CurGold) e.Add("shop_daily " + r.I("n_slot") + ": 재화 「" + cur + "」"); } foreach (var g in TradeData.Rows(TradeData.Gems)) if (TradeData.Krw(g.S("s_tier")) <= 0) e.Add("gem " + g.S("s_id") + ": 가격 단계 없음"); return e; } } }