import { assertBet, spin } from './SlotsMath'; import type { SpinResult, SymbolId } from './SlotsMath'; import type { GameRepository } from './GameRepository'; export interface GameState { version: 1; balance: number; bet: number; lastWin: number; board: SymbolId[][]; lastClaimDay: string | null; free: { remaining: number; awarded: number; total: number; bet: number } | null; pending: { id: number; result: SpinResult; free: boolean } | null; sequence: number; phase: 'idle' | 'spinning' | 'free-trigger' | 'free-ready' | 'free-result'; settings: { music: boolean; sound: boolean; vibration: boolean }; } const DAY_MS = 86_400_000; const DAILY_GIFT = 20_000; function copy(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } function addCoins(balance: number, amount: number): number { const total = balance + amount; if (!Number.isSafeInteger(total) || total < 0) throw new Error('Coin amount exceeds the supported range'); return total; } export function initialState(): GameState { return { version: 1, balance: 100_000, bet: 2000, lastWin: 0, board: [ ['cherry', 'watermelon', 'strawberry'], ['bell', 'wild', 'plum'], ['seven', 'blueberry', 'bar'], ['strawberry', 'plum', 'cherry'], ['bar', 'scatter', 'seven'], ], lastClaimDay: null, free: null, pending: null, sequence: 0, phase: 'idle', settings: { music: true, sound: true, vibration: true }, }; } /** Money is settled before animation. Restoring pending only replays its saved presentation. */ export class GameSession { private current: GameState; private changing = false; constructor( private readonly repository: GameRepository, private readonly random: () => number = Math.random, private readonly now: () => number = Date.now, ) { const saved = repository.load(); if (saved !== null) { this.current = copy(saved); } else { const first = initialState(); repository.save(first); this.current = copy(first); } } get state(): GameState { return copy(this.current); } setBet(bet: number): void { assertBet(bet); this.commit(next => { if (next.phase !== 'idle') throw new Error('Bet is locked during a round or free spins'); next.bet = bet; }); } beginSpin(): SpinResult { this.commit(next => { if (next.phase !== 'idle' && next.phase !== 'free-ready') throw new Error('A spin cannot start in this phase'); const free = next.phase === 'free-ready'; const bet = free ? next.free!.bet : next.bet; if (free && next.free!.remaining <= 0) throw new Error('No free spins remain'); if (!free && next.balance < bet) throw new Error('Insufficient coins'); if (!Number.isSafeInteger(next.sequence + 1)) throw new Error('Spin sequence exhausted'); const result = spin(bet, free, this.random); next.balance = addCoins(next.balance - (free ? 0 : bet), result.win); next.lastWin = result.win; next.board = result.board.map(column => column.slice()); next.sequence++; next.pending = { id: next.sequence, result, free }; next.phase = 'spinning'; if (free) { next.free!.remaining--; next.free!.total = addCoins(next.free!.total, result.win); } else if (result.awarded > 0) { next.free = { remaining: result.awarded, awarded: result.awarded, total: 0, bet }; } }); return copy(this.current.pending!.result); } completeSpin(): void { this.commit(next => { if (next.phase !== 'spinning' || next.pending === null) throw new Error('No spin is pending'); next.phase = next.pending.free ? (next.free!.remaining > 0 ? 'free-ready' : 'free-result') : (next.free === null ? 'idle' : 'free-trigger'); next.pending = null; }); } startFree(): void { this.commit(next => { if (next.phase !== 'free-trigger') throw new Error('No free-spin trigger is awaiting confirmation'); next.phase = 'free-ready'; }); } closeFreeResult(): void { this.commit(next => { if (next.phase !== 'free-result') throw new Error('No free-spin result is open'); next.free = null; next.phase = 'idle'; }); } canClaimDaily(): boolean { const day = this.utcDay(); return this.current.lastClaimDay === null || day > this.current.lastClaimDay; } claimDaily(): boolean { const day = this.utcDay(); if (this.current.lastClaimDay !== null && day <= this.current.lastClaimDay) return false; this.commit(next => { next.balance = addCoins(next.balance, DAILY_GIFT); next.lastClaimDay = day; }); return true; } nextResetMs(): number { const time = this.time(); return DAY_MS - ((time % DAY_MS + DAY_MS) % DAY_MS); } setPreference(key: keyof GameState['settings'], value: boolean): void { if (!['music', 'sound', 'vibration'].includes(key) || typeof value !== 'boolean') { throw new Error('Invalid preference'); } this.commit(next => { next.settings[key] = value; }); } private time(): number { const time = this.now(); if (typeof time !== 'number' || !Number.isFinite(time) || !Number.isFinite(new Date(time).getTime())) { throw new Error('Invalid current time'); } return time; } private utcDay(): string { const day = new Date(this.time()).toISOString().slice(0, 10); if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error('Current year is outside the supported range'); return day; } private commit(change: (next: GameState) => void): void { if (this.changing) throw new Error('A session operation is already in progress'); this.changing = true; try { const next = copy(this.current); change(next); this.repository.save(next); // Publish only after persistence and readback have both succeeded. this.current = next; } finally { this.changing = false; } } }