ThreeKingdomsSlingshot/Assets/Scripts/OutGame/EconomyRules.cs

636 lines
32 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 System.Globalization;
using UnityEngine;
namespace TKS.OutGame
{
/// <summary>스테이지 1회 결과(보상 · 별 · 조건) — 결과 화면·소탕 팝업 표시용.</summary>
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;
/// <summary>전리품 상자의 장비(상자 1개 = 장비 1개 · 2026-11-23) — 앞에서 fixedChests 개 = 보스 첫 클리어 확정 상자.</summary>
public List<string> gearIds = new List<string>();
public int fixedChests;
/// <summary>첫 장비(옛 한 개짜리 호출부 · 서버 응답 reward.gearId 용).</summary>
public string gearId
{
get { return gearIds.Count > 0 ? gearIds[0] : null; }
set
{
gearIds.Clear();
if (!string.IsNullOrEmpty(value)) gearIds.Add(value);
}
}
/// <summary>지역 특화(stage_drop s_region = gold · exp · gear) · 이번 판에 곱해진 지역 배율(결과 창 표시용).</summary>
public string region = "";
public float goldMult = 1f;
public float expMult = 1f;
/// <summary>보물 상자(stage_chest · stage_chest_pct · PD #1093 C) — 상자 등급 개발 반영 뒤 id.</summary>
public string chest;
/// <summary>하드 난이도 판(2026-11-24) · 보스 영웅 조각(그 보스 영웅 id · 수).</summary>
public bool hard;
public string shardHero;
public int shards;
public int stamina;
public int stars;
/// <summary>별 조건 ① 클리어 ② 아군 전원 생존 ③ star_turns 턴 이내.</summary>
public bool[] conds = new bool[3];
public int starTurns;
public int turns;
public int bestStars;
public List<string> expTo = new List<string>();
}
/// <summary>출전할 때 미리 굴린 전리품(2026-11-23 스테이지 보상 드랍) — 상자 1개 = 장비 1개 · 앞의 fixedChests 개 = 보스 첫 클리어 확정 상자.</summary>
public class StageLoot
{
public int chapter;
public int stage;
public bool sweep;
public bool hard;
public List<string> gearIds = new List<string>();
public int fixedChests;
}
/// <summary>군량(§2) · 일일 횟수 · 스테이지 보상(§6) · 소탕 · 골드 장비 상점(S15). 수치 = economy.csv · stage_rewards.csv · gear_items.csv.</summary>
public static class EconomyRules
{
// ---------- 일일 ----------
public static string DayKey(DateTime nowUtc)
{
return nowUtc.ToLocalTime().ToString("yyyyMMdd", CultureInfo.InvariantCulture);
}
/// <summary>날짜가 바뀌었으면 광고·보옥 구매 횟수를 초기화.</summary>
public static void RollDaily(SaveData d, DateTime nowUtc)
{
var day = DayKey(nowUtc);
if (d.adsUsed.day == day) return;
d.adsUsed = new AdsUsed { day = day };
}
/// <summary>다음 날 0시(현지)까지 남은 시간.</summary>
public static TimeSpan UntilNextDay(DateTime nowUtc)
{
var local = nowUtc.ToLocalTime();
return local.Date.AddDays(1) - local;
}
// ---------- 군량 ----------
/// <summary>군량 최대 = stamina_max + 농업 「군량 상한」(PD #1093 C) · stamina_max_limit 를 넘지 않는다.</summary>
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;
}
/// <summary>군량 1 회복 초 = stamina_regen_sec − 농업 「군량 회복」(최소 1).</summary>
public static int RegenSec(OutGameData db, SaveData d)
{
return Mathf.Max(1, db.Economy.StaminaRegenSec - Mathf.RoundToInt(DevRules.Mod(db, d, DevRules.FoodRegen)));
}
/// <summary>회복 계산(오프라인 포함): 최대 미만이면 stamina_regen_sec 마다 1 · 최대 이상(구매·광고로 넘침)이면 멈추고 기준 시각만 당긴다.</summary>
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));
}
}
/// <summary>다음 1 회복까지 초(최대 이상 = 0).</summary>
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;
}
/// <summary>입장 군량 = 표 비용 − 농업 「군량 비용 할인」(누적 값의 정수 부분 · 최소 1 · PD 확인 대상).</summary>
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));
}
/// <summary>입장 군량(hard = 하드 난이도 · hard_mode n_stamina · 보스 n_stamina_boss) − 농업 「군량 비용 할인」.</summary>
public static int StageCost(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool hard)
{
var h = hard ? HardRow(db, s.chapter) : null;
if (h == null) return StageCost(db, d, s);
return Mathf.Max(1, (s.kind == StageKind.Boss ? h.staminaBoss : h.stamina) - Mathf.FloorToInt(DevRules.Mod(db, d, DevRules.FoodCost) + 1e-4f));
}
// ---------- 출정 하드 난이도(hard_mode · PD 2026-11-24 ② ⑧) ----------
public static GoodsDb.HardMode HardRow(OutGameData db, int chapter)
{
return db.Goods != null ? db.Goods.HardFor(chapter) : null;
}
/// <summary>그 장의 하드 난이도가 열렸는가 = 그 장 일반 난이도 스테이지(stage_drop 줄)를 모두 클리어.</summary>
public static bool HardOpen(OutGameData db, SaveData d, int chapter)
{
if (HardRow(db, chapter) == null || db.Gear == null) return false;
int n = 0;
foreach (var s in db.Gear.stageDrops)
{
if (s.chapter != chapter) continue;
n++;
var st = d.Stage(s.chapter, s.stage, false);
if (st == null || st.clears <= 0) return false;
}
return n > 0;
}
static string HardKey(BalanceConfig.StageDef s)
{
return s.chapter.ToString(CultureInfo.InvariantCulture) + "-" + s.stage.ToString(CultureInfo.InvariantCulture);
}
static void RollHardDaily(SaveData d, DateTime nowUtc)
{
var day = DayKey(nowUtc);
if (d.hardDaily == null || d.hardDaily.day != day) d.hardDaily = new HardDaily { day = day };
}
/// <summary>오늘 그 스테이지 하드를 클리어한 수(소탕 포함 · 패배는 세지 않음).</summary>
public static int HardUsed(SaveData d, BalanceConfig.StageDef s, DateTime nowUtc)
{
RollHardDaily(d, nowUtc);
return Counts.Get(d.hardDaily.counts, HardKey(s));
}
public static int HardLeft(OutGameData db, SaveData d, BalanceConfig.StageDef s, DateTime nowUtc)
{
var h = HardRow(db, s.chapter);
return h == null ? 0 : Mathf.Max(0, h.dailyPerStage - HardUsed(d, s, nowUtc));
}
/// <summary>하드 입장(또는 소탕)을 막는 까닭(null = 가능) — 하드 줄 없음 · 장 미개방 · 오늘 횟수.</summary>
public static string HardBlock(OutGameData db, SaveData d, BalanceConfig.StageDef s, DateTime nowUtc)
{
var h = HardRow(db, s.chapter);
if (h == null) return "하드 난이도가 없는 스테이지입니다";
if (!HardOpen(db, d, s.chapter) && !TestOptions.UnlockAllStages) return s.chapter + "장 일반 난이도를 모두 클리어하면 열립니다";
if (HardLeft(db, d, s, nowUtc) <= 0) return "오늘 하드 클리어 " + h.dailyPerStage + "회 완료(매일 초기화)";
return null;
}
/// <summary>하드 클리어 1회 셈(승리 · 소탕 때 · PD 2026-11-24 「클리어 시에만 차감」).</summary>
public static void CountHard(SaveData d, BalanceConfig.StageDef s, DateTime nowUtc)
{
RollHardDaily(d, nowUtc);
Counts.Add(d.hardDaily.counts, HardKey(s), 1);
}
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);
}
/// <summary>보옥 → 군량 gem_stamina_amount(gem_stamina_daily 회/일 · 값 = 오늘 몇 번째인지에 따라 gem_stamina_cost 목록 · 살수록 비싸짐). null = 성공.</summary>
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 + "회를 모두 썼습니다";
int cost = e.GemStaminaCostAt(d.adsUsed.gemStamina);
if (d.gem < cost) return "보옥 부족 " + d.gem + " / " + cost;
d.gem -= cost;
d.adsUsed.gemStamina++;
AddStamina(db, d, e.GemStaminaAmount, nowUtc);
return null;
}
/// <summary>광고 보상 군량 +ad_stamina (ad_stamina_daily 회/일) — 광고 SDK 미연동 스텁 = 즉시 지급.</summary>
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) ----------
/// <summary>
/// 골드 = (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(표 0) ·
/// 장비 = 전리품 상자(loot = 출전 때 미리 굴린 것 · 없거나 다른 스테이지 것이면 여기서 굴림 = 소탕) ·
/// 별 = 클리어 · 전원 생존 · star_turns 턴 이내. 소탕 = 반복 보상(별 조건 없음).
/// </summary>
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, bool hard = false)
{
var e = db.Economy;
var row = db.Rewards.For(s.chapter);
var hm = hard ? HardRow(db, s.chapter) : null;
hard = hm != null;
var st = d.Stage(s.chapter, s.stage, false, hard);
var sd = StageDropOf(db, s);
var r = new StageReward
{
win = win, sweep = sweep, hard = hard, 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, hard);
r.gem = hard ? 0 : r.first ? row.gemFirst + (r.boss ? row.gemBoss : 0) : 0; // 표 값 0(PD 2026-11-24 ⑦) · 내정 「첫 클리어 보옥」 · 「보옥 보너스」 = 탑 층 첫 클리어 보옥으로 옮김
if (loot == null || loot.chapter != s.chapter || loot.stage != s.stage || loot.sweep != sweep || loot.hard != hard) loot = RollLoot(db, d, s, sweep, rng, hard);
r.gearIds.AddRange(loot.gearIds);
r.fixedChests = loot.fixedChests;
// 보물 상자 = 판당 stage_chest_pct · 등급 = chest_drop(출정 · 장 구간) 가중치 → 내정 「상자 등급」(PD 2026-11-24 ⑤)
if (hard)
{
// 하드 = 보물 상자 f_chest_pct % · 등급 = chest_drop 「출정 하드」 줄 · 보스 = 그 보스 영웅 조각 1개(f_boss_shard_pct % · stage_drop l_hard_shard_hero · 비면 없음)
if (db.Chests != null && rng.NextDouble() * 100.0 < hm.chestPct) r.chest = GoodsRules.ChestGrade(db, d, GoodsDb.SourceHard, s.chapter, e.StageChest, rng);
var sdh = StageDropOf(db, s);
if (r.boss && sdh != null && sdh.hardShardHeroes.Length > 0 && rng.NextDouble() * 100.0 < hm.bossShardPct)
{
r.shardHero = sdh.hardShardHeroes[rng.Next(sdh.hardShardHeroes.Length)];
r.shards = 1;
}
}
else if (db.Chests != null && rng.NextDouble() < e.StageChestPct) r.chest = GoodsRules.ChestGrade(db, d, GoodsDb.SourceStage, s.chapter, 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;
}
/// <summary>지역 특화 이름(stage_drop s_region) — 골드 지역 · 경험치 지역 · 장비 지역 · 없으면 빈 글자.</summary>
public static string RegionKo(string region)
{
return region == GearDb.RegionGold ? "골드 지역" : region == GearDb.RegionExp ? "경험치 지역" : region == GearDb.RegionGear ? "장비 지역" : "";
}
/// <summary>지역 특화 한 줄(스테이지 정보 창 · 결과 창) — 「골드 지역 · 골드 ×1.5」 처럼 그 스테이지 배율을 붙인다(배율 1 = 이름만).</summary>
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;
}
/// <summary>그 스테이지의 드랍 줄(stage_drop · 지역 특화 · 배율 · 지정 장비 · 없으면 null).</summary>
public static GearDb.StageDrop StageDropOf(OutGameData db, BalanceConfig.StageDef s)
{
return db.Gear != null ? db.Gear.FocusFor(s.chapter, s.stage) : null;
}
/// <summary>그 스테이지 1판의 골드 · 경험(영웅 1명) 총량 — 첫 클리어 · 반복 배율 · 지역 배율 · 개발 효과 포함(적 처치 몫을 다 더한 값).</summary>
public static void StageGoldExp(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool first, out int gold, out int exp)
{
StageGoldExp(db, d, s, first, out gold, out exp, false);
}
/// <summary>hard = 하드 난이도 — 같은 스테이지 일반 난이도 값 × hard_mode f_gold_exp_mult.</summary>
public static void StageGoldExp(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool first, out int gold, out int exp, bool hard)
{
gold = 0;
exp = 0;
var hm = hard ? HardRow(db, s.chapter) : null;
float hmult = hm != null ? hm.goldExpMult : 1f;
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) * hmult);
exp = Mathf.RoundToInt(row.expBase * (first ? 1f : e.RepeatRewardMult) * (sd != null ? sd.expMult : 1f) * DevRules.Mult(db, d, DevRules.ExpGain) * hmult);
}
/// <summary>그 스테이지 1판의 상자 기대 개수 = gear_drop_pct(장) × f_gear_mult(스테이지 종류 × 지역) + 개발 「장비 드랍」(%p ÷ 100).</summary>
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);
}
/// <summary>한 판에 상자가 1개 이상 나올 확률(굴림 chest_rolls 회 · 1회 확률 = 기대 개수 ÷ 굴림 수).</summary>
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);
}
/// <summary>
/// 전리품 굴림(출전 때 1번 · 소탕은 그 자리에서) — ① 보스 첫 클리어 = 확정 상자 boss_first_chest 개(그 장 가중치가 가장 큰 등급 · 지정 장비)
/// ② 굴림 chest_rolls 회(1회 확률 = 상자 기대 개수 ÷ 굴림 수 · 최대 1) → 상자마다 RollGear.
/// </summary>
public static StageLoot RollLoot(OutGameData db, SaveData d, BalanceConfig.StageDef s, bool sweep, System.Random rng, bool hard = false)
{
var hm = hard ? HardRow(db, s.chapter) : null;
hard = hm != null;
var loot = new StageLoot { chapter = s.chapter, stage = s.stage, sweep = sweep, hard = hard };
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, hard);
bool first = !sweep && (st == null || st.clears == 0);
if (hard)
{
// 하드 = 지정 장비(한 병종 부위 2개) 가운데 1개 확정 · 등급 = hard_mode 줄 → 그 뒤 일반 난이도와 같은 상자 굴림
var id = RollGear(db, s.chapter, s.stage, rng, true, hm);
if (id != null)
{
loot.gearIds.Add(id);
loot.fixedChests++;
}
}
else 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, false, hm);
if (id != null) loot.gearIds.Add(id);
}
return loot;
}
/// <summary>스테이지 정보 창 드랍 줄 — 그 장 드랍 등급 이름(gear_drop_chapters · 「고급 · 희귀」) · 가장 높은 등급(칸 색).</summary>
public static string DropGradesText(OutGameData db, int chapter, out string top, bool hard = false)
{
top = "white";
var row = db.Gear != null ? db.Gear.DropFor(chapter) : null;
var hm = hard ? HardRow(db, chapter) : null;
var gradeList = hm != null ? hm.grades : row != null ? row.grades : null;
if (gradeList == null) return "";
var names = new List<string>();
int best = 0;
foreach (var g in gradeList)
{
names.Add(UiKit.GearGradeKo(g));
int o = db.Gear.OrderOf(g);
if (o > best)
{
best = o;
top = g;
}
}
return string.Join("·", names.ToArray());
}
/// <summary>그 스테이지의 지정 장비(한 병종의 부위 2개 · gear_kinds · 없으면 빈 목록).</summary>
public static List<GearDb.Kind> FocusKinds(OutGameData db, int chapter, int stage)
{
var res = new List<GearDb.Kind>();
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;
}
/// <summary>지정 장비 첫 번째(옛 호출부용 · 없으면 null).</summary>
public static GearDb.Kind FocusKind(OutGameData db, int chapter, int stage)
{
var ks = FocusKinds(db, chapter, stage);
return ks.Count > 0 ? ks[0] : null;
}
/// <summary>
/// 상자 1개의 장비(2026-11-23 스테이지 보상 드랍 §2-1) — ① 등급 = gear_drop_chapters(그 장) 가중치(확정 상자 = 가중치가 가장 큰 등급)
/// ② focus_pct % 로 그 스테이지 지정 장비(지정 병종의 부위 2개 중 하나 · 반반 · 확정 상자 = 항상) ③ 나머지 = 그 등급 장비 전부 중 균등(지정 포함 · 제한 아님).
/// </summary>
public static string RollGear(OutGameData db, int chapter, int stage, System.Random rng, bool fixedChest = false, GoodsDb.HardMode hard = null)
{
var g = db.Gear;
var row = g.DropFor(chapter);
// 등급 표 = 일반(gear_drop_chapters) · 하드(hard_mode 줄 — 확정 장비도 가중치로 굴린다)
string[] grades = hard != null ? hard.grades : row != null ? row.grades : null;
float[] weights = hard != null ? hard.weights : row != null ? row.weights : null;
if (grades == null || grades.Length == 0) return null;
string grade = grades[grades.Length - 1];
if (fixedChest && hard == null)
{
float best = -1f;
for (int i = 0; i < grades.Length && i < weights.Length; i++)
if (weights[i] > best)
{
best = weights[i];
grade = grades[i];
}
}
else
{
float sum = 0f;
foreach (var w in weights) sum += w;
float at = (float)(rng.NextDouble() * sum);
for (int i = 0; i < grades.Length && i < weights.Length; i++)
{
if (at < weights[i])
{
grade = grades[i];
break;
}
at -= 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<string>();
foreach (var it in g.items)
if (it.grade == grade) pool.Add(it.id);
return pool.Count > 0 ? pool[rng.Next(pool.Count)] : null;
}
/// <summary>적 1기의 처치 몫 가중치(골드 · 경험치 총량을 나누는 비율 · drop_rules kill_share_w_*) — 보스 · 무장 · 병사.</summary>
public static float KillShare(OutGameData db, bool boss, bool general)
{
var ru = db.Gear.rules;
return boss ? ru.shareBoss : general ? ru.shareGeneral : ru.shareSoldier;
}
/// <summary>상자를 든 적을 고를 가중치(drop_rules chest_carrier_w_*).</summary>
public static float CarrierWeight(OutGameData db, bool boss, bool general)
{
var ru = db.Gear.rules;
return boss ? ru.carrierBoss : general ? ru.carrierGeneral : ru.carrierSoldier;
}
/// <summary>보상을 세이브에 넣는다(재화 · 경험 = expTo 전원 · 장비 · 스테이지 기록 · 클리어 최고 챕터).</summary>
public static void Apply(SaveData d, StageReward r, IEnumerable<string> 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);
if (r.shards > 0) GoodsRules.AddHeroShards(d, r.shardHero, r.shards); // 하드 보스 조각(보유 = 그 영웅 · 미보유 = 영입 조각)
var st = d.Stage(r.chapter, r.stage, true, r.hard); // 별 · 첫 클리어 기록은 일반과 따로
st.clears++;
st.stars = Mathf.Max(st.stars, r.stars);
r.bestStars = st.stars;
if (!r.hard) d.chapterMax = Mathf.Max(d.chapterMax, r.chapter);
}
public static int StarsOf(SaveData d, BalanceConfig.StageDef s, bool hard = false)
{
var st = d.Stage(s.chapter, s.stage, false, hard);
return st != null ? st.stars : 0;
}
/// <summary>소탕 = 별 3 스테이지만(최대 별 = 조건 수) · 하드 = 하드 기록의 별.</summary>
public static bool CanSweep(SaveData d, BalanceConfig.StageDef s, bool hard = false)
{
return StarsOf(d, s, hard) >= 3;
}
// ---------- 골드 장비 상점 ----------
/// <summary>날짜가 바뀌었거나 비었으면 shop_grades 장비 shop_slots 종(겹침 없음 · 가격 = sell_gold × shop_price_mult)을 새로 깐다.</summary>
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<string>(e.ShopGrades);
var pool = new List<GearDb.Item>();
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 });
}
}
/// <summary>보옥 shop_refresh_gem 으로 다시 깔기. null = 성공.</summary>
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;
}
/// <summary>오늘 남은 무료 새로고침(상업 「시장 개설」 Lv · 상점 refreshes = 그날 새로고침 수).</summary>
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;
}
}
}