using System; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using UnityEngine; namespace TKS.OutGame { /// 일일 · 주간 한 기간(초기화마다 새로) — 그 기간의 칸(임무 id) · 카운터 · 받은 임무 · 포인트 · 받은 구간. [Serializable] public class MissionPeriod { [Tooltip("기간 키(일 = 시작일 yyyyMMdd · 주 = W + 시작일)")] public string key = ""; [Tooltip("초기화 순간에 정한 칸별 임무 id(잠긴 콘텐츠 칸 = 대체 임무 · 기간 도중에는 바뀌지 않음)")] public List slots = new List(); public List counts = new List(); public List claimed = new List(); public int points; public List boxes = new List(); [Tooltip("포인트 상한에 닿았다(daily_full · weekly_full 을 센 뒤)")] public bool full; } [Serializable] public class MissionState { [Tooltip("기존 카운터(s_code_now)를 업적 누적으로 한 번 옮겼다")] public bool seeded; [Tooltip("Add 카운터 계정 누적(업적)")] public List totals = new List(); public MissionPeriod day = new MissionPeriod(); public MissionPeriod week = new MissionPeriod(); [Tooltip("업적 id → 받은 단계 수")] public List achieve = new List(); } /// 기기 우편 1통(서버 우편 형식 = 제목 · 내용 · 보상 목록 · 만든 때) — 글은 kind 의 글자 표 키 + args 로 화면에서 만든다. [Serializable] public class MailEntry { public int id; [Tooltip("우편 종류(글자 표 키 mail__title · mail__body)")] public string kind = ""; public List args = new List(); [Tooltip("키:수;키:수")] public string reward = ""; public string at = ""; } [Serializable] public class MailState { public int seq; public List items = new List(); } /// 임무 한 줄(화면 · 시험). public class MissionRow { public MissionDb.Mission m; public int count; public bool done; public bool claimed; public bool Claimable { get { return done && !claimed; } } } /// 업적 한 줄 = 그 종류의 지금 단계. public class AchRow { public MissionDb.Achievement a; /// 지금 단계(1부터) · 정한 단계 수를 넘으면 반복 단계. public int step; public int goal; public int gem; public int value; public bool allDone; public bool repeat; public bool Claimable { get { return !allDone && value >= goal; } } public float Progress { get { return allDone ? 1f : goal > 0 ? Mathf.Clamp01(value / (float)goal) : 0f; } } } public class AchClaim { public MissionDb.Achievement a; public int step; public int goal; public int gem; } /// /// 임무 규칙(기획서 3 · 4 · 8 · 9쪽 · 개발 요청서 §2 · 2026-11-20 PD 컨펌) — 표 = MissionDb(C45) · 상태 = SaveData.mission · 우편 = SaveData.mail. /// 기간 경계 = 기기 현지 시각(다른 일일 규칙 EconomyRules.DayKey 와 같음) + mission_config daily_reset(cfg:common.daily_reset_hour) · weekly_reset(요일;시). /// 초기화 = 끝냈지만 안 받은 임무 포인트 자동 더함 → 상한이면 daily_full/weekly_full → 닿았지만 안 받은 구간 보상 = 우편. /// public static class MissionRules { /// 세이브에서 다시 계산하는 State 카운터(코드가 아는 것 · 임포터 검증). public static readonly string[] StateKeys = { "stage_star", "tower_floor", "scenario_clear", "hero_own" }; /// 그날 첫 접속에 오르는 카운터(mission_counters s_when_ko 「그날 첫 접속」). static readonly string[] LoginKeys = { "login", "login_days" }; public const string MailDaily = "mission_daily"; public const string MailWeekly = "mission_weekly"; static readonly Regex Ident = new Regex("^[a-z_]+$"); // ---------- 표 참조 ---------- /// 「cfg:<모드>.<키>」 = content_modes_config 값 · 그 밖 = 그대로. public static string CfgRef(string v) { if (v == null || !v.StartsWith("cfg:")) return v ?? ""; var rest = v.Substring(4); int dot = rest.IndexOf('.'); if (dot <= 0) return ""; return ContentTables.Str(rest.Substring(0, dot), rest.Substring(dot + 1)); } /// s_unlock 「cfg:<모드>.unlock_stage」 의 모드(형식이 아니면 null). public static string UnlockMode(string v) { if (v == null || !v.StartsWith("cfg:")) return null; var rest = v.Substring(4); int dot = rest.IndexOf('.'); return dot > 0 && rest.Substring(dot + 1).Length > 0 ? rest.Substring(0, dot) : null; } public static bool ParseWeekly(string v, out DayOfWeek dow, out int hour) { dow = DayOfWeek.Monday; hour = 0; var p = (v ?? "").Split(';'); if (p.Length != 2 || !int.TryParse(p[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out hour)) return false; var names = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames; // Sun Mon … for (int i = 0; i < names.Length; i++) if (string.Equals(names[i], p[0].Trim(), StringComparison.OrdinalIgnoreCase)) { dow = (DayOfWeek)i; return hour >= 0 && hour < 24; } return false; } static int ResetHour(MissionDb db) { int h; return int.TryParse(CfgRef(db.Value("daily_reset")), NumberStyles.Integer, CultureInfo.InvariantCulture, out h) ? Mathf.Clamp(h, 0, 23) : 0; } /// 지금이 속한 하루의 시작(현지). public static DateTime DayStart(MissionDb db, DateTime nowUtc) { var local = nowUtc.ToLocalTime(); var s = local.Date.AddHours(ResetHour(db)); return local < s ? s.AddDays(-1) : s; } /// 지금이 속한 주의 시작(현지 · weekly_reset 요일;시). public static DateTime WeekStart(MissionDb db, DateTime nowUtc) { return WeekStartFor(db.Value("weekly_reset"), nowUtc); } /// 「요일;시」 경계로 지금이 속한 주의 시작(현지) — 임무 주간 · 비서 교환 주간 한도가 같이 쓴다. public static DateTime WeekStartFor(string spec, DateTime nowUtc) { DayOfWeek dow; int hour; ParseWeekly(spec, out dow, out hour); var local = nowUtc.ToLocalTime(); int back = ((int)local.DayOfWeek - (int)dow + 7) % 7; var s = local.Date.AddDays(-back).AddHours(hour); return local < s ? s.AddDays(-7) : s; } public static string DayKey(MissionDb db, DateTime nowUtc) { return DayStart(db, nowUtc).ToString("yyyyMMdd", CultureInfo.InvariantCulture); } public static string WeekKey(MissionDb db, DateTime nowUtc) { return "W" + WeekStart(db, nowUtc).ToString("yyyyMMdd", CultureInfo.InvariantCulture); } /// 다음 초기화까지 남은 시간. public static TimeSpan UntilReset(MissionDb db, string kind, DateTime nowUtc) { var local = nowUtc.ToLocalTime(); var next = kind == MissionDb.Daily ? DayStart(db, nowUtc).AddDays(1) : WeekStart(db, nowUtc).AddDays(7); return next - local; } static bool StageCleared(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; } /// 로비 「임무」 버튼이 열렸는가(mission_config unlock_stage 클리어). public static bool MenuOpen(OutGameData og, SaveData d) { return og.Missions != null && StageCleared(d, og.Missions.Value("unlock_stage")); } /// 그 임무의 콘텐츠가 열렸는가(s_unlock none = 늘 열림). public static bool ContentOpen(SaveData d, MissionDb.Mission m) { if (m == null || m.unlock == "none" || m.unlock.Length == 0) return true; return StageCleared(d, CfgRef(m.unlock)); } // ---------- 카운터 ---------- static MissionPeriod Period(SaveData d, string kind) { return kind == MissionDb.Daily ? d.mission.day : d.mission.week; } /// 기간 맞춤(초기화) 뒤 카운터 +n — 화면 · 전투 결과 · 세션이 부른다. public static void Count(OutGameData og, SaveData d, string key, int n, DateTime nowUtc, System.Random rng) { if (og == null || og.Missions == null || n <= 0) return; Roll(og, d, nowUtc, rng); Add(og, d, key, n); } /// 전투 이벤트 키(BattleEvents) → 그 키를 쓰는 카운터(s_key 또는 s_code_now 가 같은 것). public static void CountEvent(OutGameData og, SaveData d, string eventKey, int n, DateTime nowUtc, System.Random rng) { if (og == null || og.Missions == null || n <= 0) return; foreach (var c in og.Missions.counters) if (c.key == eventKey || c.codeNow == eventKey) Count(og, d, c.key, n, nowUtc, rng); } static void Add(OutGameData og, SaveData d, string key, int n) { var c = og.Missions.CounterOf(key); if (c == null) { Debug.LogWarning("[TKS] 임무 카운터 표에 없는 키: " + key); return; } var m = d.mission; if (c.count == MissionDb.State) return; // 세이브에서 다시 계산 if (c.count == MissionDb.Day) { if (Counts.Get(m.day.counts, key) == 0) Counts.Add(m.day.counts, key, 1); // 하루 1 return; } Counts.Add(m.totals, key, n); Counts.Add(m.day.counts, key, n); Counts.Add(m.week.counts, key, n); } /// 세이브에서 다시 계산하는 카운터 값(StateKeys). public static int StateValue(OutGameData og, SaveData d, string key) { int n = 0; switch (key) { case "stage_star": foreach (var s in d.stages) n += s.stars; return n; case "tower_floor": return d.arena != null ? d.arena.towerFloor : 0; case "scenario_clear": if (d.scenario == null) return 0; foreach (var e in d.scenario.episodes) { var row = ContentTables.Find("scenario_battles", "s_id", e.id); if (row != null && row.I("n_no") >= 1 && ((e.normal != null && e.normal.Length > 0 && e.normal[0]) || (e.hard != null && e.hard.Length > 0 && e.hard[0]))) n++; } return n; case "hero_own": foreach (var h in og.Heroes.heroes) if (!h.isSoldier && d.Owns(h.id)) n++; return n; } return 0; } /// 업적 값 = Add 누적 · State 지금 값. public static int Total(OutGameData og, SaveData d, string key) { var c = og.Missions.CounterOf(key); if (c == null) return 0; return c.count == MissionDb.State ? StateValue(og, d, key) : Counts.Get(d.mission.totals, key); } static int PeriodValue(OutGameData og, SaveData d, MissionPeriod p, string key) { var c = og.Missions.CounterOf(key); if (c == null) return 0; return c.count == MissionDb.State ? StateValue(og, d, key) : Counts.Get(p.counts, key); } // ---------- 초기화 ---------- /// /// 기간 맞춤 — 하루(주)가 바뀌었으면 지난 기간을 닫고(자동 더함 · 우편) 새 기간(칸 = 그 순간 잠김 판정)을 연다 · 새 하루 = 그날 첫 접속 카운터. /// 지난 하루를 먼저 닫는다(그날 daily_full 이 지난주 주간 카운터로 들어가게). 반환 = 바뀌었는가. /// public static bool Roll(OutGameData og, SaveData d, DateTime nowUtc, System.Random rng) { if (og == null || og.Missions == null || d == null) return false; var db = og.Missions; if (d.mission == null) d.mission = new MissionState(); if (d.mail == null) d.mail = new MailState(); var m = d.mission; bool changed = Seed(og, d); string dk = DayKey(db, nowUtc), wk = WeekKey(db, nowUtc); bool newDay = m.day.key != dk, newWeek = m.week.key != wk; if (newDay && m.day.key.Length > 0) Close(og, d, m.day, MissionDb.Daily, nowUtc); if (newWeek && m.week.key.Length > 0) Close(og, d, m.week, MissionDb.Weekly, nowUtc); if (newWeek) m.week = Open(og, d, MissionDb.Weekly, wk); if (newDay) { m.day = Open(og, d, MissionDb.Daily, dk); foreach (var k in LoginKeys) if (db.CounterOf(k) != null) Add(og, d, k, 1); } return changed || newDay || newWeek; } /// 기존 카운터(s_code_now = 키 하나)를 업적 누적으로 한 번 옮긴다(계정 생성부터 누적 · 요청서 §2-4). static bool Seed(OutGameData og, SaveData d) { var m = d.mission; if (m.seeded) return false; m.seeded = true; foreach (var c in og.Missions.counters) { if (c.count != MissionDb.Add || !Ident.IsMatch(c.codeNow ?? "")) continue; int old = Counts.Get(d.counters, c.codeNow); if (old > Counts.Get(m.totals, c.key)) Counts.Set(m.totals, c.key, old); } return true; } static MissionPeriod Open(OutGameData og, SaveData d, string kind, string key) { var p = new MissionPeriod { key = key }; foreach (var mm in og.Missions.Mains(kind)) p.slots.Add(mm.fallbackId != 0 && !ContentOpen(d, mm) ? mm.fallbackId : mm.id); return p; } static void Close(OutGameData og, SaveData d, MissionPeriod p, string kind, DateTime nowUtc) { var db = og.Missions; foreach (var id in p.slots) { var mm = db.Get(id); if (mm == null || p.claimed.Contains(id) || PeriodValue(og, d, p, mm.counter) < mm.goal) continue; p.claimed.Add(id); p.points = Mathf.Min(db.PointMax(kind), p.points + mm.point); } CheckFull(og, d, p, kind); var needs = new List(); var parts = new List(); foreach (var s in db.Steps(kind)) { if (p.points < s.need || p.boxes.Contains(s.step)) continue; p.boxes.Add(s.step); needs.Add(s.need.ToString(CultureInfo.InvariantCulture)); parts.Add(s.reward); } if (parts.Count == 0) return; var mail = d.mail; mail.seq++; mail.items.Add(new MailEntry { id = mail.seq, kind = kind == MissionDb.Daily ? MailDaily : MailWeekly, args = new List { p.key.TrimStart('W'), string.Join(";", needs.ToArray()) }, reward = Merge(parts), at = nowUtc.ToString("o", CultureInfo.InvariantCulture), }); } static void CheckFull(OutGameData og, SaveData d, MissionPeriod p, string kind) { if (p.full || p.points < og.Missions.PointMax(kind)) return; p.full = true; string key = kind == MissionDb.Daily ? "daily_full" : "weekly_full"; if (og.Missions.CounterOf(key) != null) Add(og, d, key, 1); } // ---------- 일일 · 주간 ---------- public static List Rows(OutGameData og, SaveData d, string kind) { var res = new List(); var p = Period(d, kind); foreach (var id in p.slots) { var mm = og.Missions.Get(id); if (mm == null) continue; int v = PeriodValue(og, d, p, mm.counter); res.Add(new MissionRow { m = mm, count = v, done = v >= mm.goal, claimed = p.claimed.Contains(id) }); } return res; } public static int Points(SaveData d, string kind) { return Period(d, kind).points; } public static bool BoxClaimed(SaveData d, string kind, int step) { return Period(d, kind).boxes.Contains(step); } /// 임무 받기 → 포인트(0 = 받을 수 없음). public static int Claim(OutGameData og, SaveData d, string kind, int id) { var p = Period(d, kind); var mm = og.Missions.Get(id); if (mm == null || !p.slots.Contains(id) || p.claimed.Contains(id) || PeriodValue(og, d, p, mm.counter) < mm.goal) return 0; p.claimed.Add(id); int before = p.points; p.points = Mathf.Min(og.Missions.PointMax(kind), p.points + mm.point); CheckFull(og, d, p, kind); return p.points - before; } /// 구간 상자 받기 → 보상 문자열(null = 받을 수 없음). public static string ClaimBox(OutGameData og, SaveData d, string kind, int step, System.Random rng) { var p = Period(d, kind); foreach (var s in og.Missions.Steps(kind)) { if (s.step != step) continue; if (p.points < s.need || p.boxes.Contains(step)) return null; p.boxes.Add(step); Grant(og, d, s.reward, rng); return s.reward; } return null; } /// 모두 받기 = 그 탭의 임무 포인트 + 닿은 구간 보상 · 반환 = 받은 구간 보상 목록(포인트 = out). public static List ClaimAll(OutGameData og, SaveData d, string kind, System.Random rng, out int points) { points = 0; foreach (var r in Rows(og, d, kind)) if (r.Claimable) points += Claim(og, d, kind, r.m.id); var got = new List(); foreach (var s in og.Missions.Steps(kind)) if (ClaimBox(og, d, kind, s.step, rng) != null) got.Add(s); return got; } /// 탭 빨간 점 = 「받기」가 뜬 임무 수(구간 상자 제외 · mission_config red_dot). public static int Badge(OutGameData og, SaveData d, string kind) { int n = 0; foreach (var r in Rows(og, d, kind)) if (r.Claimable) n++; return n; } // ---------- 업적 ---------- public static AchRow AchOf(OutGameData og, SaveData d, MissionDb.Achievement a) { return AchAt(og, d, a, Counts.Get(d.mission.achieve, a.id)); } /// 받은 단계 수 idx 일 때의 단계(지금 단계 = 받은 수 · 다음 단계 = 받은 수 + 1). public static AchRow AchAt(OutGameData og, SaveData d, MissionDb.Achievement a, int idx) { var r = new AchRow { a = a, step = idx + 1, value = Total(og, d, a.counter) }; int n = a.goals.Length; if (idx < n) { r.goal = a.goals[idx]; r.gem = a.gems[idx]; } else if (a.repeatAdd > 0 && n > 0) { r.repeat = true; r.goal = a.goals[n - 1] + a.repeatAdd * (idx - n + 1); r.gem = a.repeatGem; } else { r.allDone = true; r.step = n; r.goal = n > 0 ? a.goals[n - 1] : 0; } return r; } /// 업적 줄(종류마다 지금 단계 1줄) · 정렬 = 받기 → 진행 중(진행률 높은 순) → 모두 완료 · 같으면 n_order. public static List AchRows(OutGameData og, SaveData d, string category) { var res = new List(); foreach (var a in og.Missions.achievements) if (string.IsNullOrEmpty(category) || a.category == category) res.Add(AchOf(og, d, a)); res.Sort((x, y) => { int gx = x.Claimable ? 0 : x.allDone ? 2 : 1, gy = y.Claimable ? 0 : y.allDone ? 2 : 1; if (gx != gy) return gx.CompareTo(gy); if (gx == 1 && Math.Abs(x.Progress - y.Progress) > 1e-6f) return y.Progress.CompareTo(x.Progress); return x.a.order.CompareTo(y.a.order); }); return res; } /// 업적 한 단계 받기 → 보옥(0 = 받을 수 없음). public static int ClaimAch(OutGameData og, SaveData d, string id) { var a = og.Missions.Ach(id); if (a == null) return 0; var r = AchOf(og, d, a); if (!r.Claimable) return 0; Counts.Add(d.mission.achieve, id, 1); d.gem += r.gem; return r.gem; } /// 업적 모두 받기 = 받을 수 있는 단계를 연쇄로 끝까지(mission_config achieve_claim_all chain). public static List ClaimAllAch(OutGameData og, SaveData d) { var got = new List(); foreach (var a in og.Missions.achievements) { for (int guard = 0; guard < 10000; guard++) { var r = AchOf(og, d, a); if (!r.Claimable) break; ClaimAch(og, d, a.id); got.Add(new AchClaim { a = a, step = r.step, goal = r.goal, gem = r.gem }); } } return got; } /// 업적 탭 빨간 점 = 받기가 뜬 업적 줄 수(연쇄로 이어 받을 단계는 세지 않음). public static int AchBadge(OutGameData og, SaveData d) { int n = 0; foreach (var a in og.Missions.achievements) if (AchOf(og, d, a).Claimable) n++; return n; } /// 로비 「임무」 버튼 숫자 = 세 탭의 합. public static int LobbyBadge(OutGameData og, SaveData d) { if (og == null || og.Missions == null) return 0; return Badge(og, d, MissionDb.Daily) + Badge(og, d, MissionDb.Weekly) + AchBadge(og, d); } // ---------- 보상 · 우편 ---------- /// 「키:수;키:수」 지급 — gold · gem · skill_book · stamina · iron · blueprint · <상자>_chest. public static void Grant(OutGameData og, SaveData d, string reward, System.Random rng) { foreach (var kv in ContentTables.ParseMap(reward)) { int n = Mathf.RoundToInt(kv.Value); switch (kv.Key) { case "gold": d.gold += n; break; case "gem": d.gem += n; break; case "skill_book": d.inv.books.skill += n; break; case "stamina": d.stamina += n; break; case "iron": d.inv.iron += n; break; case "blueprint": d.inv.blueprint += n; break; default: 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(og, d, chest, rng ?? new System.Random()); } else Debug.LogWarning("[TKS] 임무 보상 낱말 모름: " + kv.Key); break; } } } /// 보상 여러 개를 낱말별로 합친다(표 순서 유지). public static string Merge(IList rewards) { var keys = new List(); var sums = new Dictionary(); foreach (var r in rewards) foreach (var kv in ContentTables.ParseMap(r)) { if (!sums.ContainsKey(kv.Key)) { keys.Add(kv.Key); sums[kv.Key] = 0f; } sums[kv.Key] += kv.Value; } var parts = new List(); foreach (var k in keys) parts.Add(k + ":" + Mathf.RoundToInt(sums[k]).ToString(CultureInfo.InvariantCulture)); return string.Join(";", parts.ToArray()); } /// 기기 우편 받기 → 받은 보상 목록(없으면 빈 목록). public static List ClaimMail(OutGameData og, SaveData d, IList ids, System.Random rng) { var got = new List(); if (d.mail == null) return got; for (int i = d.mail.items.Count - 1; i >= 0; i--) { var it = d.mail.items[i]; if (!ids.Contains(it.id)) continue; Grant(og, d, it.reward, rng); got.Insert(0, it.reward); d.mail.items.RemoveAt(i); } return got; } // ---------- 전투 결과 ---------- /// /// 전투 끝 카운터(요청서 §2-6) — 출정 승리 · 연무장 종류별 도전 · 투기장 승리 · 처치(쓰러진 적 = 아군이 쓰러뜨림 · 구출 대상·허수아비(연병장) 제외 · 연습 판 제외). /// kind = 연무장 종류(null = 출정) · supplyRefunded = 보급전 실패로 횟수를 돌려받음. /// public static void BattleEnd(OutGameData og, SaveData d, BattleManager bm, bool win, string kind, bool supplyRefunded, DateTime nowUtc, System.Random rng) { if (og == null || og.Missions == null || bm == null) return; var raid = bm.Mode != null ? bm.Mode.rules as RaidBattleRules : null; bool practice = raid != null && raid.Practice; if (string.IsNullOrEmpty(kind)) { if (win) Count(og, d, "stage_win", 1, nowUtc, rng); } else if (kind == SupplyRules.Kind) { if (!supplyRefunded) Count(og, d, "supply_play", 1, nowUtc, rng); } else if (kind == ArenaRules.Tower) Count(og, d, "tower_play", 1, nowUtc, rng); else if (kind == LeagueRules.Kind || kind == ArenaRules.Arena) { Count(og, d, "arena_play", 1, nowUtc, rng); if (win) Count(og, d, "arena_win", 1, nowUtc, rng); } else if ((kind == RaidRules.Kind || kind == ArenaRules.Raid) && !practice) Count(og, d, "raid_play", 1, nowUtc, rng); if (practice || (bm.Mode != null && bm.Mode.rules is DrillRules)) return; int all = 0, boss = 0; var byType = new Dictionary(); foreach (var u in bm.Units) { if (u == null || u.Faction != Faction.Enemy || u.IsAlive || u.Npc) continue; all++; if (u.IsBoss) boss++; int c; byType.TryGetValue(u.Type, out c); byType[u.Type] = c + 1; } Count(og, d, "kill_any", all, nowUtc, rng); Count(og, d, "boss_kill", boss, nowUtc, rng); foreach (var kv in byType) { var k = KillKey(kv.Key); if (k != null) Count(og, d, k, kv.Value, nowUtc, rng); } } static string KillKey(UnitType t) { switch (t) { case UnitType.Infantry: return "kill_inf"; case UnitType.Spear: return "kill_spear"; case UnitType.Cavalry: return "kill_cav"; case UnitType.Archer: return "kill_arc"; case UnitType.Strategist: return "kill_stg"; } return null; } } }