13 KiB
13 KiB
Findings
Last Updated: 2026-04-09T00:00:00.000Z
Summary
Initializer refresh for SCOPONE-0009. The cached findings were stale relative to the live source tree, so the observations below reflect the current Phaser, worker, and AI implementation.
Codebase Observations
- Primary gameplay code currently lives in 10 TypeScript source files under
src/; the Android wrapper adds 3 Java files. - The project is structurally split between framework-free gameplay modules in
src/game/and Phaser scene code insrc/scenes/. src/scenes/GameScene.tsandsrc/game/ai.tsremain the two largest concentrations of application logic.- The AI transport layer is now a stable three-file path:
ai-worker-protocol.ts,ai-worker-client.ts, andai.worker.ts. - The AI exposes three difficulty levels:
beginner,advanced, andmaster. advancedandmasterboth useCardTrackerto reason about unseen cards without directly reading hidden hands.- The current
mastersearch profile istimeBudgetMs: 4600,sampleCount: 10,maxDepth: 6,batchSize: 2. GameSceneconsumes AI progress callbacks to update an on-screen think bar while a worker request is running.AIWorkerClientfails over pending work to in-threadchooseMove()if worker creation, posting, or deserialization fails.- The Android wrapper targets SDK 36 with
minSdkVersion24 and applies immersive mode from the native activity. - Audio remains procedural via Web Audio; no dedicated audio asset pipeline is present in the source tree.
- No ESLint or Prettier configuration is present.
- The only repository-wide verification command supplied is
npx tsc --noEmit.
Potential Improvement Areas
GameScene.tsstill centralizes layout, turn flow, HUD updates, effects, and audio in one scene class, which raises maintenance cost.ai.tsstill combines heuristic tiers, inference helpers, determinization, and alpha-beta evaluation in one module.- Worker transport is isolated cleanly, but progress rendering remains coupled to scene-level UI concerns.
- A 4600 ms master search budget may still be noticeable on slower mobile devices even with batch yielding.
- There is no dedicated automated rules or AI test suite beyond type-checking.
- Formatting and style are enforced socially rather than by automated linting or formatting tools.
Current Rule / Implementation Notes
Capture behavior in engine.ts
- Direct-match capture has priority over subset-sum capture.
- When multiple direct matches exist,
findCaptures()returns one single-card option per matching card. - Subset-sum captures are considered only when no direct match exists.
applyMove()defaults to the first legal capture if no explicit capture choice is supplied.- Scope is awarded only when a capture clears the table before the final play of the round.
AI implementation snapshot
beginneruses a simpler heuristic with noise to remain beatable.advancedadds race awareness, anti-scopa logic, partner setup, anchor play, and tracker-based probability estimates.masterorders legal moves with a quick evaluator, samples hidden hands, and scores them with alpha-beta search under the active deadline.- Progress is reported through
AIDecisionProgressso the scene can keep the think bar responsive.
Worker execution snapshot
GameScenecreatesAIWorkerClientduringcreate()and disposes it on bothshutdownanddestroy.AIWorkerClientserializesCardTrackerstate throughtoSnapshot()instead of attempting to transfer the class instance.ai.worker.tsrebuilds tracker state withCardTracker.fromSnapshot()before callingchooseMove().- Progress, result, and serialized error payloads all travel through
ai-worker-protocol.ts. - If worker execution becomes unavailable, pending requests are rerun with the in-thread AI path rather than being dropped.
Scene / UI implementation snapshot
BootSceneloads atlas assets and presents a simple loading bar.MenuSceneexposes difficulty selection before match start.GameScenetracks played and captured cards inCardTrackeras the round evolves.- The scene owns score HUD rendering, player labels, status text, think-bar rendering, and procedural particle effects.
- Round-end and match-end flows remain managed inside the scene instead of separate overlay components.
Research Performed
Web Research: Scopone Scientifico Rules (2026-03-31)
Sources: Wikipedia (Scopa article, Scopone section), Pagat.com (Scopone page by John McLeod)
Core Rules (Scopone Scientifico variant)
- 4 players, 2 fixed teams of 2 (sit opposite): Team A = players 0+2, Team B = players 1+3.
- 40-card Napoletane deck: 4 suits (
bastoni,coppe,denara,spade), values 1-10. - All 40 cards are dealt at the start of the round; the table begins empty.
- Turns advance in the implementation as
0 -> 1 -> 2 -> 3.
Capture Rules
- If the played card matches one or more table cards by value, a direct match must be taken.
- If multiple direct matches exist, one matching table card is chosen.
- If no direct match exists, a subset of table cards may be captured when their values sum to the played value.
- A direct match has priority over any possible sum capture.
- Scopa awards a point only when the table is cleared before the final play of the round.
Scoring
| Category | Rule |
|---|---|
| Carte | Majority of captured cards |
| Denari | Majority of denara suit cards |
| Settebello | Team that captures the 7 of denara |
| Primiera | Highest best-of-each-suit prime value |
| Scope | One point per scopa |
Primiera values used in code
| Card value | Primiera value |
|---|---|
| 7 | 21 |
| 6 | 18 |
| 1 | 16 |
| 5 | 15 |
| 4 | 14 |
| 3 | 13 |
| 2 | 12 |
| 8, 9, 10 | 10 |
SCOPONE-0008: AI progress rendering notes (2026-04-02)
- The current implementation does not use Phaser
TimerEventprogress helpers. - Instead,
chooseMove()emits its own normalized progress payload throughAIDecisionProgress. GameScene.updateThinkBar()renders remaining time from that callback.- The yielding behavior in the master search path is necessary so the browser can repaint while search batches continue.
SCOPONE-0009: Phaser scene lifecycle notes (2026-04-08)
- Source: Context7
/websites/phaser_io_api-documentation, queryPhaser 3.87 Scene lifecycle create restart shutdown destroy event listeners scene restart preserving external state. - Phaser dispatches
shutdownwhen a scene stops being active but may be re-used later; resource cleanup that should also cover final teardown can additionally listen todestroy. - The current
GameScenepattern of registering one-shot shutdown and destroy handlers is aligned with Phaser guidance for worker disposal and UI cleanup. - Dealer rotation and next-round state changes can stay inside the existing in-scene orchestration without requiring a different Phaser lifecycle primitive.
SCOPONE-0009: Iteration 3 strength-planning notes (2026-04-08)
src/game/ai.tscurrently generates master determinization samples by uniformly shuffling all unseen cards and slicing them into opponents' hidden hands; it does not yet bias assignments by dealer role, parity residue, or observed capture semantics.- The transposition-table key in
src/game/ai.tsincludes the exact sampled hidden hands, so reuse is effective within a determinized sample but does not merge equivalent uncertainty classes across different sample assignments. - No executable benchmark harness or AI quality test module exists under
src/; the current timing evidence lives only in prompt artifacts such asprompts/SCOPONE-0009/iteration_2/benchmark_summary.md. tsconfig.jsonincludes onlysrc, so any automated quality or self-play harness that should be typechecked by the defaultnpx tsc --noEmitcommand needs to live undersrc/unless the project configuration changes.
SCOPONE-0009: Iteration 3 continuation notes (2026-04-09)
- The accepted iteration 3 benchmark work is now present in source:
src/game/ai-benchmark.tsandsrc/game/ai-benchmark-fixtures.tsexist undersrc/,package.jsonexposesbenchmark:ai-quality, and the harness already measures fixed fixtures, self-play, and production-master timing. - The live production master budgets in
src/game/ai.tsare already below the requested five-second ceiling in every shipped branch: base4300,<= 20 cards4350,<= 12 cards4200,<= 8 cards3900,<= 6 cards3600, and<= 4 cards3200milliseconds. src/scenes/GameScene.tsstill executes AI turns immediately afterawait aiClient.chooseMove(...)resolves indoAIMove(); there is currently no scene-level minimum think-time floor.src/scenes/GameScene.tsstill uses a baresetStatus(msg)helper that only callsthis.statusText.setText(msg); there is no timed persistence policy, no cancellation of prior status timers, and no dedicated post-move outcome message path.- Phaser 3.87 scene timers can be cancelled with
TimerEvent.remove()and their references cleaned withTimerEvent.destroy(); the current scene already listens toshutdownanddestroy, so timed status cleanup belongs in the existinghandleSceneShutdown()path.
SCOPONE-0009: Iteration 3 refresh notes (2026-04-09)
- The current
src/game/ai.tsheuristic does not reason about numeric even/odd card values; it already computes the unseen copy count for each rank and stores whether the remaining copies for that rank are in a singleton residue or a paired residue, but the internal names still useoddResidue,evenResidue, andscoreParityTableState, which can mislead future work. - The live tactical seam that needs refresh is therefore naming and policy framing, not a wholesale replacement of the underlying signal: the AI should explicitly treat
apparigliare/sparigliareas preserving or breaking same-rank copy residues and connect that to table control, scopa prevention, and forced replies. - The accepted benchmark harness in
src/game/ai-benchmark.tsstill measures runtime withperformance.now()and therefore depends on wall-clock search time. It does not yet use an injected or simulated search clock for fast validation runs. src/scenes/GameScene.tsalready contains the previously planned pacing and status work:AI_MIN_THINK_MS = 1000,MOVE_OUTCOME_STATUS_MS = 2000, a timer-backedsetStatus(...), andhandleSceneShutdown()timer cleanup are all present in source and should be preserved rather than re-planned.src/game/ai-benchmark-fixtures.tsstill contains one fixture and tag using the stale labeldealer-parity-preserve-pair/critical-dealer-parity; if benchmark files are reopened for simulated timing, that terminology should be refreshed to rank-residue wording at the same time.
SCOPONE-0009: Iteration 5 planning notes (2026-04-09)
- The live AI quality harness in
src/game/ai-benchmark.tsstill hard-codes aniteration: 4quality gate with targets of12fixed fixtures,4critical concepts, and48self-play matches requiring>= 30wins and<= 12losses; the readable summary does not yet surface cross-seed aggregation such as the recurring dual-loss seeds from the latest rejected run. src/game/ai-benchmark-fixtures.tscurrently coverssettebello-capture,anti-scopa-defense,dealer-rank-residue-preservation, andexact-endgame-resolutionas critical concepts, but it does not yet encode an explicit critical fixture for partner invitation / partner scopa setup and does not yet makefare scopaitself a critical concept despite the user's new ordering.- Non-critical fixtures already exist for denari pressure, late denari shielding, and seven pressure, so the benchmark seam for iteration 5 is to rebalance critical-vs-fixed coverage and ordering expectations rather than to introduce a second harness.
- Cross-tier heuristic priorities are concentrated in
src/game/ai.ts: beginner logic inscoreCaptureBeginner()/scoreDumpBeginner(), advanced logic inscoreCaptureAdv()/scoreDumpAdv(), and master root/search logic inquickEval(),orderSearchMoves(),generateSamples(), andevaluateFast(). - Partner-aware logic already exists in all three tiers, but it is currently additive and distributed across multiple heuristics; there is no single explicit priority ladder that guarantees
partner setupoutranks seven denial, denari denial, and generic material capture across the whole file. - Anti-scopa prevention is already strong enough to pass the fixed tactical fixtures, but the rejected iteration 4 result (
18wins,30losses over48seeded self-play matches) indicates that full-game strength is still limited by strategic continuity across seed-intrinsic lines rather than by isolated tactical blindness.