增加游戏玩法界面和各个弹窗初版

This commit is contained in:
zpx committed 2026-11-20 18:51:48 +08:00
1 parent e84e14783e
commit eb48d8e845
211 files changed
+59920 -21

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
/** 队列只控制未来普通局;STOP 不回滚已经提交的当前局。 / The queue controls future paid rounds; stopping never rolls back the committed spin. */
export class AutoSpinQueue {
active = false;
remaining = 0;
start(count: number): void {
if (![10, 25, 50, 100].includes(count) || this.active) throw new Error('Invalid automatic spin request');
this.remaining = count; this.active = true;
}
consume(): void {
if (!this.active || this.remaining <= 0) throw new Error('No automatic spin remains');
this.remaining--;
}
stop(): void { this.active = false; this.remaining = 0; }
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "07dd84c7-1fee-42d0-90da-228570b1a442",
"files": [],
"subMetas": {},
"userData": {}
}
+178
View File
@@ -0,0 +1,178 @@
import { assertBet, assertBoard, evaluate } from './SlotsMath';
import type { SpinResult } from './SlotsMath';
import type { GameState } from './GameSession';
export interface GameStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
}
interface Snapshot {
revision: number;
state: GameState;
}
/** Shared across repository instances, including writes reentered from a storage adapter. */
const writing = new WeakMap<GameStorage, Set<string>>();
function requireValue(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(`Invalid game snapshot: ${message}`);
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function coins(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
}
function validDay(value: unknown): boolean {
if (value === null) return true;
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
const time = new Date(`${value}T00:00:00.000Z`);
return Number.isFinite(time.getTime()) && time.toISOString().slice(0, 10) === value;
}
function validateResult(value: unknown, bet: number, free: boolean): asserts value is SpinResult {
requireValue(record(value), 'missing spin result');
assertBoard(value.board);
const expected = evaluate(value.board, bet);
requireValue(value.win === expected.win && value.scatters === expected.scatters, 'incorrect spin award or scatter count');
requireValue(value.awarded === (free ? 0 : expected.awarded), 'incorrect free-spin award');
requireValue(Array.isArray(value.wins) && value.wins.length === expected.wins.length, 'incorrect winning lines');
for (let index = 0; index < expected.wins.length; index++) {
const actual: unknown = value.wins[index];
const award = expected.wins[index];
requireValue(record(actual) && actual.line === award.line && actual.count === award.count
&& actual.symbol === award.symbol && actual.amount === award.amount, 'incorrect line award');
}
if (free) {
const column = value.wildColumn;
requireValue(typeof column === 'number' && Number.isInteger(column) && column >= 0 && column < 5, 'invalid wild column');
requireValue(value.board[column].every(symbol => symbol === 'wild' || symbol === 'scatter'), 'unconverted free-spin column');
} else {
requireValue(value.wildColumn === null, 'ordinary spin has a wild column');
}
}
function validateState(value: unknown): asserts value is GameState {
requireValue(record(value), 'state is not an object');
requireValue(value.version === 1, 'unsupported version');
requireValue(coins(value.balance) && coins(value.lastWin) && coins(value.sequence), 'invalid coin amount or sequence');
assertBet(value.bet);
assertBoard(value.board);
requireValue(validDay(value.lastClaimDay), 'invalid claim day');
requireValue(record(value.settings) && typeof value.settings.music === 'boolean'
&& typeof value.settings.sound === 'boolean' && typeof value.settings.vibration === 'boolean', 'invalid preferences');
requireValue(['idle', 'spinning', 'free-trigger', 'free-ready', 'free-result'].includes(value.phase as string), 'unknown phase');
const free = value.free;
requireValue(free === null || record(free), 'invalid free-spin state');
if (free !== null) {
requireValue(typeof free.awarded === 'number' && [8, 12, 16].includes(free.awarded), 'invalid awarded spin count');
requireValue(coins(free.remaining) && free.remaining <= free.awarded && coins(free.total), 'invalid remaining spins or free total');
assertBet(free.bet);
requireValue(free.bet === value.bet, 'free-spin bet is not locked');
if (free.remaining === free.awarded) requireValue(free.total === 0, 'unplayed free spins have winnings');
}
const pending = value.pending;
requireValue(pending === null || record(pending), 'invalid pending state');
requireValue((value.phase === 'spinning') === (pending !== null), 'phase and pending result disagree');
if (pending !== null) {
requireValue(coins(pending.id) && pending.id > 0 && pending.id === value.sequence, 'invalid pending identifier');
requireValue(typeof pending.free === 'boolean', 'invalid pending round type');
validateResult(pending.result, value.bet, pending.free);
requireValue(JSON.stringify(value.board) === JSON.stringify(pending.result.board), 'pending board differs from displayed board');
requireValue(value.lastWin === pending.result.win && value.balance >= pending.result.win, 'pending award is not settled');
if (pending.free) {
requireValue(free !== null && (free.remaining as number) < (free.awarded as number)
&& (free.total as number) >= pending.result.win, 'pending free spin has invalid counters');
} else if (pending.result.awarded > 0) {
requireValue(free !== null && free.awarded === pending.result.awarded
&& free.remaining === free.awarded && free.total === 0, 'missing free-spin trigger');
} else {
requireValue(free === null, 'ordinary round retains unrelated free spins');
}
}
switch (value.phase) {
case 'idle':
requireValue(free === null, 'idle phase retains free spins');
break;
case 'free-trigger':
requireValue(free !== null && free.remaining === free.awarded && free.total === 0, 'invalid free-spin trigger');
break;
case 'free-ready':
requireValue(free !== null && (free.remaining as number) > 0, 'no free spins to start');
break;
case 'free-result':
requireValue(free !== null && free.remaining === 0, 'free-spin result has unfinished rounds');
break;
}
}
function decode(raw: string): Snapshot {
const value: unknown = JSON.parse(raw);
requireValue(record(value) && coins(value.revision) && value.revision > 0, 'invalid snapshot revision');
validateState(value.state);
return { revision: value.revision, state: value.state };
}
/**
* One JSON value per scope. A revision and exact observed bytes reject stale writers.
* Readback failure leaves the commit uncertain: never roll back or grant a new balance.
* Callers must reload after a conflict or uncertain write. Synchronous storage has no
* cross-process compare-and-swap; the shared lock additionally protects same-page reentry.
*/
export class GameRepository {
private readonly key: string;
private loaded = false;
private observed: string | null = null;
private revision = 0;
constructor(private readonly storage: GameStorage, scope: string) {
if (storage === null || typeof storage !== 'object' || typeof storage.getItem !== 'function'
|| typeof storage.setItem !== 'function') throw new Error('Storage is unavailable');
if (typeof scope !== 'string' || scope.trim().length === 0) throw new Error('A game storage scope is required');
this.key = `fruit-pop:game:v1:${encodeURIComponent(scope)}`;
}
load(): GameState | null {
const raw = this.storage.getItem(this.key);
if (raw !== null && typeof raw !== 'string') throw new Error('Storage returned an invalid value');
const snapshot = raw === null ? null : decode(raw);
this.observed = raw;
this.revision = snapshot === null ? 0 : snapshot.revision;
this.loaded = true;
// Parsing created fresh arrays and objects; nothing exposed is retained internally.
return snapshot === null ? null : snapshot.state;
}
save(state: GameState): void {
validateState(state);
let locks = writing.get(this.storage);
if (locks === undefined) {
locks = new Set<string>();
writing.set(this.storage, locks);
}
if (locks.has(this.key)) throw new Error('A write for this game scope is already in progress');
locks.add(this.key);
try {
if (!this.loaded) this.load();
if (this.storage.getItem(this.key) !== this.observed) throw new Error('Stale game snapshot; reload before retrying');
const revision = this.revision + 1;
if (!Number.isSafeInteger(revision)) throw new Error('Snapshot revision exhausted');
const raw = JSON.stringify({ revision, state });
// Validate the serialized representation as well, before any storage mutation.
decode(raw);
this.storage.setItem(this.key, raw);
if (this.storage.getItem(this.key) !== raw) throw new Error('Game snapshot readback verification failed');
this.observed = raw;
this.revision = revision;
} finally {
locks.delete(this.key);
}
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "890fa222-3dea-4856-9b97-f53a46f33cab",
"files": [],
"subMetas": {},
"userData": {}
}
+190
View File
@@ -0,0 +1,190 @@
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<T>(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;
}
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "274005d2-a03d-497c-a72a-3b8fdf13e92f",
"files": [],
"subMetas": {},
"userData": {}
}
+110
View File
@@ -0,0 +1,110 @@
import type { SymbolId } from './SlotsMath';
/** Imported artwork basenames mapped to sprite frame UUIDs. */
export const ART: Record<string, string> = {
'amethyst-fruit': 'b47019a0-c4f7-42e7-9a33-4945d17c174e@f9941',
'berry-satin': '0380d0fb-5122-403d-8604-70a144859b43@f9941',
'bonus-award-caption': 'e0db8cde-ca5c-4112-be64-e6871493df49@f9941',
'bonus-award-emblem': '3179a863-860f-4c58-bbc4-58356c95fa42@f9941',
'bonus-award-title': '7e060877-376e-47f9-85ea-2f3c66e9ddae@f9941',
'bonus-begin': '36b5dc89-4f08-45e7-a778-29da62b2c676@f9941',
'bonus-cherries': 'fab57a26-82bf-4147-8045-d320cb2f9aae@f9941',
'bonus-dismiss': '01809861-596e-4d6e-877d-d2d6f56dfe9b@f9941',
'bonus-heading': '94cfe577-ee93-4ea9-bfeb-6845a7c63fb0@f9941',
'bonus-prize-card': '1b780eb4-05ed-4ae0-926a-561ab1966f6f@f9941',
'bonus-summary-amount': '0032f965-0b3f-41f4-a8f4-768947270ff6@f9941',
'bonus-summary-caption': '5fe188dc-8060-48f3-84c8-0e097dbe417e@f9941',
'bonus-summary-garnish': '32980430-d35c-4472-b414-1bdc45d52089@f9941',
'bonus-summary-shell': '832ac5e3-c0ee-435d-9911-632fe9bc6ccc@f9941',
'bonus-summary-title': '2d6f13ea-68e3-454a-a9de-03425764b150@f9941',
'century-idle': 'bd94cae1-bea9-4286-ab7f-073cb752b4fe@f9941',
'century-picked': '7f98e04c-2e40-42f9-a8be-cf059329466a@f9941',
'claimed-shell': 'b675197c-fd3f-4376-8cda-d0b1a3e729a8@f9941',
'claimed-heading': '79620ccd-b39b-4942-8151-81e449f537d1@f9941',
'claimed-caption': 'cd60d9af-af15-4f42-935d-451b93254f06@f9941',
'claimed-garnish': '0d0198ae-4301-41f8-bb1d-e5d42d71874b@f9941',
'crest-lockup': '0b581d55-1305-4877-89bc-e36ee689ca4e@f9941',
'crimson-berry': 'fc6bac6d-3825-459c-b4cc-f44fab444668@f9941',
'daily-pill': '8fae78d2-3f85-4dbd-b9f8-3a45fcc8ce34@f9941',
'dismiss-orb': '8d4d6b9a-e889-480f-9d9d-02da011a07a2@f9941',
'effects-row': '874c8667-e914-4115-a18d-35976b134b35@f9941',
'empty-wallet-garnish': 'c20af03c-31d0-4f63-81b6-de8f20b0b465@f9941',
'empty-wallet-gift': '633dbb38-8b87-4f84-9e11-1a1a73424e7e@f9941',
'empty-wallet-heading': 'cccd71d1-f386-4586-90b0-6671734f6195@f9941',
'empty-wallet-later': '61520aa8-eba7-46a5-8307-f9ce0af22a92@f9941',
'empty-wallet-note': 'd45840bd-9f59-4547-9d8a-a023d37acade@f9941',
'empty-wallet-shell': 'd323cc8f-e867-4cee-bc3b-ddcd853c2123@f9941',
'gift-amount': 'c2d56f56-a86a-4f10-9855-b240aa7eb65b@f9941',
'gift-collect': '56889216-15e8-495e-9f1a-b1246baaf7f8@f9941',
'gift-collected': 'e19d65c1-2f82-4d93-9bec-583a3e2bb6c6@f9941',
'gift-daily': '97667b17-7152-4daf-90bc-95c7891d081f@f9941',
'gift-garnish': '980a53dc-72fb-4fa9-814d-32215e314ea0@f9941',
'gift-heading': '96eaf805-eb09-42ab-863d-44ac65755371@f9941',
'gift-shell': '8f9626d0-01d7-48ee-8955-c17dddb47917@f9941',
'guide-pill': '005c8c72-6184-41ca-bfb0-6a2867f39bc8@f9941',
'half-idle': '21caa4c3-e00c-43c4-a913-2fa8e112c849@f9941',
'half-picked': 'ad98f388-aeb6-49bb-9f45-0cf312ed30e2@f9941',
'halt-orb': '895a374d-514e-4f13-840a-3a18d125be0e@f9941',
'haptics-row': '0d3d122a-8d3f-49c4-a379-efa8a5cf0b16@f9941',
'indigo-bunch': '8f04acce-51da-4561-a8d6-8ce0c34eb806@f9941',
'instructions-pill': 'c73e2e73-e67c-4ff3-9bee-6ee6157be924@f9941',
'launch-orb': '10ada041-9713-4f0f-8987-b6b95b69593c@f9941',
'melody-row': 'dd6cd366-0385-4703-ad19-1e81038adc0d@f9941',
'neon-grid': 'dbe9db6c-7b3d-4fdf-b1f5-49af9986ac4e@f9941',
'paired-rubies': '61cc917c-b5b5-42d5-8776-6b25f8a56771@f9941',
'preferences-heading': '5cce6650-a0ea-41f6-bc79-7eee5d551984@f9941',
'preferences-orb': '5aa72211-d961-46f7-9885-bd758762e48d@f9941',
'preferences-shell': 'ccd2564c-1f01-421d-99a4-14a702645e7b@f9941',
'prism-chime': 'ced72a7e-16ce-4ad2-b797-33f8ba727613@f9941',
'prize-heading': 'bd5e21d0-7a5a-47f1-a7ca-1ee734e3f555@f9941',
'prize-plaque': 'ef26ea81-59e6-4f76-9659-59c4c1005ce0@f9941',
'quarter-idle': '8247fbcc-a0da-4841-a680-57076c0bffd8@f9941',
'quarter-picked': 'd58049a0-58a2-489b-b542-c93bc581d9bc@f9941',
'remaining-heading': '9594d9e0-13fe-419f-ac1d-4f6048f59daf@f9941',
'repeat-confirm': '76bb0f1f-746e-4e76-a81c-fca189b6468b@f9941',
'repeat-garnish': '308895e6-2597-4190-a3cc-94941f28798c@f9941',
'repeat-heading': '39538473-44f1-4edc-a359-c68f8d4d175b@f9941',
'repeat-orb': 'f23f2230-fcb3-490f-a39d-9c6d297750ec@f9941',
'repeat-shell': '74f57ccb-28f6-4a3f-80f9-313c907687a7@f9941',
'repeat-title': '6f12b32e-66b3-41e5-b69f-b59dcece67e4@f9941',
'resting-orb': 'd1f686c5-0185-4230-949d-d995c97b9ae9@f9941',
'round-prize-card': '33bf511e-c307-4652-91c0-343f4c30aaaa@f9941',
'rounds-ribbon': '82d717ef-f6f5-4f66-8f96-d23dafd7dd7d@f9941',
'ruby-seven': 'c0f53dcb-6802-4cad-9837-4c7ce5cfa33d@f9941',
'starburst-joker': '033d2418-d7a0-4580-9eb8-87c4a35fb6a7@f9941',
'summer-wedge': '4c5176fb-834d-46b4-b806-04bab836c5c8@f9941',
'ten-idle': '7ed97c1e-fbcc-44d4-b3d8-35e2cdcdd022@f9941',
'ten-picked': '3abd4a1d-ac44-44fc-a6fa-6523380b6071@f9941',
'toggle-dim': 'f3633a9e-0f96-4a27-a6e8-bccb4cb955e6@f9941',
'toggle-lit': '0e2b9198-297f-4007-82bb-c710c8501cf8@f9941',
'violet-ingot': '8a721063-d845-4715-ba42-84e4245b4fff@f9941',
'wager-down': '2f8be029-5455-47de-bf15-969ccee2ee81@f9941',
'wager-heading': '367ef08e-19b7-4758-b034-14602bd3057d@f9941',
'wager-plaque': '81668bb6-3b10-47cd-adc1-4121321a30eb@f9941',
'wager-up': '7bc945c5-706a-4270-8477-6ca626d8680c@f9941',
'wallet-pill': 'c454efe8-cbae-40f8-966b-6813b13d6973@f9941',
};
/** Logical symbols mapped to artwork basenames. */
export const SYMBOL_ART: Record<SymbolId, string> = {
seven: 'ruby-seven',
bell: 'prism-chime',
bar: 'violet-ingot',
strawberry: 'crimson-berry',
blueberry: 'indigo-bunch',
plum: 'amethyst-fruit',
cherry: 'paired-rubies',
watermelon: 'summer-wedge',
wild: 'starburst-joker',
scatter: 'bonus-cherries',
};
export const FONT_UUID = '76285818-1331-4483-8f03-aefb51af3f34';
export const ART_KEYS = Object.keys(ART).sort();
export function assetIndex(key: string): number {
const index = ART_KEYS.indexOf(key);
if (index === -1) throw new Error(`Unknown artwork key: ${key}`);
return index;
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "f4cf29b7-b6cd-4e4d-8799-81d86ae05a52",
"files": [],
"subMetas": {},
"userData": {}
}
@@ -0,0 +1,90 @@
import { _decorator, assetManager, BitmapFont, Component, Graphics, Mask, Sprite, SpriteFrame, UITransform, Widget } from 'cc';
import { EDITOR } from 'cc/env';
import { ART, ART_KEYS, FONT_UUID, SYMBOL_ART } from './OrchardAssets';
import { OrchardComposer } from './OrchardComposer';
import { authorDialogs } from './OrchardDialogs';
import { OrchardView } from './OrchardView';
import { initialState } from './GameSession';
const { ccclass, property, executeInEditMode } = _decorator;
@ccclass('OrchardAuthoring')
@executeInEditMode
export class OrchardAuthoring extends Component {
@property status = 'Not authored';
@property
get composeReference(): boolean { return false; }
set composeReference(value: boolean) {
if (!EDITOR || !value || this.status === 'Preparing artwork') return;
this.status = 'Preparing artwork';
assetManager.loadAny([...ART_KEYS.map(key => ART[key]), FONT_UUID], (error, assets) => {
if (!this.isValid) return;
if (error) { this.status = 'Artwork preparation failed'; return; }
try {
const list = assets as (SpriteFrame | BitmapFont)[];
const view = this.node.getComponent(OrchardView) ?? this.node.addComponent(OrchardView);
view.artFrames = list.slice(0, ART_KEYS.length) as SpriteFrame[];
view.numerals = list[ART_KEYS.length] as BitmapFont;
this.compose(view);
this.status = 'Ready: editable reference layout';
} catch (cause) { this.status = `Layout error: ${cause instanceof Error ? cause.message : 'unknown'}`; }
});
}
private compose(view: OrchardView): void {
const root = this.node;
const widget = root.getComponent(Widget);
if (widget) { widget.alignFlags = 0; widget.enabled = false; }
root.getComponent(UITransform)!.setContentSize(1080, 1920); root.setPosition(540, 960, 0);
const ui = new OrchardComposer(root, key => view.artFrames[ART_KEYS.indexOf(key)], view.numerals!);
ui.image('OrchardScenery', 'berry-satin', 540, 960, 1080, 1920);
ui.image('OrchardCrest', 'crest-lockup', 516, 223, 633, 417);
ui.button('PreferencesAccess', 'preferences-orb', 96, 78, 122, 122);
ui.image('WalletPlate', 'wallet-pill', 906, 50, 314, 92);
ui.text('WalletAmount', '100,000', 937, 48, 210, 68, 47);
ui.image('ReelSurround', 'neon-grid', 540, 817, 1080, 755);
const board = initialState().board;
for (let c = 0; c < 5; c++) {
const column = ui.group(`ReelWindow${c}`);
column.setPosition(-410 + c * 205, 145, 0);
column.getComponent(UITransform)!.setContentSize(200, 690);
const mask = column.getComponent(Mask) ?? column.addComponent(Mask);
mask.type = Mask.Type.GRAPHICS_RECT;
for (let r = 0; r < 6; r++) {
const n = ui.image(`Cell${r}`, SYMBOL_ART[board[c][r % 3]], 540, 960, 190, 205, column);
n.setPosition(0, 230 - r * 230, 0);
n.getComponent(Sprite)!.trim = false;
const size = n.getComponent(Sprite)!.spriteFrame!.originalSize;
const scale = Math.min(198 / size.width, 212 / size.height);
n.getComponent(UITransform)!.setContentSize(size.width * scale, size.height * scale);
}
}
const lines = ui.group('WinningLines'); lines.getComponent(Graphics) ?? lines.addComponent(Graphics);
const normal = ui.group('NormalPrize');
ui.image('NormalPrizePlate', 'prize-plaque', 540, 1287, 712, 153, normal);
ui.image('NormalPrizeTitle', 'prize-heading', 380, 1287, 190, 86, normal);
ui.text('NormalPrizeAmount', '0', 641, 1288, 310, 124, 108, normal, true);
const ribbon = ui.group('RoundsRibbon');
ui.image('RoundsPlate', 'rounds-ribbon', 540, 1257, 980, 138, ribbon);
ui.image('RoundsHeading', 'bonus-heading', 416, 1257, 354, 58, ribbon);
ui.text('RoundsCount', '8', 649, 1257, 128, 92, 85, ribbon, true);
ui.image('RoundsSuffix', 'remaining-heading', 776, 1257, 151, 58, ribbon);
ribbon.active = false;
const dual = ui.group('BonusPrize');
ui.image('RoundPrizePlate', 'round-prize-card', 300, 1404, 431, 150, dual);
ui.image('BonusPrizePlate', 'bonus-prize-card', 770, 1404, 482, 162, dual);
ui.text('RoundPrizeAmount', '0', 300, 1425, 350, 90, 76, dual, true);
ui.text('BonusPrizeAmount', '0', 770, 1425, 395, 95, 78, dual, true);
dual.active = false;
const wager = ui.group('WagerControls'); wager.setPosition(0, -500, 0);
ui.image('WagerPlate', 'wager-plaque', 540, 960, 773, 139, wager);
ui.button('WagerDecrease', 'wager-down', 248, 960, 126, 102, wager);
ui.button('WagerIncrease', 'wager-up', 834, 960, 128, 102, wager);
ui.image('WagerTitle', 'wager-heading', 442, 960, 96, 59, wager);
ui.text('WagerAmount', '2,000', 602, 960, 218, 90, 73, wager, true);
ui.button('LaunchAccess', 'launch-orb', 540, 1714, 342, 341);
ui.button('RepeatAccess', 'repeat-orb', 760, 1598, 141, 140);
ui.button('GuideAccess', 'guide-pill', 164, 1720, 284, 123);
ui.button('GiftAccess', 'daily-pill', 928, 1720, 264, 121);
ui.text('GameNotice', '', 540, 191, 760, 84, 30).active = false;
authorDialogs(ui);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "42f73f6b-fd83-42ae-8e89-274e6cca5a1f",
"files": [],
"subMetas": {},
"userData": {}
}
+60
View File
@@ -0,0 +1,60 @@
import { BitmapFont, BlockInputEvents, Button, Color, Graphics, Label, Layers, Node, Sprite, SpriteFrame, UITransform } from 'cc';
import type { DialogComposer } from './OrchardDialogs';
/** 仅供显式编辑命令创建节点,运行时不重建界面。 / Used only by explicit editor authoring, never by runtime rendering. */
export class OrchardComposer implements DialogComposer {
constructor(readonly root: Node, readonly art: (key: string) => SpriteFrame, readonly font: BitmapFont) {}
group(name: string, parent = this.root): Node {
const node = parent.getChildByName(name) ?? new Node(name);
node.parent = parent;
node.layer = Layers.Enum.UI_2D;
node.setPosition(0, 0, 0);
node.getComponent(UITransform) ?? node.addComponent(UITransform);
return node;
}
image(name: string, key: string, x: number, y: number, w: number, h: number, parent = this.root): Node {
const node = this.group(name, parent);
node.setPosition(x - 540, 960 - y, 0);
const sprite = node.getComponent(Sprite) ?? node.addComponent(Sprite);
sprite.spriteFrame = this.art(key);
sprite.sizeMode = Sprite.SizeMode.CUSTOM;
sprite.trim = false;
node.getComponent(UITransform)!.setContentSize(w, h);
return node;
}
text(name: string, value: string, x: number, y: number, w: number, h: number, size: number, parent = this.root, gold = false): Node {
const node = this.group(name, parent);
node.setPosition(x - 540, 960 - y, 0);
const label = node.getComponent(Label) ?? node.addComponent(Label);
label.font = gold ? this.font : null;
label.useSystemFont = !gold;
label.fontFamily = 'Arial';
label.string = value;
label.fontSize = size;
label.lineHeight = size * 1.15;
label.horizontalAlign = Label.HorizontalAlign.CENTER;
label.verticalAlign = Label.VerticalAlign.CENTER;
label.overflow = Label.Overflow.SHRINK;
label.enableWrapText = false;
label.color = Color.WHITE;
label.isBold = !gold;
node.getComponent(UITransform)!.setContentSize(w, h);
return node;
}
button(name: string, key: string, x: number, y: number, w: number, h: number, parent = this.root): Node {
const node = this.image(name, key, x, y, w, h, parent);
const button = node.getComponent(Button) ?? node.addComponent(Button);
button.transition = Button.Transition.SCALE;
button.zoomScale = .96;
return node;
}
shade(name: string, parent: Node): Node {
const node = this.group(name, parent);
node.getComponent(UITransform)!.setContentSize(20000, 20000);
const graphics = node.getComponent(Graphics) ?? node.addComponent(Graphics);
graphics.clear(); graphics.fillColor = new Color(12, 0, 22, 205);
graphics.rect(-10000, -10000, 20000, 20000); graphics.fill();
node.getComponent(BlockInputEvents) ?? node.addComponent(BlockInputEvents);
return node;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "d459c9c7-6f52-48d2-ba96-6428ab673391",
"files": [],
"subMetas": {},
"userData": {}
}
+567
View File
@@ -0,0 +1,567 @@
import { BlockInputEvents, Button, Label, Node, Sprite, SpriteFrame, UITransform } from 'cc';
import type { GameSession, GameState } from './GameSession';
import { SYMBOL_ART } from './OrchardAssets';
import { PAYLINES, PAYTABLE } from './SlotsMath';
import type { OrdinarySymbol } from './SlotsMath';
import { director } from 'cc';
/**
* Coordinates are screen centres in the 1080 x 1920 reference layout (origin: top left).
* Every group stays at the Canvas origin; the composer converts leaf coordinates.
* Gold labels use the composer's bitmap font; all other labels use Arial.
*/
export interface DialogComposer {
group(name: string, parent?: Node): Node;
image(name: string, key: string, x: number, y: number, w: number, h: number, parent?: Node): Node;
text(name: string, value: string, x: number, y: number, w: number, h: number, size: number, parent?: Node, gold?: boolean): Node;
button(name: string, key: string, x: number, y: number, w: number, h: number, parent?: Node): Node;
shade(name: string, parent: Node): Node;
}
export type DialogKind = 'repeat' | 'preferences' | 'gift' | 'empty' | 'award' | 'summary' | 'guide';
type PreferenceKey = keyof GameState['settings'];
type VisibleDialog = DialogKind | 'error';
const GROUP_NAMES: Record<VisibleDialog, string> = {
repeat: 'RepeatDialog',
preferences: 'PreferencesDialog',
gift: 'GiftDialog',
empty: 'EmptyWalletDialog',
award: 'BonusAwardDialog',
summary: 'BonusSummaryDialog',
guide: 'GuideDialog',
error: 'ErrorDialog',
};
const AUTO_OPTIONS = [
{ count: 10, key: 'ten', x: 340, y: 880 },
{ count: 25, key: 'quarter', x: 740, y: 880 },
{ count: 50, key: 'half', x: 340, y: 1080 },
{ count: 100, key: 'century', x: 740, y: 1080 },
] as const;
const PREFERENCES: readonly { key: PreferenceKey; name: string; art: string; y: number }[] = [
{ key: 'music', name: 'Music', art: 'melody-row', y: 790 },
{ key: 'sound', name: 'Sound', art: 'effects-row', y: 955 },
{ key: 'vibration', name: 'Vibration', art: 'haptics-row', y: 1120 },
];
const PAYING_SYMBOLS = Object.keys(PAYTABLE) as OrdinarySymbol[];
const SYMBOL_NAMES: Record<OrdinarySymbol, string> = {
seven: 'SEVEN', bell: 'BELL', bar: 'BAR', strawberry: 'STRAWBERRY',
blueberry: 'BLUEBERRY', plum: 'PLUM', cherry: 'CHERRY', watermelon: 'WATERMELON',
};
const GUIDE_TITLES = ['PAYTABLE 1 / 2', 'PAYTABLE 2 / 2', 'RULES & SYMBOLS', '20 PAYLINES', 'BONUS & DAILY COINS'];
const DAILY_COINS = 20_000;
const FAILURE = {
open: 'Unable to open this dialog. Please try again.',
repeat: 'Unable to start auto spin. Please try again.',
selection: 'Unable to update the selection. Please try again.',
preference: 'Unable to save your preference. Please try again. Your saved data has not been reset.',
gift: 'Unable to collect daily coins. Please try again. Your saved data has not been reset.',
clock: 'Unable to check the daily gift time. Please try again.',
award: 'Unable to start free spins. Please try again. Your saved progress has not been reset.',
summary: 'Unable to close the free-spin result. Please try again. Your saved progress has not been reset.',
guide: 'Unable to display this help page. Please try again.',
restore: 'Unable to restore the dialog. Please try again.',
};
function coins(value: number): string {
return value.toLocaleString('en-US');
}
/** Plain text buttons avoid reusing artwork that already contains an unrelated caption. */
function labelButton(ui: DialogComposer, name: string, value: string, x: number, y: number, w: number, parent: Node): Node {
const node = ui.text(name, value, x, y, w, 90, 36, parent);
const button = node.getComponent(Button) ?? node.addComponent(Button);
button.transition = Button.Transition.SCALE;
button.zoomScale = 0.96;
return node;
}
function body(ui: DialogComposer, name: string, value: string, y: number, h: number, parent: Node): Node {
const node = ui.text(name, value, 540, y, 820, h, 34, parent);
const label = node.getComponent(Label);
if (label) {
label.horizontalAlign = Label.HorizontalAlign.LEFT;
label.verticalAlign = Label.VerticalAlign.CENTER;
label.lineHeight = 48;
label.enableWrapText = true;
}
return node;
}
/**
* Authors ModalLayer/ Shade + eight independent dialog groups. No scene is saved here.
* Button and live-label names below are the shared authoring/runtime contract.
*/
export function authorDialogs(ui: DialogComposer): void {
const layer = ui.group('ModalLayer');
const shade = ui.shade('Shade', layer);
if (!shade.getComponent(BlockInputEvents)) shade.addComponent(BlockInputEvents);
const groups = {} as Record<VisibleDialog, Node>;
for (const kind of Object.keys(GROUP_NAMES) as VisibleDialog[]) {
groups[kind] = ui.group(GROUP_NAMES[kind], layer);
groups[kind].active = false;
}
const repeat = groups.repeat;
ui.image('RepeatShell', 'repeat-shell', 540, 960, 870, 990, repeat);
ui.image('RepeatTitle', 'repeat-title', 540, 600, 630, 145, repeat);
ui.image('RepeatGarnish', 'repeat-garnish', 225, 705, 150, 140, repeat);
ui.text('RepeatHint', 'CHOOSE YOUR SPINS', 595, 735, 570, 60, 34, repeat);
for (const option of AUTO_OPTIONS) {
ui.button(`RepeatCount${option.count}`, `${option.key}-${option.count === 10 ? 'picked' : 'idle'}`,
option.x, option.y, 360, 170, repeat);
}
ui.button('RepeatStart', 'repeat-confirm', 540, 1300, 735, 185, repeat);
ui.button('RepeatClose', 'dismiss-orb', 900, 510, 114, 112, repeat);
const preferences = groups.preferences;
ui.image('PreferencesShell', 'preferences-shell', 540, 960, 879, 1035, preferences);
ui.image('PreferencesTitle', 'preferences-heading', 540, 568, 505, 85, preferences);
for (const preference of PREFERENCES) {
ui.image(`Preferences${preference.name}Row`, preference.art, 540, preference.y, 788, 155, preferences);
ui.button(`Preferences${preference.name}Toggle`, 'toggle-lit', 795, preference.y, 216, 94, preferences);
}
ui.button('PreferencesGuide', 'instructions-pill', 540, 1318, 630, 133, preferences);
ui.text('PreferencesNote', 'Preferences are saved on this device.', 540, 1430, 790, 50, 32, preferences);
ui.button('PreferencesClose', 'dismiss-orb', 900, 510, 114, 112, preferences);
const gift = groups.gift;
ui.image('GiftShell', 'gift-shell', 540, 960, 928, 1205, gift);
ui.image('GiftTitle', 'gift-heading', 540, 465, 590, 105, gift);
ui.image('GiftGarnish', 'gift-garnish', 540, 760, 415, 397, gift);
ui.image('GiftAmountPlate', 'gift-amount', 540, 1030, 782, 166, gift);
ui.text('GiftAmount', coins(DAILY_COINS), 600, 1030, 530, 120, 96, gift, true);
ui.image('GiftDailyLabel', 'gift-daily', 540, 1180, 738, 66, gift);
ui.button('GiftClaim', 'gift-collect', 540, 1340, 642, 196, gift);
ui.image('GiftCollected', 'gift-collected', 540, 1340, 585, 147, gift).active = false;
ui.text('GiftCountdown', 'Available once per UTC day.', 540, 1480, 820, 60, 32, gift);
ui.button('GiftClose', 'dismiss-orb', 920, 405, 114, 112, gift);
const empty = groups.empty;
ui.image('EmptyWalletShell', 'empty-wallet-shell', 540, 960, 862, 1113, empty);
ui.image('EmptyWalletTitle', 'empty-wallet-heading', 540, 600, 705, 310, empty);
ui.image('EmptyWalletNote', 'empty-wallet-note', 540, 825, 523, 108, empty);
ui.image('EmptyWalletGarnish', 'empty-wallet-garnish', 540, 1050, 661, 365, empty);
ui.button('EmptyWalletGift', 'empty-wallet-gift', 540, 1300, 703, 158, empty);
ui.button('EmptyWalletLater', 'empty-wallet-later', 540, 1435, 350, 85, empty);
ui.button('EmptyWalletClose', 'dismiss-orb', 902, 465, 108, 108, empty);
const award = groups.award;
ui.image('BonusAwardShell', 'repeat-shell', 540, 960, 870, 990, award);
ui.image('BonusAwardTitle', 'bonus-award-title', 540, 620, 824, 244, award);
ui.image('BonusAwardCaption', 'bonus-award-caption', 540, 822, 680, 109, award);
ui.text('BonusAwardCount', '0', 540, 985, 440, 200, 180, award, true);
for (let index = 0; index < 3; index++) {
ui.image(`BonusAwardScatter${index + 1}`, 'bonus-award-emblem', 350 + index * 190, 1145, 155, 153, award);
}
ui.button('BonusAwardStart', 'bonus-begin', 540, 1340, 640, 217, award);
const summary = groups.summary;
ui.image('BonusSummaryShell', 'bonus-summary-shell', 540, 960, 1060, 945, summary);
ui.image('BonusSummaryTitle', 'bonus-summary-title', 540, 650, 770, 250, summary);
ui.image('BonusSummaryCaption', 'bonus-summary-caption', 540, 852, 690, 75, summary);
ui.image('BonusSummaryGarnish', 'bonus-summary-garnish', 850, 1180, 330, 171, summary);
ui.image('BonusSummaryAmountPlate', 'bonus-summary-amount', 540, 1018, 780, 205, summary);
ui.text('BonusSummaryAmount', '0', 540, 1018, 680, 150, 108, summary, true);
ui.button('BonusSummaryContinue', 'bonus-dismiss', 540, 1280, 630, 190, summary);
const guide = groups.guide;
ui.image('GuideShell', 'preferences-shell', 540, 960, 980, 1550, guide);
ui.text('GuideTitle', GUIDE_TITLES[0], 540, 310, 760, 85, 44, guide);
ui.button('GuideClose', 'dismiss-orb', 960, 260, 90, 90, guide);
const pages = GUIDE_TITLES.map((_, index) => ui.group(`GuidePage${index}`, guide));
for (let page = 0; page < 2; page++) {
const parent = pages[page];
ui.text(`GuidePaytableHint${page}`, 'MATCHING SYMBOLS FROM THE LEFT', 540, 405, 820, 55, 32, parent);
for (let column = 0; column < 3; column++) {
ui.text(`GuidePaytableHeader${page}_${column}`, `${column + 3} MATCH`, 450 + column * 200, 490, 180, 55, 34, parent);
}
PAYING_SYMBOLS.slice(page * 4, page * 4 + 4).forEach((symbol, row) => {
const y = 625 + row * 225;
ui.image(`GuideSymbol_${symbol}`, SYMBOL_ART[symbol], 215, y, 145, 145, parent);
ui.text(`GuideSymbolName_${symbol}`, SYMBOL_NAMES[symbol], 215, y + 96, 230, 48, 32, parent);
PAYTABLE[symbol].forEach((multiplier, column) => {
ui.text(`GuideMultiplier_${symbol}_${column + 3}`, `${multiplier}x`, 450 + column * 200, y, 180, 80, 36, parent);
});
});
ui.text(`GuideLineBetCaption${page}`, 'LINE BET', 300, 1450, 280, 65, 34, parent);
ui.text(`GuideLineBet${page}`, '0', 685, 1450, 450, 70, 52, parent, true);
ui.text(`GuidePaytableNote${page}`, `Award = multiplier x line bet. All ${PAYLINES.length} lines play.`, 540, 1535, 850, 65, 32, parent);
}
ui.image('GuideWildSymbol', SYMBOL_ART.wild, 330, 510, 150, 150, pages[2]);
ui.image('GuideScatterSymbol', SYMBOL_ART.scatter, 750, 510, 150, 150, pages[2]);
ui.text('GuideWildCaption', 'WILD', 330, 615, 300, 55, 36, pages[2]);
ui.text('GuideScatterCaption', 'SCATTER', 750, 615, 300, 55, 36, pages[2]);
body(ui, 'GuideRules', [
`${PAYLINES.length} active lines. 5 reels, 3 rows.`,
'',
'Matching symbols pay from left to right.',
'Start on reel 1. Match 3, 4 or 5 symbols.',
'Only the best award pays on each line.',
'Wins on different lines are added.',
'',
'WILD replaces regular symbols.',
'It does not replace SCATTER.',
'',
'SCATTER counts anywhere on the reels.',
'3 / 4 / 5+ award 8 / 12 / 16 free spins.',
'SCATTER has no separate coin payout.',
].join('\n'), 1080, 800, pages[2]);
ui.text('GuideLineLegend', 'T = TOP M = MIDDLE B = BOTTOM', 540, 435, 850, 70, 32, pages[3]);
const linesPerColumn = Math.ceil(PAYLINES.length / 2);
PAYLINES.forEach((line, index) => {
const parent = ui.group(`GuidePayline${index + 1}`, pages[3]);
const x = 170 + Math.floor(index / linesPerColumn) * 420;
const y = 570 + index % linesPerColumn * 80;
ui.text(`GuidePaylineNumber${index + 1}`, String(index + 1).padStart(2, '0'), x, y, 65, 65, 36, parent);
// Individual fixed-width Arial cells preserve alignment without changing the font contract.
line.forEach((row, reel) => {
ui.text(`GuidePayline${index + 1}Reel${reel + 1}`, ['T', 'M', 'B'][row],
x + 85 + reel * 50, y, 45, 65, 36, parent);
});
});
ui.text('GuideLineDirection', 'Read each sequence from reel 1 to reel 5.', 540, 1470, 850, 100, 32, pages[3]);
ui.text('GuideFreeTitle', 'FREE SPINS', 540, 465, 820, 65, 36, pages[4]);
body(ui, 'GuideFreeRules', [
'3 / 4 / 5+ SCATTERs award 8 / 12 / 16.',
'Free spins keep the triggering bet.',
'Each spin makes one whole reel WILD;',
'SCATTERs stay unchanged.',
'Free spins do not retrigger.',
].join('\n'), 665, 290, pages[4]);
ui.text('GuideAutoTitle', 'AUTO SPIN', 540, 900, 820, 65, 36, pages[4]);
body(ui, 'GuideAutoRules', [
`Choose ${AUTO_OPTIONS.map(option => option.count).join(' / ')} spins.`,
'Only paid spins use this counter.',
'Opening a dialog stops auto spin.',
'Insufficient coins or a bonus stops it.',
].join('\n'), 1075, 240, pages[4]);
ui.text('GuideDailyTitle', 'DAILY COINS', 540, 1270, 820, 65, 36, pages[4]);
ui.text('GuideDailyAmount', coins(DAILY_COINS), 540, 1360, 600, 80, 60, pages[4], true);
body(ui, 'GuideDailyRules', 'Coins, once per UTC day.\nResets at 00:00 UTC.\nSaved locally for this guest account.', 1470, 160, pages[4]);
pages.forEach((page, index) => { page.active = index === 0; });
labelButton(ui, 'GuidePrevious', 'PREVIOUS', 260, 1640, 300, guide);
ui.text('GuidePageNumber', '1 / 5', 540, 1640, 180, 70, 34, guide);
labelButton(ui, 'GuideNext', 'NEXT', 820, 1640, 300, guide);
const error = groups.error;
ui.image('ErrorShell', 'repeat-shell', 540, 960, 870, 990, error);
ui.text('ErrorTitle', 'PLEASE TRY AGAIN', 540, 665, 740, 90, 44, error);
const message = body(ui, 'ErrorMessage', 'Unable to complete the action. Please try again.', 965, 390, error);
const messageLabel = message.getComponent(Label);
if (messageLabel) messageLabel.horizontalAlign = Label.HorizontalAlign.CENTER;
labelButton(ui, 'ErrorAcknowledge', 'OK', 540, 1300, 600, error);
layer.active = false;
}
function findNode(root: Node, name: string): Node | null {
if (root.name === name) return root;
for (const child of root.children) {
const found = findNode(child, name);
if (found) return found;
}
return null;
}
/** Owns only modal presentation; closing a dialog never resets the game phase. */
export class OrchardDialogs {
private readonly layer: Node;
private readonly groups: Record<VisibleDialog, Node>;
private readonly nodes = new Map<string, Node>();
private readonly listeners: { node: Node; callback: () => void }[] = [];
private visible: VisibleDialog | null = null;
private errorReturn: DialogKind | null = null;
private guideReturn: 'preferences' | null = null;
private selectedCount: number = AUTO_OPTIONS[0].count;
private guidePage = 0;
private working = false;
private persistenceFailed = false;
private disposed = false;
/** root may be the Canvas, its scene ancestor, or ModalLayer itself. */
constructor(
root: Node,
private readonly session: GameSession,
private readonly art: (key: string) => SpriteFrame,
private readonly onAuto: (count: number) => void,
private readonly onResume: () => void,
private readonly onChange: () => void,
) {
const layer = findNode(root, 'ModalLayer');
if (!layer) throw new Error('Missing ModalLayer. Run authorDialogs before binding OrchardDialogs.');
this.layer = layer;
this.groups = {} as Record<VisibleDialog, Node>;
for (const kind of Object.keys(GROUP_NAMES) as VisibleDialog[]) {
this.groups[kind] = this.required(GROUP_NAMES[kind]);
}
const shade = this.required('Shade');
if (!shade.getComponent(BlockInputEvents)) shade.addComponent(BlockInputEvents);
shade.active = true;
this.bindControls();
this.close();
}
get opened(): boolean {
return !this.disposed && this.layer.isValid && this.layer.active;
}
show(kind: DialogKind): void {
if (this.disposed) return;
try {
if (kind === 'guide' && this.visible !== 'guide' && this.visible !== 'error') {
this.guideReturn = this.visible === 'preferences' ? 'preferences' : null;
this.guidePage = 0;
}
this.refresh(kind);
this.activate(kind);
} catch {
this.error(FAILURE.open);
}
}
close(): void {
if (this.disposed) return;
for (const group of Object.values(this.groups)) group.active = false;
this.layer.active = false;
this.visible = null;
this.errorReturn = null;
this.guideReturn = null;
}
/** Call from the view update loop; the session supplies the UTC clock. */
tick(): void {
if (!this.opened || this.visible !== 'gift') return;
try {
this.refreshGift();
} catch {
this.error(FAILURE.clock);
}
}
error(message: string, reload = false): void {
if (this.disposed) return;
if (reload) this.persistenceFailed = true;
if (this.visible !== 'error') this.errorReturn = this.visible;
this.label('ErrorMessage').string = message.trim().slice(0, 300) || FAILURE.open;
this.activate('error');
}
dispose(): void {
if (this.disposed) return;
for (const listener of this.listeners) {
if (listener.node.isValid) listener.node.off(Button.EventType.CLICK, listener.callback, this);
}
this.listeners.length = 0;
if (this.layer.isValid) this.close();
this.nodes.clear();
this.disposed = true;
}
private bindControls(): void {
for (const name of ['RepeatClose', 'PreferencesClose', 'GiftClose', 'EmptyWalletClose', 'EmptyWalletLater']) {
this.bind(name, () => this.close(), FAILURE.open);
}
for (const option of AUTO_OPTIONS) {
this.bind(`RepeatCount${option.count}`, () => {
this.selectedCount = option.count;
this.refreshRepeat();
}, FAILURE.selection);
}
this.bind('RepeatStart', () => {
if (this.session.state.phase !== 'idle') throw new Error('Auto spin requires the idle phase.');
this.close();
this.onAuto(this.selectedCount);
}, FAILURE.repeat);
for (const preference of PREFERENCES) {
this.bind(`Preferences${preference.name}Toggle`, () => {
this.session.setPreference(preference.key, !this.session.state.settings[preference.key]);
this.refreshPreferences();
this.onChange();
}, FAILURE.preference);
}
this.bind('PreferencesGuide', () => this.show('guide'), FAILURE.guide);
this.bind('EmptyWalletGift', () => this.show('gift'), FAILURE.gift);
this.bind('GiftClaim', () => {
const claimed = this.session.claimDaily();
this.refreshGift();
if (claimed) this.onChange();
}, FAILURE.gift);
// These are the only controls on the two mandatory free-spin dialogs.
this.bind('BonusAwardStart', () => {
this.session.startFree();
this.close();
this.onResume();
}, FAILURE.award);
this.bind('BonusSummaryContinue', () => {
this.session.closeFreeResult();
this.close();
this.onChange();
}, FAILURE.summary);
this.bind('GuidePrevious', () => this.turnGuide(-1), FAILURE.guide);
this.bind('GuideNext', () => this.turnGuide(1), FAILURE.guide);
this.bind('GuideClose', () => {
if (this.guideReturn === 'preferences') this.show('preferences');
else this.close();
}, FAILURE.guide);
this.bind('ErrorAcknowledge', () => {
if (this.persistenceFailed) {
// 旧会话不能盲目重放不确定提交,重新登录后从已保存阶段恢复。 / Reload the committed snapshot instead of replaying an uncertain mutation.
director.loadScene('Welcome');
return;
}
const next = this.recoverKind(this.errorReturn);
if (next === null) this.close();
else this.show(next);
}, FAILURE.restore);
}
private bind(name: string, action: () => void, failure: string): void {
const node = this.required(name);
const button = node.getComponent(Button);
if (!button) throw new Error(`Missing dialog Button: ${name}`);
const callback = (): void => {
if (this.disposed || this.working || !this.opened || !node.activeInHierarchy || !button.interactable) return;
const previous = this.visible;
this.working = true;
try {
action();
} catch {
if ([FAILURE.preference, FAILURE.gift, FAILURE.award, FAILURE.summary].includes(failure)) {
this.persistenceFailed = true;
this.error('Unable to confirm the saved change. Tap OK to return to login and safely restore your saved progress.');
return;
}
this.error(failure);
if (previous !== 'error') this.errorReturn = previous;
} finally {
this.working = false;
}
};
node.on(Button.EventType.CLICK, callback, this);
this.listeners.push({ node, callback });
}
private activate(kind: VisibleDialog): void {
for (const key of Object.keys(this.groups) as VisibleDialog[]) this.groups[key].active = key === kind;
this.visible = kind;
this.layer.active = true;
}
private refresh(kind: DialogKind): void {
switch (kind) {
case 'repeat': this.refreshRepeat(); break;
case 'preferences': this.refreshPreferences(); break;
case 'gift': this.refreshGift(); break;
case 'award': {
const state = this.session.state;
if (state.phase !== 'free-trigger' || state.free === null) throw new Error('No free-spin award is pending.');
this.label('BonusAwardCount').string = String(state.free.awarded);
break;
}
case 'summary': {
const state = this.session.state;
if (state.phase !== 'free-result' || state.free === null) throw new Error('No free-spin result is pending.');
this.label('BonusSummaryAmount').string = coins(state.free.total);
break;
}
case 'guide': this.refreshGuide(); break;
case 'empty': break;
}
}
private refreshRepeat(): void {
for (const option of AUTO_OPTIONS) {
this.setArt(`RepeatCount${option.count}`, `${option.key}-${option.count === this.selectedCount ? 'picked' : 'idle'}`);
}
}
private refreshPreferences(): void {
const settings = this.session.state.settings;
for (const preference of PREFERENCES) {
this.setArt(`Preferences${preference.name}Toggle`, settings[preference.key] ? 'toggle-lit' : 'toggle-dim');
}
}
private refreshGift(): void {
const available = this.session.canClaimDaily();
for (const [name, key, x, y, w, h] of (available ? [
['GiftShell', 'gift-shell', 540, 960, 928, 1205],
['GiftTitle', 'gift-heading', 540, 465, 590, 105],
['GiftGarnish', 'gift-garnish', 540, 760, 415, 397],
['GiftDailyLabel', 'gift-daily', 540, 1180, 738, 66],
] : [
['GiftShell', 'claimed-shell', 540, 960, 925, 1150],
['GiftTitle', 'claimed-heading', 540, 520, 755, 368],
['GiftGarnish', 'claimed-garnish', 540, 840, 355, 252],
['GiftDailyLabel', 'claimed-caption', 540, 1180, 764, 62],
]) as [string, string, number, number, number, number][]) {
this.setArt(name, key);
this.required(name).setPosition(x - 540, 960 - y, 0);
this.required(name).getComponent(UITransform)!.setContentSize(w, h);
}
this.required('GiftClaim').active = available;
this.required('GiftCollected').active = !available;
this.label('GiftAmount').string = coins(DAILY_COINS);
const seconds = Math.ceil(Math.max(0, this.session.nextResetMs()) / 1000);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
const remaining = seconds % 60;
const time = [hours, minutes, remaining].map(value => String(value).padStart(2, '0')).join(':');
this.label('GiftCountdown').string = `${available ? 'Resets' : 'Next gift'} in ${time} (UTC)`;
}
private turnGuide(direction: number): void {
this.guidePage = Math.max(0, Math.min(GUIDE_TITLES.length - 1, this.guidePage + direction));
this.refreshGuide();
}
private refreshGuide(): void {
const state = this.session.state;
const lineBet = (state.free?.bet ?? state.bet) / PAYLINES.length;
for (let page = 0; page < GUIDE_TITLES.length; page++) {
this.required(`GuidePage${page}`).active = page === this.guidePage;
}
for (let page = 0; page < 2; page++) this.label(`GuideLineBet${page}`).string = coins(lineBet);
this.label('GuideTitle').string = this.guidePage === 3 ? `${PAYLINES.length} PAYLINES` : GUIDE_TITLES[this.guidePage];
this.label('GuidePageNumber').string = `${this.guidePage + 1} / ${GUIDE_TITLES.length}`;
this.component('GuidePrevious', Button).interactable = this.guidePage > 0;
this.component('GuideNext', Button).interactable = this.guidePage < GUIDE_TITLES.length - 1;
}
/** Restore pending confirmations after an error without replaying successful mutations. */
private recoverKind(previous: DialogKind | null): DialogKind | null {
const phase = this.session.state.phase;
if (phase === 'free-trigger') return 'award';
if (phase === 'free-result') return 'summary';
return previous === 'award' || previous === 'summary' ? null : previous;
}
private required(name: string): Node {
const cached = this.nodes.get(name);
if (cached) return cached;
const node = findNode(this.layer, name);
if (!node) throw new Error(`Missing authored dialog node: ${name}`);
this.nodes.set(name, node);
return node;
}
private component<T extends Label | Sprite | Button>(name: string, type: new () => T): T {
const component = this.required(name).getComponent(type);
if (!component) throw new Error(`Missing dialog component on: ${name}`);
return component;
}
private label(name: string): Label {
return this.component(name, Label);
}
private setArt(name: string, key: string): void {
this.component(name, Sprite).spriteFrame = this.art(key);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "e65a743d-79a5-41e5-ad21-2dfcdcbaf426",
"files": [],
"subMetas": {},
"userData": {}
}
+135
View File
@@ -0,0 +1,135 @@
import { assetManager, SceneAsset, sys } from 'cc';
import { GUEST_SERVICE } from '../../login/scripts/GuestRuntime';
import { GameRepository } from './GameRepository';
import { GameSession } from './GameSession';
interface ExclusiveGameLock {
scope: string;
acquired: Promise<void>;
release(): void;
}
/** Authenticated, local-only game composition root. Never restore authentication from a token. */
export class OrchardRuntime {
static readonly LOCK_IN_USE = 'This saved game is already open in another tab. Close it and tap the guest button to retry.';
static readonly LOCK_UNAVAILABLE = 'Exclusive saved game access is unavailable on this platform. Please use a supported browser and retry.';
static session: GameSession | null = null;
private static exclusive: ExclusiveGameLock | null = null;
private static preparation = 0;
private static detachCancellation: (() => void) | null = null;
/** Synchronous composition for pure tests. Browser entry points must use prepareExclusive. */
static prepare(guestId: string): GameSession {
this.clear();
this.session = this.restore(this.scopeFor(guestId));
return this.session;
}
static async prepareExclusive(guestId: string, signal?: AbortSignal): Promise<GameSession> {
if (signal?.aborted) throw new Error('Game preparation was cancelled.');
const operation = ++this.preparation;
this.detachCancellation?.();
this.detachCancellation = null;
this.session = null;
try {
const scope = this.scopeFor(guestId);
if (typeof globalThis.navigator?.locks?.request !== 'function') throw new Error(this.LOCK_UNAVAILABLE);
if (this.exclusive?.scope !== scope) {
const previous = this.exclusive;
this.exclusive = null;
previous?.release();
}
const exclusive = this.exclusive ?? this.requestExclusive(scope);
const cancel = (): void => {
if (operation === this.preparation && this.exclusive === exclusive) this.clear();
};
signal?.addEventListener('abort', cancel, { once: true });
this.detachCancellation = () => signal?.removeEventListener('abort', cancel);
await exclusive.acquired;
if (signal?.aborted || operation !== this.preparation || this.exclusive !== exclusive) {
throw new Error('Game preparation was cancelled.');
}
this.session = this.restore(scope);
return this.session;
} catch (error) {
if (operation === this.preparation) this.clear();
throw error;
}
}
private static requestExclusive(scope: string): ExclusiveGameLock {
let acquired!: () => void;
let failed!: (error: Error) => void;
let release!: () => void;
const holding = new Promise<void>(resolve => { release = resolve; });
const exclusive: ExclusiveGameLock = {
scope,
acquired: new Promise<void>((resolve, reject) => { acquired = resolve; failed = reject; }),
release: () => { failed(new Error('Game preparation was cancelled.')); release(); },
};
this.exclusive = exclusive;
try {
void globalThis.navigator.locks.request(`fruit-pop:game:v1:${encodeURIComponent(scope)}`,
{ mode: 'exclusive', ifAvailable: true }, lock => {
if (this.exclusive !== exclusive) return;
if (!lock) { failed(new Error(this.LOCK_IN_USE)); return; }
acquired();
// The request promise lasts for the session lifetime, not just preparation.
return holding;
}).catch(() => { failed(new Error(this.LOCK_UNAVAILABLE)); });
} catch {
failed(new Error(this.LOCK_UNAVAILABLE));
}
return exclusive;
}
private static scopeFor(guestId: string): string {
if (typeof guestId !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(guestId)) {
throw new Error('Sign in to continue.');
}
if (typeof globalThis.crypto?.getRandomValues !== 'function') {
throw new Error('Secure game preparation is unavailable on this platform.');
}
return `${GUEST_SERVICE.origin.replace(/\/+$/, '')}|${GUEST_SERVICE.product}|${guestId}`;
}
private static restore(scope: string): GameSession {
const random = (): number => globalThis.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
try {
return new GameSession(new GameRepository(sys.localStorage, scope), random);
} catch {
// Never replace unreadable/corrupt data with a fresh balance or expose adapter errors.
throw new Error('Unable to open saved game data. Please retry. Your saved game has not been reset.');
}
}
static getSession(): GameSession {
if (this.session === null) throw new Error('Sign in to continue.');
return this.session;
}
/** An expected session prevents late loading callbacks from clearing a newer owner. */
static clear(expectedSession?: GameSession): void {
if (expectedSession !== undefined && this.session !== expectedSession) return;
this.preparation++;
this.detachCancellation?.();
this.detachCancellation = null;
this.session = null;
const exclusive = this.exclusive;
this.exclusive = null;
exclusive?.release();
}
static loadScene(): Promise<SceneAsset> {
return new Promise((resolve, reject) => {
const failed = (): void => reject(new Error('Unable to load the game. Please tap the guest button to retry.'));
try {
if (!assetManager.main) { failed(); return; }
assetManager.main.loadScene('Orchard', (error, scene) => {
if (error || !scene) failed();
else resolve(scene);
});
} catch { failed(); }
});
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "acba7323-559b-41cb-a3f0-48a0adbef15d",
"files": [],
"subMetas": {},
"userData": {}
}
+208
View File
@@ -0,0 +1,208 @@
import { _decorator, BitmapFont, Button, Component, director, Game, game, Label, Node, ResolutionPolicy, Sprite, SpriteFrame, UITransform, view } from 'cc';
import { ART_KEYS } from './OrchardAssets';
import { GameSession } from './GameSession';
import { OrchardRuntime } from './OrchardRuntime';
import { OrchardDialogs, type DialogKind } from './OrchardDialogs';
import { ReelPresentation } from './ReelPresentation';
import { BETS, type SpinResult } from './SlotsMath';
import { AutoSpinQueue } from './AutoSpinQueue';
const { ccclass, property } = _decorator;
/** 只编排输入和表现;概率、资金与存档由独立领域服务管理。 / Coordinates input and presentation; domain services own probability, money and persistence. */
@ccclass('OrchardView')
export class OrchardView extends Component {
@property({ type: [SpriteFrame] }) artFrames: SpriteFrame[] = [];
@property({ type: BitmapFont }) numerals: BitmapFont | null = null;
ready = false;
private session: GameSession | null = null;
private reels: ReelPresentation | null = null;
private dialogs: OrchardDialogs | null = null;
private readonly automatic = new AutoSpinQueue();
private get autoActive(): boolean { return this.automatic.active; }
private get autoRemaining(): number { return this.automatic.remaining; }
private wait = -1;
private hidden = false;
private fatal = false;
private frameKey = '';
private readonly listeners: { node: Node; action: () => void }[] = [];
private readonly cache = new Map<string, Node>();
onLoad(): void {
try {
if (this.artFrames.length !== ART_KEYS.length || !this.numerals) throw new Error('Game artwork is incomplete.');
this.session = OrchardRuntime.getSession();
this.reels = new ReelPresentation(this.node, key => this.art(key));
this.dialogs = new OrchardDialogs(this.node, this.session, key => this.art(key),
count => this.startAuto(count), () => this.resumeFree(), () => this.render());
this.bind('LaunchAccess', () => this.autoActive ? this.stopAuto() : this.launch());
this.bind('WagerDecrease', () => this.changeBet(-1));
this.bind('WagerIncrease', () => this.changeBet(1));
this.bind('RepeatAccess', () => this.open('repeat'));
this.bind('PreferencesAccess', () => this.open('preferences'));
this.bind('GuideAccess', () => this.open('guide'));
this.bind('GiftAccess', () => this.open('gift'));
game.on(Game.EVENT_HIDE, this.onHide, this);
game.on(Game.EVENT_SHOW, this.onShow, this);
this.reels.show(this.session.state.board);
this.fit(); this.render(); this.ready = true;
const state = this.session.state;
if (state.pending) this.present(state.pending.result);
else if (state.phase === 'free-trigger') this.dialogs.show('award');
else if (state.phase === 'free-result') this.dialogs.show('summary');
else if (state.phase === 'free-ready') this.wait = .7;
} catch {
this.fatal = true;
const notice = this.node.getChildByName('GameNotice');
if (notice) {
notice.active = true;
notice.getComponent(Label)!.string = 'Sign in to continue. Please reopen the login screen.';
notice.setSiblingIndex(this.node.children.length - 1);
}
}
}
private art(key: string): SpriteFrame {
const frame = this.artFrames[ART_KEYS.indexOf(key)];
if (!frame) throw new Error('Game artwork is unavailable.');
return frame;
}
private item(name: string): Node {
if (this.cache.has(name)) return this.cache.get(name)!;
const find = (node: Node): Node | null => {
if (node.name === name) return node;
for (const child of node.children) { const value = find(child); if (value) return value; }
return null;
};
const node = find(this.node);
if (!node) throw new Error(`Game control is missing: ${name}`);
this.cache.set(name, node); return node;
}
private bind(name: string, action: () => void): void {
const node = this.item(name); node.on(Button.EventType.CLICK, action, this); this.listeners.push({ node, action });
}
private text(name: string, amount: number): void { this.item(name).getComponent(Label)!.string = amount.toLocaleString('en-US'); }
private setInteractable(name: string, value: boolean): void { this.item(name).getComponent(Button)!.interactable = value; }
private changeBet(step: number): void {
if (!this.session || this.autoActive || this.dialogs?.opened || this.session.state.phase !== 'idle') return;
const index = (BETS as readonly number[]).indexOf(this.session.state.bet);
const bet = BETS[index + step];
if (bet !== undefined) this.act(() => this.session!.setBet(bet));
}
private launch(): void {
if (!this.session || this.fatal || this.hidden || this.dialogs?.opened) return;
const state = this.session.state;
if (state.phase !== 'idle' && state.phase !== 'free-ready') return;
if (state.phase === 'idle' && state.balance < state.bet) {
this.stopAuto(); this.dialogs?.show('empty'); return;
}
this.wait = -1;
this.act(() => {
const result = this.session!.beginSpin();
if (this.autoActive) this.automatic.consume();
if (result.awarded > 0) this.stopAuto();
this.present(result);
});
}
private present(result: SpinResult): void {
this.reels!.play(result, () => {
if (!this.isValid || !this.session) return;
this.act(() => {
this.session!.completeSpin();
const state = this.session!.state;
if (state.phase === 'free-trigger') { this.stopAuto(); this.dialogs!.show('award'); }
else if (state.phase === 'free-result') this.dialogs!.show('summary');
else if (state.phase === 'free-ready') this.wait = .9;
else if (this.autoActive && this.autoRemaining > 0) this.wait = .65;
else this.stopAuto();
if (result.win > 0 && state.settings.vibration && typeof navigator !== 'undefined' && navigator.vibrate) navigator.vibrate(45);
});
});
this.render();
}
private startAuto(count: number): void {
if (!this.session || this.session.state.phase !== 'idle' || ![10, 25, 50, 100].includes(count)) return;
this.automatic.start(count); this.launch();
}
private stopAuto(): void {
this.automatic.stop();
if (this.session?.state.phase === 'idle') this.wait = -1;
if (this.ready) this.render();
}
private resumeFree(): void {
this.render();
if (this.session?.state.phase === 'free-ready') this.wait = .5;
}
private open(kind: DialogKind): void {
if (!this.session || this.fatal || this.reels?.spinning || this.session.state.phase !== 'idle') return;
this.stopAuto(); this.dialogs?.show(kind);
}
private act(action: () => void): void {
try { action(); this.render(); }
catch { this.fatal = true; this.automatic.stop(); this.wait = -1; this.dialogs?.error('Unable to save game progress. Tap OK to return to login and safely restore your saved round.', true); }
}
private render(): void {
if (!this.session) return;
const state = this.session.state;
const bonus = !!state.free && (state.pending?.free === true || state.phase !== 'spinning');
const automated = this.autoActive && !bonus;
this.item('NormalPrize').active = !bonus;
this.item('RoundsRibbon').active = bonus || automated;
this.item('BonusPrize').active = bonus;
this.item('NormalPrize').setPosition(0, 0, 0);
const prizeY = automated ? -442 : -327;
this.item('NormalPrizePlate').setPosition(0, prizeY, 0);
this.item('NormalPrizePlate').getComponent(UITransform)!.setContentSize(automated ? 610 : 712, automated ? 120 : 153);
this.item('NormalPrizeTitle').setPosition(-160, prizeY, 0);
this.item('NormalPrizeAmount').setPosition(101, prizeY, 0);
this.item('NormalPrizeAmount').getComponent(Label)!.fontSize = automated ? 84 : 108;
this.item('WagerControls').setPosition(0, bonus || automated ? -582 : -500, 0);
this.item('WagerPlate').getComponent(UITransform)!.setContentSize(773, bonus || automated ? 110 : 139);
this.item('WagerDecrease').getComponent(UITransform)!.setContentSize(bonus || automated ? 100 : 126, bonus || automated ? 81 : 102);
this.item('WagerIncrease').getComponent(UITransform)!.setContentSize(bonus || automated ? 102 : 128, bonus || automated ? 81 : 102);
this.item('RoundsHeading').getComponent(Sprite)!.spriteFrame = this.art(bonus ? 'bonus-heading' : 'repeat-heading');
this.text('RoundsCount', bonus ? state.free!.remaining : this.autoRemaining);
this.text('WalletAmount', state.balance);
this.text('NormalPrizeAmount', state.lastWin);
this.text('RoundPrizeAmount', state.lastWin);
this.text('BonusPrizeAmount', state.free?.total ?? 0);
this.text('WagerAmount', state.free?.bet ?? state.bet);
const idle = state.phase === 'idle' && !this.reels?.spinning && !this.fatal;
this.setInteractable('WagerDecrease', idle && !this.autoActive && state.bet > BETS[0]);
this.setInteractable('WagerIncrease', idle && !this.autoActive && state.bet < BETS[BETS.length - 1]);
this.item('RepeatAccess').active = !bonus && !automated;
this.setInteractable('RepeatAccess', idle && !automated);
this.setInteractable('LaunchAccess', !this.fatal && (automated || idle) && !bonus);
const spinSprite = this.item('LaunchAccess').getComponent(Sprite)!;
spinSprite.spriteFrame = this.art(automated ? 'halt-orb' : bonus || !idle ? 'resting-orb' : 'launch-orb');
this.item('LaunchAccess').setPosition(0, bonus || automated ? -795 : -754, 0);
this.item('LaunchAccess').getComponent(UITransform)!.setContentSize(bonus || automated ? 312 : 342, bonus ? 300 : automated ? 312 : 341);
for (const key of ['PreferencesAccess', 'GuideAccess', 'GiftAccess']) this.setInteractable(key, idle && !automated);
}
update(dt: number): void {
this.fit();
if (!this.ready || this.fatal || this.hidden) return;
this.reels?.update(dt); this.dialogs?.tick();
if (this.wait >= 0 && !this.reels?.spinning && !this.dialogs?.opened) {
this.wait -= Math.min(.1, Math.max(0, dt));
if (this.wait <= 0) { this.wait = -1; this.launch(); }
}
}
private fit(): void {
const frame = view.getFrameSize();
if (frame.width <= 0 || frame.height <= 0) return;
const key = `${frame.width}:${frame.height}`;
if (key === this.frameKey) return;
this.frameKey = key;
view.setDesignResolutionSize(1080, 1920, frame.height / frame.width < 1920 / 1080 ? ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.FIXED_WIDTH);
const size = view.getVisibleSize(); this.node.getComponent(UITransform)?.setContentSize(size);
const cover = Math.max(size.width / 1080, size.height / 1920);
this.node.getChildByName('OrchardScenery')?.setScale(cover, cover, 1);
}
private onHide(): void { this.hidden = true; this.stopAuto(); }
private onShow(): void { this.hidden = false; }
onDisable(): void { this.stopAuto(); }
onDestroy(): void {
this.dialogs?.dispose();
if (this.session) OrchardRuntime.clear(this.session);
game.off(Game.EVENT_HIDE, this.onHide, this); game.off(Game.EVENT_SHOW, this.onShow, this);
for (const { node, action } of this.listeners) if (node.isValid) node.off(Button.EventType.CLICK, action, this);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "e5e86556-b5d7-4a48-adf3-784c97f1c904",
"files": [],
"subMetas": {},
"userData": {}
}
@@ -0,0 +1,82 @@
import { Color, Graphics, Node, Sprite, SpriteFrame, UITransform } from 'cc';
import { PAYLINES, SYMBOLS, type SpinResult, type SymbolId } from './SlotsMath';
import { SYMBOL_ART } from './OrchardAssets';
/** 动画只展示已提交的结果,不参与随机或金币结算。 / Animation presents committed outcomes without generating or settling them. */
export class ReelPresentation {
private elapsed = 0;
private result: SpinResult | null = null;
private completed: (() => void) | null = null;
private highlight = 0;
private readonly cells: Sprite[][];
private readonly lines: Graphics;
constructor(private readonly root: Node, private readonly art: (key: string) => SpriteFrame) {
this.cells = Array.from({ length: 5 }, (_, c) => Array.from({ length: 6 }, (_, r) =>
root.getChildByPath(`ReelWindow${c}/Cell${r}`)!.getComponent(Sprite)!));
this.lines = root.getChildByName('WinningLines')!.getComponent(Graphics)!;
}
get spinning(): boolean { return this.result !== null; }
show(board: SymbolId[][]): void {
for (let c = 0; c < 5; c++) for (let r = 0; r < 6; r++) {
this.symbol(this.cells[c][r], board[c][r % 3]);
this.cells[c][r].node.setPosition(0, 230 - r * 230, 0);
}
}
play(result: SpinResult, done: () => void): void {
this.result = result; this.completed = done; this.elapsed = 0; this.highlight = 0;
this.lines.clear();
}
update(dt: number): void {
if (!Number.isFinite(dt)) return;
dt = Math.min(.1, Math.max(0, dt));
if (!this.result) { if (this.highlight > 0) this.highlight -= dt; return; }
this.elapsed += dt;
for (let c = 0; c < 5; c++) {
const stop = .65 + c * .16;
if (this.elapsed >= stop) {
for (let r = 0; r < 6; r++) {
this.symbol(this.cells[c][r], this.result.board[c][r % 3]);
const bounce = this.elapsed < stop + .18 ? Math.sin((this.elapsed - stop) / .18 * Math.PI) * 9 : 0;
this.cells[c][r].node.setPosition(0, 230 - r * 230 + bounce, 0);
}
} else {
const distance = this.elapsed * (1400 + c * 90);
for (let r = 0; r < 6; r++) {
const y = 460 - ((distance + r * 230) % 1380);
this.cells[c][r].node.setPosition(0, y, 0);
const cycle = Math.floor((distance + r * 230) / 1380);
this.symbol(this.cells[c][r], SYMBOLS[(cycle * 6 + r + c * 3) % SYMBOLS.length]);
}
}
}
if (this.elapsed >= 1.55) {
const result = this.result, done = this.completed;
this.result = null; this.completed = null;
this.show(result.board); this.mark(result); done?.();
}
}
private symbol(sprite: Sprite, symbol: SymbolId): void {
const frame = this.art(SYMBOL_ART[symbol]);
sprite.spriteFrame = frame;
const size = frame.originalSize;
const scale = Math.min(198 / size.width, 212 / size.height);
sprite.getComponent(UITransform)!.setContentSize(size.width * scale, size.height * scale);
}
private mark(result: SpinResult): void {
this.lines.clear();
this.lines.strokeColor = new Color(255, 229, 113, 235); this.lines.lineWidth = 5;
for (const win of result.wins) {
const line = PAYLINES[win.line];
line.slice(0, win.count).forEach((row, col) => {
const x = -410 + col * 205, y = 375 - row * 230;
if (col === 0) this.lines.moveTo(x, y); else this.lines.lineTo(x, y);
});
this.lines.stroke();
}
if (result.wildColumn !== null) {
this.lines.strokeColor = new Color(64, 255, 212, 220);
this.lines.roundRect(-510 + result.wildColumn * 205, -200, 199, 690, 24); this.lines.stroke();
}
this.highlight = 1.2;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "d2c75eb4-c069-448e-a690-b60dbddd1193",
"files": [],
"subMetas": {},
"userData": {}
}
+125
View File
@@ -0,0 +1,125 @@
/** Symbol identifiers are independent of the artwork used to display them. */
export const SYMBOLS = Object.freeze([
'seven', 'bell', 'bar', 'strawberry', 'blueberry', 'plum', 'cherry', 'watermelon', 'wild', 'scatter',
] as const);
export type SymbolId = typeof SYMBOLS[number];
export type OrdinarySymbol = Exclude<SymbolId, 'wild' | 'scatter'>;
export const BETS = Object.freeze([1000, 2000, 5000, 10000, 20000, 50000] as const);
export const PAYTABLE = Object.freeze({
seven: Object.freeze([45, 158, 675] as const),
bell: Object.freeze([36, 113, 450] as const),
bar: Object.freeze([27, 90, 360] as const),
strawberry: Object.freeze([18, 54, 203] as const),
blueberry: Object.freeze([14, 45, 158] as const),
plum: Object.freeze([9, 27, 90] as const),
cherry: Object.freeze([5, 18, 68] as const),
watermelon: Object.freeze([5, 14, 45] as const),
});
export const PAYLINES: readonly (readonly number[])[] = Object.freeze([
'MMMMM', 'TTTTT', 'BBBBB', 'TMBMT', 'BMTMB', 'MTTTM', 'MBBBM', 'MTBTM', 'MBTBM', 'TMMMT',
'BMMMB', 'TTMMB', 'BBMMT', 'TMMBB', 'BMMTT', 'MTMMM', 'MBMMM', 'MMMTM', 'MMMBM', 'MTMBM',
].map(line => Object.freeze([...line].map(row => ({ T: 0, M: 1, B: 2 })[row as 'T' | 'M' | 'B']))));
export interface LineWin {
/** Zero-based index into PAYLINES. */
line: number;
count: number;
symbol: OrdinarySymbol;
amount: number;
}
export interface SpinResult {
/** Column-major board: board[column][row]. */
board: SymbolId[][];
wins: LineWin[];
win: number;
scatters: number;
awarded: number;
wildColumn: number | null;
}
const WEIGHTS = [3, 5, 7, 10, 11, 13, 15, 30, 2, 4] as const;
const ORDINARY = SYMBOLS.slice(0, 8) as OrdinarySymbol[];
export function assertBet(bet: unknown): asserts bet is number {
if (typeof bet !== 'number' || !(BETS as readonly number[]).includes(bet)) {
throw new Error('Unsupported total bet');
}
}
export function assertBoard(board: unknown): asserts board is SymbolId[][] {
if (!Array.isArray(board) || board.length !== 5) throw new Error('Board must have five columns');
for (let column = 0; column < 5; column++) {
const cells: unknown = board[column];
if (!Array.isArray(cells) || cells.length !== 3) throw new Error('Board must have three rows');
for (let row = 0; row < 3; row++) {
if (!(SYMBOLS as readonly unknown[]).includes(cells[row])) throw new Error('Unknown symbol');
}
}
}
/** Evaluate every ordinary-symbol candidate, then pay only the highest award on each line. */
export function evaluate(board: readonly (readonly SymbolId[])[], bet: number): SpinResult {
assertBet(bet);
assertBoard(board);
const snapshot = board.map(column => column.slice());
const wins: LineWin[] = [];
for (let line = 0; line < PAYLINES.length; line++) {
const rows = PAYLINES[line];
let best: LineWin | null = null;
for (const symbol of ORDINARY) {
let count = 0;
while (count < 5 && (snapshot[count][rows[count]] === symbol || snapshot[count][rows[count]] === 'wild')) count++;
if (count < 3) continue;
const amount = bet / PAYLINES.length * PAYTABLE[symbol][count - 3];
if (best === null || amount > best.amount) best = { line, count, symbol, amount };
}
if (best !== null) wins.push(best);
}
const scatters = snapshot.reduce((total, column) => total + column.filter(symbol => symbol === 'scatter').length, 0);
return {
board: snapshot,
wins,
win: wins.reduce((total, award) => total + award.amount, 0),
scatters,
awarded: scatters < 3 ? 0 : scatters === 3 ? 8 : scatters === 4 ? 12 : 16,
wildColumn: null,
};
}
function draw(random: () => number): number {
const value = random();
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value >= 1) {
throw new Error('Random samples must be finite numbers in [0, 1)');
}
return value;
}
function drawSymbol(random: () => number): SymbolId {
const sample = draw(random);
let upper = 0;
for (let index = 0; index < SYMBOLS.length; index++) {
upper += WEIGHTS[index];
if (sample < upper / 100) return SYMBOLS[index];
}
throw new Error('Invalid symbol weights');
}
/** Fifteen independent column-major draws; a free round consumes one additional column draw. */
export function spin(bet: number, free: boolean, random: () => number = Math.random): SpinResult {
assertBet(bet);
if (typeof free !== 'boolean') throw new Error('Invalid free-spin flag');
const board = Array.from({ length: 5 }, () => Array.from({ length: 3 }, () => drawSymbol(random)));
const wildColumn = free ? Math.floor(draw(random) * 5) : null;
if (wildColumn !== null) {
board[wildColumn] = board[wildColumn].map(symbol => symbol === 'scatter' ? symbol : 'wild');
}
const result = evaluate(board, bet);
result.wildColumn = wildColumn;
if (free) result.awarded = 0;
return result;
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "2e34a161-68c8-4fbd-a503-d1a78dfcb7e9",
"files": [],
"subMetas": {},
"userData": {}
}