ThreeKingdomsSlingshot/Assets/Scripts/OutGame/Supply/SupplyRules.cs

433 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using UnityEngine;
namespace TKS.OutGame
{
/// <summary>보급전 세이브(기기 세이브 모드 · 서버 모드는 서버 응답 · GET /tks/modes/supply 로 덮는다).</summary>
[Serializable]
public class SupplyBest
{
public string id = "";
public int tier;
[Tooltip("등급 낱말(S · A …) 또는 별 수(병법 훈련)")]
public string grade = "";
}
[Serializable]
public class SupplyState
{
public List<SupplyBest> best = new List<SupplyBest>();
[Tooltip("그날(서버 날짜 · 기기 = 현지 날짜) 끝낸 던전 · 그날 보너스를 받았는가")]
public string doneDay = "";
public List<string> doneIds = new List<string>();
public bool doneBonus;
[Tooltip("주간 도장(주 키 · 「일일 보급 완료」 날 · 받음)")]
public string stampWeek = "";
public List<string> stampDays = new List<string>();
public bool stampClaimed;
[Tooltip("서버 모드 = 서버가 알려 준 단계 해금(그 밖 = 기기가 스테이지 기록으로 판정)")]
public List<int> serverOpenTiers = new List<int>();
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 });
}
}
/// <summary>보급전 한 판(또는 소탕)의 결과 — 결과 화면 · 서버 응답 공용.</summary>
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, awakenStone;
/// <summary>황건적 소탕의 보물 상자(받은 상자 id · 2026-11-24).</summary>
public List<string> chestIds = new List<string>();
public List<string> gearIds = new List<string>();
public string shardHero;
public int shards;
}
/// <summary>
/// 보급전 규칙(기기 세이브 모드 · 서버 규칙 `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:&lt;던전&gt;」 「supplyAd:&lt;던전&gt;」.
/// </summary>
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;
}
/// <summary>테스트 · 캡처 전용 = 던전 해금 스테이지를 잠깐 바꾼 것처럼(던전 id → 스테이지 키 · 화면이 표를 다시 읽어도 유지 · 게임 코드는 쓰지 않음 · 쓴 쪽이 비운다).</summary>
public static readonly Dictionary<string, string> UnlockOverride = new Dictionary<string, string>();
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStatics()
{
UnlockOverride.Clear();
}
/// <summary>던전 해금 스테이지 = 표 supply_dungeons.s_unlock_stage(PD 2026-11-19 「각 메뉴별로 각각 개방 조건」) · 비면 모드 기본 supply.unlock_stage.</summary>
public static string UnlockStage(SupplyData.Dungeon dg)
{
string v;
if (dg != null && UnlockOverride.TryGetValue(dg.id, out v) && !string.IsNullOrEmpty(v)) return v;
if (dg != null && !string.IsNullOrEmpty(dg.unlockStage)) return dg.unlockStage;
return ContentTables.Str(SupplyData.Mode, "unlock_stage");
}
/// <summary>던전 해금(그 던전 해금 스테이지 클리어) — 보급전 페이지(연무장 → 훈련장)는 늘 들어가고 던전마다 잠긴다.</summary>
public static bool DungeonUnlocked(SaveData d, SupplyData.Dungeon dg)
{
if (dg == null) return false;
if (d.supply.serverView) return true; // 서버 모드 = 서버가 판정(잠겼으면 입장 응답이 거절 · 서버 규칙은 모드 해금 하나 — 던전별 값은 서버에 아직 없음)
if (TestOptions.UnlockAllStages && !SaveStore.MemoryOnly) return true; // 플레이 테스트 「전 스테이지 열기」 = 컨텐츠 해금도 무시(연의 전기 ScenarioModeRules 와 같음 · 메모리 세이브 테스트 · 캡처는 원래 판정 · PD 2026-11-18 「맹장 토벌전 · 투기장이 제대로 안 보임」)
return Cleared(d, UnlockStage(dg));
}
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));
}
/// <summary>입장(또는 소탕) 가능 여부 — null = 가능 · 글 = 까닭.</summary>
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 (!DungeonUnlocked(d, dg)) return UnlockStage(dg) + " 클리어 뒤 열림";
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;
}
/// <summary>입장 = 횟수 1 사용(실패하면 Result 가 돌려준다).</summary>
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;
}
/// <summary>광고 추가 입장(던전마다 하루 supply.ad_entries_per_day).</summary>
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;
}
// ---------- 결과 · 소탕 ----------
/// <summary>전투 끝(기기 세이브 모드) — 판정 · 보상 · 최고 판정 · 그날 완료 · 주간 도장 · 실패 시 횟수 반환.</summary>
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;
}
/// <summary>소탕 — 그 단계 최고 판정이 소탕 등급(별) 이상 · 입장 횟수 1 · 전투 없이 그 판정의 보상.</summary>
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<int, float, int> 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("chest"))
{
// 보물 상자 = 판정 등급별 개수(bandit_chest_count) × 내정 「던전 장비」(소수 = 확률로 1개 더) · 등급 = chest_drop(황건적 소탕 · 단계 구간) → 내정 「상자 등급」
float exact = BanditChests(r.grade) * DevRules.Mult(db, d, DevRules.DungeonGear);
int whole = Mathf.FloorToInt(exact + 1e-4f);
int count = whole + (rng.NextDouble() < exact - whole ? 1 : 0);
for (int k = 0; k < count; k++)
{
var id = GoodsRules.ChestGrade(db, d, GoodsDb.SourceBandit, t.tier, db.Economy.StageChest, rng);
if (id == null) continue;
Counts.Add(d.inv.chests, id, 1);
r.chestIds.Add(id);
}
}
if (dg.rewardKinds.Contains("awaken_stone") && db.Awaken != null)
{
r.awakenStone = scaled(t.awakenStone, 1f); // ★3 = 표 값 · ★마다 3분의 1(supply.tactics_star_pct)
AwakenRules.AddGoods(d, db.Awaken.StoneKey, r.awakenStone);
}
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);
}
/// <summary>그날 열린 곳을 모두 끝냈으면 보너스(supply.daily_all_bonus · 한 번) · 그날을 주간 도장에 찍고 weekly_stamp_need 날이면 주간 보너스(한 번).</summary>
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<string>();
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);
}
}
/// <summary>「silver_chest:1;gem:20」 꾸러미 지급(상자 = 「&lt;상자&gt;_chest」 · 재화 = gem · gold).</summary>
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);
}
}
/// <summary>같은 id 를 세어 「id → 수」(나온 순서).</summary>
static List<KeyValuePair<string, int>> CountIds(List<string> ids)
{
var res = new List<KeyValuePair<string, int>>();
foreach (var id in ids)
{
int at = res.FindIndex(k => k.Key == id);
if (at < 0) res.Add(new KeyValuePair<string, int>(id, 1));
else res[at] = new KeyValuePair<string, int>(id, res[at].Value + 1);
}
return res;
}
/// <summary>황건적 소탕의 판정 등급별 상자 수(supply.bandit_chest_count 「S:2;A:2;B:1;C:1」 · 줄이 없거나 등급이 없으면 0).</summary>
public static float BanditChests(string grade)
{
if (!ContentTables.Has(SupplyData.Mode, "bandit_chest_count")) return 0f;
float n;
ContentTables.Map(SupplyData.Mode, "bandit_chest_count").TryGetValue(grade ?? "", out n);
return n;
}
// ---------- 세이브 이전 ----------
/// <summary>
/// 옛 일일 던전 id → 새 id(existing_tables_patch.csv 의 dungeons 줄 「id &lt;새 id&gt; · …」 · forge → bandit · shrine → tactics) — 오늘 입장 횟수 기록을 새 id 의 보급전 키로 옮긴다.
/// </summary>
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<string> 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.awakenStone > 0) m.lines.Add(GoodsRules.NameOf(db, db.Awaken.StoneKey) + " +" + r.awakenStone);
foreach (var kv in CountIds(r.chestIds))
{
var c = db.Chests.Get(kv.Key);
m.lines.Add((c != null ? c.nameKo : kv.Key) + " ×" + kv.Value);
}
foreach (var gid in r.gearIds)
{
var g = db.Gear.Get(gid);
m.lines.Add("장비 " + (g != null ? g.nameKo + " (" + UiKit.GearGradeKo(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;
}
}
}