2026-11-19 13:37:08 +00:00
using System ;
using System.Collections.Generic ;
using System.Globalization ;
using UnityEngine ;
namespace TKS.OutGame
{
/// <summary>
/// 이벤트 규칙(PD 2026-11-19 「게임에 구현해」 · 시안 7장 · PD 결정 5건: ① 로비 이벤트 버튼 · 기기 세이브 모드만 ② 유료 팩 = 결제 준비 중 토스트 · 광고 = 시험 즉시 지급
/// ③ 값 = 예시 표 그대로 · 룰렛 판 = 흰 · 검은 돌 + 최종 보상만(등급 색 = 확률 정보 창) ④ 하루 = 게임 공통 0시 · 출석 = 접속한 날마다 1칸 · 일일 14일 = 다 받으면 다시 · 7일 미션 = 첫 접속일부터 하루 1일차 · 룰렛 = 표 날짜).
/// 값 = Resources/Event 표(EventData · C45) · 세이브 = SaveData.ev(EventState) · 미션 카운터 = OutGameSession 동작마다 Count(성공 경로 한 줄).
/// </summary>
public static class EventRules
{
// 미션 종류(코드가 세는 동작 · 표 event_kinds 가 글자 · 이동을 붙임)
public const string KLogin = "login" ;
public const string KStageClear = "stage_clear" ;
public const string KStageCleared = "stage_cleared" ;
public const string KStars = "stars" ;
public const string KStaminaUse = "stamina_use" ;
public const string KHeroLevelUp = "hero_levelup" ;
public const string KPromote = "promote" ;
public const string KEvolve = "evolve" ;
public const string KSkillUp = "skill_up" ;
public const string KHeroStar = "hero_star" ;
public const string KGacha = "gacha" ;
public const string KGoldUse = "gold_use" ;
public const string KTreasure = "treasure_enhance" ;
public const string KTrain = "train" ;
public const string KSupplyTry = "supply_try" ;
public const string KTowerFloor = "tower_floor" ;
public const string KArenaTry = "arena_try" ;
public const string KArenaWin = "arena_win" ;
public const string KRaidTry = "raid_try" ;
public const string KScenario = "scenario_clear" ;
public const string Att7 = "att7" ;
public const string Att14 = "att14" ;
/// <summary>받은 보상 한 줄(화면 표시 · 테스트).</summary>
public class Granted
{
public string id ;
public int n ;
/// <summary>조각으로 받았으면 그 영웅 id(영웅 보상이 이미 있음 · 무작위 영웅 조각) · 조각 수.</summary>
public string shardOf ;
public int shards ;
}
public static EventState St ( SaveData d )
{
if ( d . ev = = null ) d . ev = new EventState ( ) ;
d . ev . Sanitize ( ) ;
return d . ev ;
}
// ---------- 날짜 ----------
/// <summary>yyyyMMdd(게임 하루) → 그날 0시(UTC) · 못 읽으면 null.</summary>
public static DateTime ? DayStartUtc ( string dayKey )
{
DateTime t ;
if ( string . IsNullOrEmpty ( dayKey ) | | ! DateTime . TryParseExact ( dayKey , "yyyyMMdd" , CultureInfo . InvariantCulture , DateTimeStyles . None , out t ) ) return null ;
return DateTime . SpecifyKind ( t , DateTimeKind . Local ) . ToUniversalTime ( ) ;
}
/// <summary>첫 접속일부터 며칠째(첫날 = 1).</summary>
public static int DayIndex ( SaveData d , DateTime nowUtc )
{
var e = St ( d ) ;
var a = DayStartUtc ( e . firstDay ) ;
var b = DayStartUtc ( EconomyRules . DayKey ( nowUtc ) ) ;
if ( a = = null | | b = = null ) return 1 ;
return Mathf . Max ( 1 , ( int ) Math . Round ( ( b . Value - a . Value ) . TotalDays ) + 1 ) ;
}
static DateTime NextDayUtc ( DateTime nowUtc )
{
var s = DayStartUtc ( EconomyRules . DayKey ( nowUtc ) ) ;
return s . HasValue ? s . Value . AddDays ( 1 ) : nowUtc . AddDays ( 1 ) ;
}
/// <summary>첫 접속일 0시 + days(기간 끝 · UTC).</summary>
static DateTime WindowEnd ( SaveData d , string daysKey )
{
var s = DayStartUtc ( St ( d ) . firstDay ) ;
return ( s ? ? DateTime . UtcNow ) . AddDays ( EventData . CfgInt ( daysKey ) ) ;
}
// ---------- 접속(하루 한 번) ----------
/// <summary>
/// 접속 반영(세션 시작 · 이벤트 화면 열 때) — 첫 접속일 · 룰렛 회차 · 날이 바뀌었으면 출석 칸 +1(오픈 기념 = 기간 안 · 일일 = 다 받았으면 새 회차) ·
/// 오늘 카운터 · 일일 미션 · 광고 초기화 · 접속 카운터 +1. 바뀌었으면 true(호출 쪽이 저장).
/// </summary>
public static bool Tick ( SaveData d , DateTime nowUtc )
{
if ( ! EventData . Loaded ) return false ;
var e = St ( d ) ;
bool changed = false ;
string day = EconomyRules . DayKey ( nowUtc ) ;
if ( e . firstDay . Length = = 0 )
{
e . firstDay = day ;
changed = true ;
}
string rid = EventData . Cfg ( "roulette_start" ) ;
if ( e . rouId ! = rid )
{
e . ResetRoulette ( rid ) ;
changed = true ;
}
if ( e . lastDay = = day ) return changed ;
e . lastDay = day ;
if ( nowUtc < WindowEnd ( d , "att7_window_days" ) & & e . att7Days < EventData . CfgInt ( "att7_days" ) ) e . att7Days + + ;
int n14 = EventData . CfgInt ( "att14_days" ) ;
if ( e . att14Got > = n14 )
{
e . att14Days = 0 ;
e . att14Got = 0 ;
e . att14Cycle + + ;
}
if ( e . att14Days < n14 ) e . att14Days + + ;
e . dayCounts . Clear ( ) ;
e . questDayGot . Clear ( ) ;
e . adToday = 0 ;
AddCount ( d , KLogin , 1 , nowUtc ) ;
return true ;
}
// ---------- 카운터(미션 진행) ----------
/// <summary>동작 수 세기(OutGameSession 성공 경로) — 누적 · 룰렛 회차(기간 안) · 오늘. 날이 바뀌었으면 먼저 접속 반영.</summary>
public static void Count ( SaveData d , string kind , int n , DateTime nowUtc )
{
if ( n < = 0 | | d = = null | | ! EventData . Loaded ) return ;
var e = St ( d ) ;
if ( e . lastDay ! = EconomyRules . DayKey ( nowUtc ) ) Tick ( d , nowUtc ) ;
AddCount ( d , kind , n , nowUtc ) ;
}
/// <summary>값(arg)이 있는 동작(훈련장 던전) = 종류 전체 + 종류:값 둘 다.</summary>
public static void Count ( SaveData d , string kind , string arg , int n , DateTime nowUtc )
{
Count ( d , kind , n , nowUtc ) ;
if ( ! string . IsNullOrEmpty ( arg ) ) Count ( d , kind + ":" + arg , n , nowUtc ) ;
}
static void AddCount ( SaveData d , string key , int n , DateTime nowUtc )
{
var e = St ( d ) ;
Counts . Add ( e . counts , key , n ) ;
Counts . Add ( e . dayCounts , key , n ) ;
if ( RouletteOpen ( nowUtc ) ) Counts . Add ( e . rouCounts , key , n ) ;
}
/// <summary>규칙 호출 결과(null = 성공)를 그대로 돌려주며 성공이면 센다(Do(() => …) 안에서 · 저장 = Do 가).</summary>
public static string Counted ( string why , SaveData d , string kind , int n , DateTime nowUtc )
{
if ( why = = null ) Count ( d , kind , n , nowUtc ) ;
return why ;
}
/// <summary>미션 진행 — 상태형(탑 층 · 깬 스테이지 · 별 · 연의 전기 · n성 영웅) = 지금 세이브 값 · 세는 미션 = 카운터 목록에서.</summary>
public static int Progress ( SaveData d , string kind , string arg , List < CountEntry > counts )
{
var k = EventData . KindOf ( kind ) ;
if ( k ! = null & & k . state ) return State ( d , kind , arg ) ;
string key = string . IsNullOrEmpty ( arg ) ? kind : kind + ":" + arg ;
return Counts . Get ( counts , key ) ;
}
static int State ( SaveData d , string kind , string arg )
{
switch ( kind )
{
case KTowerFloor :
return d . arena ! = null ? d . arena . towerFloor : 0 ;
case KStageCleared :
{
int ch , st ;
if ( ! ArenaRules . ParseStageKey ( arg , out ch , out st ) ) return 0 ;
var s = d . Stage ( ch , st , false ) ;
return s ! = null & & s . clears > 0 ? 1 : 0 ;
}
case KStars :
{
int n = 0 ;
foreach ( var s in d . stages ) n + = s . stars ;
return n ;
}
case KScenario :
{
int n = 0 ;
if ( d . scenario ! = null & & d . scenario . episodes ! = null )
foreach ( var ep in d . scenario . episodes )
if ( ( ep . normal ! = null & & ep . normal . Length > 0 & & ep . normal [ 0 ] ) | | ( ep . hard ! = null & & ep . hard . Length > 0 & & ep . hard [ 0 ] ) ) n + + ;
return n ;
}
case KHeroStar :
{
int need ;
if ( ! int . TryParse ( arg , NumberStyles . Integer , CultureInfo . InvariantCulture , out need ) ) need = 1 ;
int n = 0 ;
foreach ( var h in d . heroes )
if ( h . star > = need ) n + + ;
return n ;
}
}
return 0 ;
}
// ---------- 지급 ----------
public static List < Granted > GrantAll ( OutGameData db , SaveData d , List < EventData . Reward > rewards , System . Random rng )
{
var res = new List < Granted > ( ) ;
if ( rewards ! = null )
foreach ( var r in rewards ) Grant ( db , d , r , rng , res ) ;
return res ;
}
public static void Grant ( OutGameData db , SaveData d , EventData . Reward r , System . Random rng , List < Granted > res )
{
var it = EventData . ItemOf ( r . id ) ;
if ( it = = null | | r . n < = 0 )
{
Debug . LogWarning ( "[TKS] 이벤트 보상 id 없음(event_items): " + r . id ) ;
return ;
}
var g = new Granted { id = r . id , n = r . n } ;
switch ( it . kind )
{
case "gold" : d . gold + = r . n ; break ;
case "gem" : d . gem + = r . n ; break ;
case "stamina" : d . stamina + = r . n ; break ;
case "iron" : d . inv . iron + = r . n ; break ;
case "blueprint" : d . inv . blueprint + = r . n ; break ;
case "tower_ticket" : d . arena . towerTickets + = r . n ; break ;
case "chest" : Counts . Add ( d . inv . chests , it . arg , r . n ) ; break ;
case "pouch" : St ( d ) . pouch + = r . n ; break ;
case "hero_shard" :
if ( d . heroes . Count > 0 )
{
var h = d . heroes [ rng ! = null ? rng . Next ( d . heroes . Count ) : 0 ] ;
h . shards + = r . n ;
g . shardOf = h . id ;
g . shards = r . n ;
}
break ;
case "hero" :
{
var h = db . Heroes . Get ( it . arg ) ;
if ( h = = null ) break ;
for ( int i = 0 ; i < r . n ; i + + )
{
if ( HeroRules . Grant ( db , d , h , HeroRules . GearSlotCount ( db ) ) )
{
var hs = d . Hero ( h . id ) ;
if ( hs ! = null & & it . star > hs . star ) hs . star = it . star ;
}
else if ( ! h . isSoldier & & d . Hero ( h . id ) ! = null )
{
2026-11-24 00:41:12 +00:00
int sh = GachaRules . DupShards ( db , h . rarity ) ; // 이미 있으면 등용 중복과 같은 조각
2026-11-19 13:37:08 +00:00
d . Hero ( h . id ) . shards + = sh ;
g . shardOf = h . id ;
g . shards + = sh ;
}
}
break ;
}
default :
Debug . LogWarning ( "[TKS] 이벤트 보상 종류 모름: " + it . kind ) ;
return ;
}
res . Add ( g ) ;
}
// ---------- 출석부 ----------
public static int AttDays ( string ev )
{
return EventData . Attend ( ev ) . Count ;
}
public static int AttOpenDays ( SaveData d , string ev )
{
var e = St ( d ) ;
return ev = = Att7 ? e . att7Days : e . att14Days ;
}
public static int AttGot ( SaveData d , string ev )
{
var e = St ( d ) ;
return ev = = Att7 ? e . att7Got : e . att14Got ;
}
/// <summary>오픈 기념 기간 안인가(일일 = 상시).</summary>
public static bool AttActive ( SaveData d , string ev , DateTime nowUtc )
{
return ev ! = Att7 | | nowUtc < WindowEnd ( d , "att7_window_days" ) ;
}
/// <summary>다음에 받을 칸(1~) · 받을 칸이 없으면 0.</summary>
public static int AttClaimable ( SaveData d , string ev , DateTime nowUtc )
{
if ( ! AttActive ( d , ev , nowUtc ) ) return 0 ;
int got = AttGot ( d , ev ) ;
return got < AttOpenDays ( d , ev ) & & got < AttDays ( ev ) ? got + 1 : 0 ;
}
public static List < Granted > ClaimAttend ( OutGameData db , SaveData d , string ev , DateTime nowUtc , System . Random rng )
{
int day = AttClaimable ( d , ev , nowUtc ) ;
if ( day < = 0 ) return null ;
var e = St ( d ) ;
if ( ev = = Att7 ) e . att7Got + + ;
else e . att14Got + + ;
return GrantAll ( db , d , EventData . Attend ( ev ) [ day - 1 ] . rewards , rng ) ;
}
/// <summary>남은 기간 — 오픈 기념 = 기간 끝까지 · 일일(상시) = 남은 칸을 매일 받았을 때 끝나는 때까지.</summary>
public static TimeSpan AttLeft ( SaveData d , string ev , DateTime nowUtc )
{
if ( ev = = Att7 ) return WindowEnd ( d , "att7_window_days" ) - nowUtc ;
int left = Mathf . Max ( 0 , AttDays ( ev ) - St ( d ) . att14Days ) ;
return NextDayUtc ( nowUtc ) . AddDays ( left ) - nowUtc ;
}
// ---------- 7일 특별 미션 ----------
public static bool MissionActive ( SaveData d , DateTime nowUtc )
{
return nowUtc < WindowEnd ( d , "mission7_window_days" ) ;
}
public static TimeSpan MissionLeft ( SaveData d , DateTime nowUtc )
{
return WindowEnd ( d , "mission7_window_days" ) - nowUtc ;
}
/// <summary>그 일차가 열렸나(첫 접속일부터 n일째).</summary>
public static bool DayOpen ( SaveData d , int day , DateTime nowUtc )
{
return day < = DayIndex ( d , nowUtc ) ;
}
public static int MissionProgress ( SaveData d , EventData . Mission m )
{
return Progress ( d , m . kind , m . arg , St ( d ) . counts ) ;
}
public static bool MissionGot ( SaveData d , EventData . Mission m )
{
return St ( d ) . m7Got . Contains ( m . Key ) ;
}
public static bool MissionReady ( SaveData d , EventData . Mission m , DateTime nowUtc )
{
return MissionActive ( d , nowUtc ) & & DayOpen ( d , m . day , nowUtc ) & & ! MissionGot ( d , m ) & & MissionProgress ( d , m ) > = m . target ;
}
public static List < Granted > ClaimMission ( OutGameData db , SaveData d , EventData . Mission m , DateTime nowUtc , System . Random rng )
{
if ( ! MissionReady ( d , m , nowUtc ) ) return null ;
St ( d ) . m7Got . Add ( m . Key ) ;
return GrantAll ( db , d , m . rewards , rng ) ;
}
/// <summary>미션 점수 = 받은 미션 점수 합.</summary>
public static int Points ( SaveData d )
{
var got = St ( d ) . m7Got ;
int n = 0 ;
foreach ( var m in EventData . Missions )
if ( got . Contains ( m . Key ) ) n + = m . point ;
return n ;
}
public static bool StepGot ( SaveData d , EventData . Step s )
{
return St ( d ) . m7Steps . Contains ( s . point ) ;
}
public static bool StepReady ( SaveData d , EventData . Step s )
{
return ! StepGot ( d , s ) & & Points ( d ) > = s . point ;
}
public static List < Granted > ClaimStep ( OutGameData db , SaveData d , EventData . Step s , System . Random rng )
{
if ( ! StepReady ( d , s ) ) return null ;
St ( d ) . m7Steps . Add ( s . point ) ;
return GrantAll ( db , d , s . rewards , rng ) ;
}
// ---------- 행운 룰렛 ----------
public static DateTime ? RouletteStart
{
get { return DayStartUtc ( EventData . Cfg ( "roulette_start" ) ) ; }
}
public static DateTime ? RouletteEnd
{
get { return DayStartUtc ( EventData . Cfg ( "roulette_end" ) ) ; }
}
public static bool RouletteOpen ( DateTime nowUtc )
{
var a = RouletteStart ;
var b = RouletteEnd ;
return a . HasValue & & b . HasValue & & nowUtc > = a . Value & & nowUtc < b . Value ;
}
public static TimeSpan RouletteLeft ( DateTime nowUtc )
{
var b = RouletteEnd ;
return b . HasValue ? b . Value - nowUtc : TimeSpan . Zero ;
}
public static int Cost ( int count )
{
return count > = EventData . CfgInt ( "roulette_count_10" ) ? EventData . CfgInt ( "roulette_cost_10" ) : EventData . CfgInt ( "roulette_cost_1" ) * Mathf . Max ( 1 , count ) ;
}
/// <summary>최종 보상까지 남은 뽑기 수.</summary>
public static int FinalLeft ( SaveData d )
{
return Mathf . Max ( 0 , EventData . CfgInt ( "roulette_final_every" ) - St ( d ) . sinceFinal ) ;
}
/// <summary>
/// 뽑기 count 회(복주머니 Cost) — 칸 = 확률 가중치 · 한정 = limited_every 회 안에 없으면 그 회에 반드시 · 최종 보상 = final_every 회마다 반드시(가중치 0).
/// 반환 = 멈춘 칸 번호들(실패 = null + why 글자 키).
/// </summary>
public static List < int > Draw ( OutGameData db , SaveData d , int count , DateTime nowUtc , System . Random rng , List < Granted > granted , out string why )
{
why = null ;
var e = St ( d ) ;
if ( ! RouletteOpen ( nowUtc ) )
{
why = "ev_rou_ended" ;
return null ;
}
int cost = Cost ( count ) ;
if ( e . pouch < cost )
{
why = "ev_rou_no_pouch" ;
return null ;
}
e . pouch - = cost ;
int finalEvery = EventData . CfgInt ( "roulette_final_every" ) , limitedEvery = EventData . CfgInt ( "roulette_limited_every" ) ;
var fin = EventData . FinalSlot ;
var res = new List < int > ( ) ;
for ( int i = 0 ; i < count ; i + + )
{
e . draws + + ;
e . sinceFinal + + ;
e . sinceLimited + + ;
EventData . Slot s ;
if ( fin ! = null & & finalEvery > 0 & & e . sinceFinal > = finalEvery )
{
s = fin ;
e . sinceFinal = 0 ;
}
else if ( limitedEvery > 0 & & e . sinceLimited > = limitedEvery ) s = Pick ( rng , true ) ;
else s = Pick ( rng , false ) ;
if ( s = = null ) continue ;
if ( s . tag = = EventData . TagLimited ) e . sinceLimited = 0 ;
e . cursor = s . slot ;
res . Add ( s . slot ) ;
Grant ( db , d , s . reward , rng , granted ) ;
}
return res ;
}
static EventData . Slot Pick ( System . Random rng , bool limitedOnly )
{
float sum = 0f ;
foreach ( var s in EventData . Slots )
if ( s . weight > 0f & & ( ! limitedOnly | | s . tag = = EventData . TagLimited ) ) sum + = s . weight ;
if ( sum < = 0f ) return null ;
float r = ( float ) ( rng ! = null ? rng . NextDouble ( ) : 0.5 ) * sum ;
EventData . Slot last = null ;
foreach ( var s in EventData . Slots )
{
if ( s . weight < = 0f | | ( limitedOnly & & s . tag ! = EventData . TagLimited ) ) continue ;
last = s ;
if ( r < s . weight ) return s ;
r - = s . weight ;
}
return last ;
}
public static bool CountGot ( SaveData d , EventData . Extra c )
{
return St ( d ) . countGot . Contains ( c . target ) ;
}
public static bool CountReady ( SaveData d , EventData . Extra c )
{
return ! CountGot ( d , c ) & & St ( d ) . draws > = c . target ;
}
public static List < Granted > ClaimCount ( OutGameData db , SaveData d , EventData . Extra c , System . Random rng )
{
if ( ! CountReady ( d , c ) ) return null ;
St ( d ) . countGot . Add ( c . target ) ;
return GrantAll ( db , d , c . rewards , rng ) ;
}
public static bool QuestDaily ( EventData . Extra q )
{
return q . reset = = "daily" ;
}
public static int QuestProgress ( SaveData d , EventData . Extra q )
{
var e = St ( d ) ;
return Progress ( d , q . sKind , q . arg , QuestDaily ( q ) ? e . dayCounts : e . rouCounts ) ;
}
public static bool QuestGot ( SaveData d , EventData . Extra q )
{
var e = St ( d ) ;
return QuestDaily ( q ) ? e . questDayGot . Contains ( q . order ) : e . questGot . Contains ( q . order ) ;
}
public static bool QuestReady ( SaveData d , EventData . Extra q , DateTime nowUtc )
{
return RouletteOpen ( nowUtc ) & & ! QuestGot ( d , q ) & & QuestProgress ( d , q ) > = q . target ;
}
public static List < Granted > ClaimQuest ( OutGameData db , SaveData d , EventData . Extra q , DateTime nowUtc , System . Random rng )
{
if ( ! QuestReady ( d , q , nowUtc ) ) return null ;
var e = St ( d ) ;
if ( QuestDaily ( q ) ) e . questDayGot . Add ( q . order ) ;
else e . questGot . Add ( q . order ) ;
return GrantAll ( db , d , q . rewards , rng ) ;
}
public static int PackBought ( SaveData d , EventData . Extra p )
{
return p . price < = 0 ? St ( d ) . adToday : Counts . Get ( St ( d ) . packBought , p . order . ToString ( CultureInfo . InvariantCulture ) ) ;
}
/// <summary>광고 칸(광고 SDK 미연동 = 시험 즉시 지급 · 하루 n_limit · PD 결정 ②) — 실패 = null + why 글자 키.</summary>
public static List < Granted > Ad ( OutGameData db , SaveData d , EventData . Extra p , DateTime nowUtc , System . Random rng , out string why )
{
why = null ;
if ( ! RouletteOpen ( nowUtc ) )
{
why = "ev_rou_ended" ;
return null ;
}
var e = St ( d ) ;
if ( e . lastDay ! = EconomyRules . DayKey ( nowUtc ) ) Tick ( d , nowUtc ) ;
if ( e . adToday > = p . limit )
{
why = "ev_ad_limit" ;
return null ;
}
e . adToday + + ;
return GrantAll ( db , d , p . rewards , rng ) ;
}
/// <summary>받을 것이 있는가(로비 이벤트 버튼 · 하단 이벤트 탭 붉은 점).</summary>
public static bool AnyAttend ( SaveData d , DateTime nowUtc )
{
return AttClaimable ( d , Att7 , nowUtc ) > 0 | | AttClaimable ( d , Att14 , nowUtc ) > 0 ;
}
public static bool AnyMission ( SaveData d , DateTime nowUtc )
{
foreach ( var m in EventData . Missions )
if ( MissionReady ( d , m , nowUtc ) ) return true ;
foreach ( var s in EventData . Steps )
if ( StepReady ( d , s ) ) return true ;
return false ;
}
public static bool AnyRoulette ( SaveData d , DateTime nowUtc )
{
foreach ( var c in EventData . Of ( "count" ) )
if ( CountReady ( d , c ) ) return true ;
return AnyQuest ( d , nowUtc ) ;
}
public static bool AnyQuest ( SaveData d , DateTime nowUtc )
{
foreach ( var q in EventData . Of ( "quest" ) )
if ( QuestReady ( d , q , nowUtc ) ) return true ;
return false ;
}
public static bool AnyClaimable ( SaveData d , DateTime nowUtc )
{
return EventData . Loaded & & ( AnyAttend ( d , nowUtc ) | | AnyMission ( d , nowUtc ) | | AnyRoulette ( d , nowUtc ) ) ;
}
}
}