Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aa2a021712 | |||
| 6037596cc0 | |||
| d7ffb16df5 | |||
| b57db017d3 | |||
| 0b3140ad6d | |||
| e41def8c89 | |||
| aad8bb9c83 | |||
| 55c235b55f | |||
| 21ec03b157 | |||
| 17e3112502 | |||
| de4751115f | |||
| 9ff48ace5b | |||
| 91b7605b9f | |||
| 42d90b199c | |||
| 3e11e9e79a | |||
| bfcd05fbb5 | |||
| c497c3193c | |||
| 9aa0dd23b1 | |||
| d065d49fe7 | |||
| c30b04ec72 | |||
| 40d6e0ab17 | |||
| 9fe650fa20 | |||
| b73d246b4c | |||
| ae40a1db7a | |||
| b7c3a4996f | |||
| d48b9489db | |||
| 08b006ff30 | |||
| 17e0737a10 | |||
| dd63261999 | |||
| 93660c2217 | |||
| 56e2e6f151 | |||
| cc635328be | |||
| a4bc063497 | |||
| 540869c851 | |||
| bdac754b26 | |||
| f863d85c35 | |||
| 3c7a0eb4fb | |||
| d489e7a31b | |||
| f2f30c8002 | |||
| a49a340a30 |
+2
-3
@@ -47,11 +47,10 @@ Solitaire Quest is a cross-platform Klondike Solitaire game written in Rust, tar
|
||||
### Design Principles
|
||||
|
||||
- **Offline first.** The local file is always the source of truth. Sync is additive, never destructive.
|
||||
- **Pure core.** All game logic lives in a dependency-free Rust crate with no Bevy, no network, and no I/O. This keeps it fully unit-testable and portable.
|
||||
- **No panics in game logic.** Every state transition returns `Result<_, MoveError>`. Panics are only acceptable in startup/configuration code.
|
||||
- **One language, one repo.** The game client, sync client, shared types, and sync server are all Rust crates in a single Cargo workspace.
|
||||
- **Plugin-based Bevy architecture.** Each major feature is a Bevy `Plugin`. Systems are small and single-purpose. Cross-system communication uses Bevy `Event`s.
|
||||
- **UI-first interaction.** Every player-triggered action — new game, undo, draw, pause, open stats / settings / help / profile / leaderboard, etc. — must be reachable from a visible UI control. Keyboard shortcuts exist only as optional accelerators for power users; they are never the sole entry point. A player using only mouse or touch must be able to perform every action. New gameplay features ship with the UI control alongside the system that backs it.
|
||||
|
||||
Pure-core, no-panics-in-game-logic, and UI-first-interaction constraints are enforced by CLAUDE.md §2.1, §2.3, and §3.3 respectively — those are the canonical statements; this file describes the design that motivates them.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+315
@@ -8,6 +8,321 @@ project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
_Nothing yet._
|
||||
|
||||
## [0.19.0] — 2026-05-06
|
||||
|
||||
Closes the v0.18.0 punch list (items B and D — async hint and
|
||||
persistent replay share URLs), expands desktop platform fit
|
||||
(Wayland session support + monitor-aware default window size for
|
||||
HiDPI / 4K displays), polishes the win-celebration and
|
||||
double-click animation paths, and clears two test-flake
|
||||
contributors. A short-lived "Rusty Pixel" pixel-art card theme
|
||||
was prototyped and reverted in the same window — the engine
|
||||
plumbing it touched (`pixel_art` field on `ThemeMeta`, PNG
|
||||
manifest face support, second `embedded://` theme channel) was
|
||||
fully reverted and is not part of this release.
|
||||
|
||||
### Changed
|
||||
|
||||
- **H-key hint runs on `AsyncComputeTaskPool`** (`3e11e9e`). The
|
||||
synchronous `try_solve_from_state` call on every H press is gone;
|
||||
`handle_keyboard_hint` now spawns a task whose result the new
|
||||
`pending_hint::poll_pending_hint_task` system surfaces one frame
|
||||
later. New `PendingHintTask` resource carries the in-flight handle
|
||||
plus `move_count_at_spawn` for staleness detection;
|
||||
`drop_pending_hint_on_state_change` cancels the task whenever the
|
||||
game state shifts; `PendingHintTask::spawn` implements
|
||||
cancel-on-replace so two quick H presses keep at most one task in
|
||||
flight. Mirrors the v0.18.0 `PendingNewGameSeed` template.
|
||||
`emit_hint_visuals` and `find_heuristic_hint` are extracted as
|
||||
`pub` helpers so the polling system can call them.
|
||||
- **Persistent replay share URLs** (`42d90b1`). v0.18.0's
|
||||
`LastSharedReplayUrl` was an in-memory resource wiped on quit —
|
||||
the player had to share within the session of the win.
|
||||
`solitaire_data::Replay` now carries a `share_url: Option<String>`
|
||||
field with `#[serde(default)]` (no `REPLAY_SCHEMA_VERSION` bump
|
||||
needed; older `replays.json` files load unchanged with `share_url
|
||||
== None` on every entry). `poll_replay_upload_result` writes the
|
||||
resolved URL into `replays[0].share_url` and persists the updated
|
||||
history via `save_replay_history_to`. The Stats overlay's
|
||||
"Copy share link" button reads from
|
||||
`history.0.replays[selected.0].share_url`, so the Prev/Next
|
||||
selector's currently-displayed replay drives the clipboard
|
||||
contents — each historical win keeps its own URL.
|
||||
`LastSharedReplayUrl` removed (its role is now subsumed by the
|
||||
`share_url` field on the replay record).
|
||||
|
||||
### Added
|
||||
|
||||
- **Wayland session support** (`b57db01`). The workspace
|
||||
`Cargo.toml` Bevy feature list now enables `wayland` alongside
|
||||
`x11`. winit prefers Wayland when `WAYLAND_DISPLAY` is set on the
|
||||
session, falling back to X11 when it isn't. Pre-fix, a Wayland
|
||||
desktop environment fell through to XWayland, rendering the
|
||||
game inside an X11 frame stitched into the Wayland compositor.
|
||||
Post-fix, the game opens as a native Wayland surface. Costs a
|
||||
few hundred KB of binary for the libwayland-client bindings;
|
||||
cross-distro friendly because winit dlopen-probes the libraries
|
||||
rather than hard-linking them.
|
||||
- **Monitor-relative default window size** (`b57db01`). On launches
|
||||
with no saved geometry, the new
|
||||
`apply_smart_default_window_size` Update system queries
|
||||
`Monitor` (with the `PrimaryMonitor` marker) and resizes the
|
||||
primary window to ~70 % of the monitor's *logical* size on the
|
||||
first frame. Before, every fresh launch opened at 1280×800
|
||||
regardless of monitor; on a 4K monitor that's a comparatively
|
||||
tiny window in one corner. Logical size already accounts for
|
||||
the OS's HiDPI scale factor, so a Retina display reporting
|
||||
scale_factor 2.0 yields the same physical inches as a 1080p
|
||||
display reporting 1.0. Skipped entirely when saved geometry was
|
||||
applied — the player's chosen size always wins.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Duplicate "You Win" toast on game-won** (`55c235b`). The
|
||||
post-win UI was firing two celebration surfaces: a 4-second
|
||||
toast banner ("You Win! Score: X Time: Y") on top of the
|
||||
`win_summary_plugin`'s "You Won!" modal. In screenshots the
|
||||
toast banner was partially clipped behind the modal card,
|
||||
peeking out on either side. The toast predated the modal and is
|
||||
strictly subsumed by it; removed. The cards-fly-off cascade
|
||||
animation (`MotionCurve::Expressive` per-card rotation drift)
|
||||
is unchanged — that's the visual celebration, distinct from
|
||||
the textual celebration the modal owns. `WIN_TOAST_SECS` const
|
||||
removed.
|
||||
- **Double-click on a single card with no destination now plays
|
||||
the reject animation** (`d7ffb16`). `handle_double_click` only
|
||||
fired `MoveRejectedEvent` for multi-card stacks with no
|
||||
destination; a double-click on a single card whose top didn't
|
||||
fit any foundation or tableau slot produced zero feedback —
|
||||
no `card_invalid.wav`, no source-pile shake. Both priorities'
|
||||
failure paths now converge on a single rejection at the end of
|
||||
the double-click branch, so single-card and stack misses get
|
||||
the same feedback shape as drag-and-drop rejections.
|
||||
- **Double-click move animation no longer plays twice**
|
||||
(`6037596`). On a successful double-click, the slide-to-
|
||||
destination animation rendered twice — once from the move's
|
||||
`StateChangedEvent` landing, then again from the release's
|
||||
`end_drag` firing a redundant `StateChangedEvent` mid-slide.
|
||||
`sync_cards_on_change` saw the card mid-CardAnim (`cur ≠
|
||||
target`) and replaced the in-flight tween with a fresh one
|
||||
starting at the mid-position, visibly restarting the slide. The
|
||||
defensive `StateChangedEvent` write in `end_drag`'s
|
||||
uncommitted-drag branch is removed; `start_drag` only mutates
|
||||
`DragState` (never card transforms), so an uncommitted drag
|
||||
has no visual side effect to undo. The committed-drag branch
|
||||
keeps its `StateChangedEvent` since real drag snap-backs do
|
||||
need a resync.
|
||||
- **`auto_save_writes_after_30_seconds` test flake** (`91b7605`).
|
||||
The test's single-frame `app.update()` was sensitive to
|
||||
first-frame `Time::delta_secs()` variance under heavy parallel
|
||||
cargo-test load, and to production-disk
|
||||
`~/.local/share/solitaire_quest/game_state.json` state leaking
|
||||
into the test world via `GamePlugin::build`'s load path.
|
||||
`test_app` now resets `PendingRestoredGame(None)` after plugin
|
||||
build (preventing the dev machine's saved-game state from
|
||||
tripping the auto-save guard) and the test re-arms the timer in
|
||||
a small bounded loop until the file appears (robust against
|
||||
first-frame Time variance). No production-code change.
|
||||
|
||||
### Stats
|
||||
|
||||
- 1170 passing tests (was 1166 at v0.18.0 close — net +4 from
|
||||
the persistent share URL backwards-compat test, the three
|
||||
async-hint tests, minus the dropped synchronous hint tests).
|
||||
- Zero clippy warnings under `--workspace --all-targets -- -D warnings`.
|
||||
|
||||
## [0.18.0] — 2026-05-06
|
||||
|
||||
The launch-experience round. The engine used to drop the player on a
|
||||
silent default Classic deal whether they had unfinished work or not;
|
||||
v0.18.0 replaces that with two stacked decision points — a Restore
|
||||
prompt for in-progress saves, then an MSSC-style Home / mode picker
|
||||
that surfaces Daily / Zen / Challenge / Time Attack as picture tiles
|
||||
with live stats. The same round closes the last solver-on-main-thread
|
||||
hot path (winnable-only seed selection moves to
|
||||
`AsyncComputeTaskPool`), wires "Copy share link" into Stats, lights a
|
||||
"Won before" HUD chip on re-deals of beaten seeds, and tidies the
|
||||
unified-3.0 rule set across CLAUDE.md / CLAUDE_SPEC.md /
|
||||
CLAUDE_WORKFLOW.md / CLAUDE_PROMPT_PACK.md.
|
||||
|
||||
### Added
|
||||
|
||||
- **Restore prompt on launch** (`3c7a0eb`). When `game_state.json`
|
||||
holds an in-progress game (`move_count > 0`, not won), the engine
|
||||
now seeds `GameStateResource` with a fresh deal and holds the saved
|
||||
game in a new `PendingRestoredGame` resource. After the splash
|
||||
clears, a "Welcome back" modal offers **Continue** (Enter / C /
|
||||
click) or **New game** (N / click). Fresh-deal saves
|
||||
(`move_count == 0`) skip the prompt and load directly.
|
||||
- **Save preservation while the prompt is unanswered** (`f863d85`).
|
||||
Both `save_game_state_on_exit` and `auto_save_game_state` consult
|
||||
`PendingRestoredGame` first: if it still holds a pending saved
|
||||
game, that's what gets persisted (or the auto-save is skipped),
|
||||
so exiting before answering the prompt no longer overwrites the
|
||||
meaningful save with the placeholder fresh deal.
|
||||
- **Home / mode picker auto-shows on launch** (`dd63261`). The mode
|
||||
picker was only reachable via **M** during gameplay; players who
|
||||
hadn't discovered the hotkey never saw the Daily / Zen / Challenge
|
||||
/ Time Attack entry points after the splash cleared. `HomePlugin`
|
||||
gains an `auto_show_on_launch` flag (default true) and a
|
||||
one-shot `LaunchHomeShown` gate. Skips when the Restore prompt is
|
||||
on screen so Welcome-back still takes precedence.
|
||||
- **MSSC-style Home picker — header / chips / score chips / draw
|
||||
mode** (`ae40a1d`). Player-stats header strip (Level / XP /
|
||||
Lifetime Score, compact-formatted as `1.2M` / `12.3K` / `1,234`)
|
||||
acts as a clickable shortcut to Profile. Draw-mode chip row above
|
||||
the mode cards lets the player flip Draw 1 / Draw 3 from the
|
||||
picker itself; persists `settings.json` and respawns the modal so
|
||||
the active state repaints cleanly. Per-mode best-score / streak
|
||||
chips on each card; hidden on a 0 best so a fresh profile doesn't
|
||||
read "Best 0" everywhere.
|
||||
- **Today's Event callout on the Daily card** (`b73d246`). "Today,
|
||||
May 6" date line plus the server-fetched goal (when SyncPlugin is
|
||||
wired). Once today's daily is recorded as completed, the date
|
||||
flips to `Today, May 6 • Done` in `ACCENT_PRIMARY` so the picker
|
||||
reads as a reward state rather than a TODO.
|
||||
- **Picture-tile mode cards** (`9fe650f` + glyph-picking follow-ups
|
||||
`40d6e0a`, `c30b04e`, `d065d49`). Mode cards become a wrapping
|
||||
2-up grid (`FlexWrap::Wrap`, tiles 48 % wide, `min_height: 180px`)
|
||||
with a centred Unicode-glyph centrepiece per tile. Final glyph set
|
||||
picked from FiraMono-Medium's actual coverage: ♣ Classic, ◆ Daily,
|
||||
○ Zen, ▲ Challenge, → TimeAttack. `ACCENT_PRIMARY` when the mode is
|
||||
unlocked, `TEXT_DISABLED` when locked. Centrepiece is a `Text` node
|
||||
for now — when real per-mode artwork lands, swap to `Image` without
|
||||
touching tile layout, focus order, or chip rendering.
|
||||
- **Solver-vetted seed selection on `AsyncComputeTaskPool`**
|
||||
(`d489e7a`). Closes the worst-case 6 s UI stall on a New Game
|
||||
click with "Winnable deals only" enabled. New `PendingNewGameSeed`
|
||||
resource holds the in-flight `Task<u64>` plus the original
|
||||
request's `mode` / `confirmed` flags. `poll_pending_new_game_seed`
|
||||
runs `.before(GameMutation)` and replays a synthetic
|
||||
`NewGameRequestEvent` once the task resolves — the player sees no
|
||||
extra-frame visual lag. Cancel-on-replace: a fresh
|
||||
`NewGameRequestEvent` while a task is in flight drops the old
|
||||
task, letting Bevy's `Task` Drop cancel cooperatively at the next
|
||||
await point.
|
||||
- **"Won before" HUD indicator** (`bdac754`). When the current
|
||||
deal's `(seed, draw_mode, mode)` triple matches an entry in the
|
||||
rolling `ReplayHistory`, the HUD's tier-2 context row shows
|
||||
**✓ Won before** in `STATE_SUCCESS`. Cleared on win (the on-screen
|
||||
victory cue is enough) and on first-time deals. New
|
||||
`HudWonPreviously` marker driven by a separate
|
||||
`update_won_previously` system; gracefully no-ops in headless
|
||||
tests that don't load `StatsPlugin`.
|
||||
- **"Copy share link" Stats button** (`540869c`). End-to-end replay
|
||||
sharing on a server-backed sync backend:
|
||||
`sync_plugin::push_replay_on_win` spawns the upload on
|
||||
`AsyncComputeTaskPool` and stores the handle in
|
||||
`PendingReplayUpload` (drops any in-flight predecessor — the most
|
||||
recent win is what the player wants the link for);
|
||||
`poll_replay_upload_result` writes `<server>/replays/<id>` to
|
||||
`LastSharedReplayUrl` on success; the Stats overlay's action bar
|
||||
gains a button that writes the URL to the OS clipboard via
|
||||
`arboard` and surfaces a "Copied: \<url\>" toast. URL is in-memory
|
||||
only — sharing must happen within the session of the win.
|
||||
- **Empty-state copy + onboarding hints** (`56e2e6f`). Leaderboard
|
||||
empty state: two-tier "Be the first on the leaderboard." headline
|
||||
+ body invite. Achievements panel: first-launch hint above the
|
||||
grid until the first unlock. Volume hotkeys (`[` / `]`) now emit
|
||||
an `InfoToastEvent` with the new percentage so off-panel
|
||||
adjustments give visible feedback (previously silent).
|
||||
- **Enter dismisses the Win Summary and starts a fresh deal**
|
||||
(`17e0737`). The post-win modal's "Play Again" was click-only;
|
||||
keyboard-only players had to reach for the mouse to leave the
|
||||
celebration screen. The button label gains a trailing return-key
|
||||
glyph so the keyboard path is discoverable on first sight.
|
||||
- **`N` opens the real Confirm/Cancel modal** (`93660c2`). The old
|
||||
"Press N again" double-tap pattern was a UI-first violation (only
|
||||
continuation was another keystroke). `N` now fires
|
||||
`NewGameRequestEvent::default()` directly; `handle_new_game`'s
|
||||
active-game check spawns the existing `ConfirmNewGameScreen`. The
|
||||
HUD button already routed through the same modal — keyboard and
|
||||
mouse paths are unified. `Shift+N` keeps the keyboard power-user
|
||||
bypass (`confirmed: true`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Settings row layout** (`a4bc063`). All five
|
||||
slider/toggle row helpers (volume × 2, tooltip delay, time-bonus
|
||||
multiplier, replay-move interval, generic toggle) restructured to
|
||||
a label-spacer-cluster layout (`width: 100%`, label gets
|
||||
`flex-grow: 1`, controls cluster sits flush right). Stable across
|
||||
varying value-text widths ("0.80" → "1.00", "Instant" vs "1.5 s")
|
||||
and narrow windows.
|
||||
- **Docs adopt the unified-3.0 rule set** (`f2f30c8`). `CLAUDE.md`
|
||||
grows from a 114-line pointer doc to a 571-line rulebook (hard
|
||||
global constraints §2, engine rules §3, asset rules §4, code
|
||||
standards §5, build + verification §6, git workflow §7, the ASK
|
||||
BEFORE list §8, Context Injection System §14). New companions:
|
||||
`CLAUDE_SPEC.md` (formal architecture spec — crate dependency
|
||||
graph, data ownership, state-machine invariants, sync merge /
|
||||
server contracts, validation checklist),
|
||||
`CLAUDE_WORKFLOW.md` (two-agent Builder/Guardian pipeline with
|
||||
hard-fail patterns), `CLAUDE_PROMPT_PACK.md` (task-type
|
||||
templates). Three duplicate rule passages removed across
|
||||
`CLAUDE_SPEC.md` and `ARCHITECTURE.md`.
|
||||
- **Test discipline pruning** (`a49a340`). Removed 43 low-value
|
||||
tests across `solitaire_data` and `solitaire_core` (default-value
|
||||
tests, serde-derive round-trips on plain structs, single-field
|
||||
clamp tests, near-duplicates, constant-equals-itself tests). None
|
||||
pinned a behaviour contract or a regression on a real bug. Future
|
||||
agent briefs request tests for behaviour contracts or real-bug
|
||||
regressions, not a count of N.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Esc on a modal no longer opens Pause underneath** (`08b006f`).
|
||||
A single Esc press on Confirm New Game / Restore / Home /
|
||||
Onboarding / Settings used to both close the modal and spawn the
|
||||
Pause overlay on top in the same frame. `toggle_pause` now skips
|
||||
when any non-Pause `ModalScrim` is in the world; the HUD-button
|
||||
path is gated too. The four modal queries are bundled into a
|
||||
`PauseModalQueries` `SystemParam` to stay under Bevy's
|
||||
16-parameter cap.
|
||||
- **Esc dismisses Home / accepts the Restore-prompt default**
|
||||
(`d48b948`). Both screens previously ignored Esc, leaving the
|
||||
player no keyboard-only escape after the previous fix. Home: Esc
|
||||
behaves like Cancel (despawns the modal, keeps the underlying
|
||||
default deal). Restore: Esc maps to Continue (preserves the saved
|
||||
game, matching how the primary action already advertises Enter).
|
||||
- **Esc dismisses the topmost modal when Profile stacks on Home**
|
||||
(`9aa0dd2`). Clicking the Home header chip opens Profile on top
|
||||
of Home; Esc used to close Home (because
|
||||
`handle_home_cancel_button` fired with no awareness of layered
|
||||
modals) and leave Profile orphaned over the game.
|
||||
`profile_plugin` now splits P/button (toggle) from Esc
|
||||
(close-only); `handle_home_cancel_button` skips its Esc branch
|
||||
when any other `ModalScrim` exists.
|
||||
- **Restore-prompt resolution suppresses Home auto-show**
|
||||
(`b7c3a49`). Resolving the Welcome-back prompt cleared
|
||||
`PendingRestoredGame` and despawned the modal, but the
|
||||
launch-time Home auto-show then fired the next frame and stacked
|
||||
itself over the player's chosen path. `LaunchHomeShown` becomes
|
||||
`pub` so `handle_restore_prompt` flips it to `true` after either
|
||||
resolution; **M** still re-opens the picker on demand.
|
||||
- **Game timers freeze while the Home picker is up** (`c497c31`).
|
||||
The HUD's elapsed-time counter ticked from the moment the default
|
||||
Classic deal landed at startup, even though the auto-show Home
|
||||
picker was still up — the player saw "0:11" before they had
|
||||
chosen a mode. `tick_elapsed_time` and `advance_time_attack` now
|
||||
also gate on the absence of `HomeScreen`, mirroring their
|
||||
existing `PausedResource` check.
|
||||
- **Popover rows stay visible regardless of action-bar fade**
|
||||
(`cc63532`). Opening Modes / Menu showed a solid dark-purple
|
||||
block in the top-right with no readable content — the action-bar
|
||||
auto-fade was matching the popover rows by their shared
|
||||
`ActionButton` marker and dropping their alpha to the
|
||||
cursor-position-based fade value (typically 0). New `PopoverRow`
|
||||
marker on rows in `spawn_modes_popover` / `spawn_menu_popover`;
|
||||
`apply_action_fade` excludes them via `Without<PopoverRow>`.
|
||||
|
||||
### Stats
|
||||
|
||||
- 1166 passing tests (was 1208 at v0.17.0 close — 43 net removals
|
||||
from the test-discipline prune plus 1 net-new test from the
|
||||
async-seed work, no behaviour regressions).
|
||||
- Zero clippy warnings under `--workspace --all-targets -- -D warnings`.
|
||||
|
||||
## [0.17.0] — 2026-05-06
|
||||
|
||||
A short follow-up round on top of v0.16.0: the H-key hint is no
|
||||
|
||||
@@ -1,114 +1,571 @@
|
||||
# Solitaire Quest — Claude Code Instructions
|
||||
# CLAUDE.md
|
||||
|
||||
See @ARCHITECTURE.md for full project design, crate responsibilities, data models, and API reference.
|
||||
version: unified-3.0
|
||||
|
||||
---
|
||||
|
||||
## Project Layout
|
||||
# 0. Role of This File
|
||||
|
||||
```text
|
||||
solitaire_core/ # Pure Rust game logic — NO Bevy, NO network, NO I/O
|
||||
solitaire_sync/ # Shared API types — NO Bevy, serde/uuid/chrono only
|
||||
solitaire_data/ # Persistence + SyncProvider trait + server client
|
||||
solitaire_engine/ # Bevy ECS systems, components, plugins
|
||||
solitaire_server/ # Axum sync server binary
|
||||
solitaire_app/ # Thin binary entry point
|
||||
assets/ # Source assets — embedded at compile time via include_bytes!()
|
||||
This document defines:
|
||||
|
||||
* **Execution rules (what Claude must do)**
|
||||
* **System constraints (what Claude must never violate)**
|
||||
* **Operational architecture (how code is structured)**
|
||||
|
||||
For full system design details:
|
||||
→ `ARCHITECTURE.md` (authoritative source of truth)
|
||||
|
||||
This file overrides all conversational assumptions.
|
||||
|
||||
---
|
||||
|
||||
# 1. System Architecture (Authoritative Mapping)
|
||||
|
||||
## 1.1 Crates
|
||||
|
||||
```text id="crate_map"
|
||||
solitaire_core/ # PURE logic (no IO, no Bevy, deterministic)
|
||||
solitaire_sync/ # Shared API + merge logic
|
||||
solitaire_data/ # Persistence + sync client
|
||||
solitaire_engine/ # Bevy ECS + UI + gameplay orchestration
|
||||
solitaire_server/ # Axum backend (optional sync layer)
|
||||
solitaire_app/ # Entry binary
|
||||
assets/ # Runtime assets (except audio)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Build & Test Commands
|
||||
## 1.2 Architecture Source of Truth
|
||||
|
||||
```bash
|
||||
# Dev run (fast compile via dynamic linking)
|
||||
cargo run -p solitaire_app --features bevy/dynamic_linking
|
||||
* Full system design: `ARCHITECTURE.md`
|
||||
* This file NEVER redefines system design
|
||||
* This file ONLY enforces behavior
|
||||
|
||||
# Release build
|
||||
cargo build --workspace --release
|
||||
---
|
||||
|
||||
# All tests — MUST pass before any commit
|
||||
# 2. Hard Global Constraints (NON-NEGOTIABLE)
|
||||
|
||||
These override all other instructions.
|
||||
|
||||
## 2.1 Core Determinism
|
||||
|
||||
* `solitaire_core` MUST:
|
||||
|
||||
* be deterministic
|
||||
* be side-effect free
|
||||
* never depend on Bevy / IO / async
|
||||
|
||||
---
|
||||
|
||||
## 2.2 Sync Isolation
|
||||
|
||||
* `solitaire_sync`:
|
||||
|
||||
* no Bevy
|
||||
* no IO
|
||||
* no engine dependencies
|
||||
* merge logic must be pure functions only
|
||||
|
||||
---
|
||||
|
||||
## 2.3 Error Policy
|
||||
|
||||
* NO `unwrap()`
|
||||
* NO `panic!()` in runtime/game logic
|
||||
* All state transitions:
|
||||
|
||||
```rust id="err_model"
|
||||
Result<T, MoveError>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2.4 Threading Rules
|
||||
|
||||
* Sync must run on `AsyncComputeTaskPool`
|
||||
* NEVER block Bevy main thread
|
||||
|
||||
---
|
||||
|
||||
## 2.5 Persistence Rules
|
||||
|
||||
* atomic writes only:
|
||||
|
||||
* write `.tmp`
|
||||
* rename atomically
|
||||
* no partial state writes allowed
|
||||
|
||||
---
|
||||
|
||||
## 2.6 Security Rules
|
||||
|
||||
* credentials ONLY via `keyring`
|
||||
* NEVER store secrets in:
|
||||
|
||||
* files
|
||||
* logs
|
||||
* source code
|
||||
|
||||
---
|
||||
|
||||
## 2.7 Sync System Rules
|
||||
|
||||
* All sync backends implement:
|
||||
|
||||
```rust id="sync_trait"
|
||||
trait SyncProvider
|
||||
```
|
||||
|
||||
* `SyncPlugin` MUST be backend-agnostic
|
||||
* NEVER match on backend inside ECS systems
|
||||
|
||||
---
|
||||
|
||||
# 3. Engine Rules (Bevy Layer)
|
||||
|
||||
## 3.1 ECS Design
|
||||
|
||||
* systems = single responsibility
|
||||
* communication = Events only
|
||||
* shared state = Resources only
|
||||
* per-entity state = Components only
|
||||
|
||||
---
|
||||
|
||||
## 3.2 Game State Authority
|
||||
|
||||
* ONLY `GameStateResource` can mutate game state
|
||||
* UI systems MUST NOT directly modify core logic
|
||||
|
||||
---
|
||||
|
||||
## 3.3 UI-First Constraint (CRITICAL)
|
||||
|
||||
Every player action MUST:
|
||||
|
||||
* have a visible UI control
|
||||
* NOT rely solely on keyboard shortcuts
|
||||
|
||||
Keyboard shortcuts are:
|
||||
→ optional accelerators only
|
||||
|
||||
---
|
||||
|
||||
## 3.4 Layout System
|
||||
|
||||
* recompute on `WindowResized`
|
||||
* no fixed resolution assumptions
|
||||
|
||||
---
|
||||
|
||||
# 4. Asset System Rules
|
||||
|
||||
## 4.1 Runtime Assets (AssetServer)
|
||||
|
||||
Loaded via:
|
||||
|
||||
* `CardImageSet`
|
||||
* `BackgroundImageSet`
|
||||
* `FontResource`
|
||||
|
||||
Includes:
|
||||
|
||||
* cards
|
||||
* backgrounds
|
||||
* fonts
|
||||
|
||||
---
|
||||
|
||||
## 4.2 Embedded Assets
|
||||
|
||||
Only audio:
|
||||
|
||||
```text id="audio_rule"
|
||||
include_bytes!()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4.3 Test Compatibility Rule
|
||||
|
||||
All asset loaders MUST accept:
|
||||
|
||||
```rust id="asset_fallback"
|
||||
Option<Res<AssetServer>>
|
||||
```
|
||||
|
||||
Must degrade gracefully under `MinimalPlugins`.
|
||||
|
||||
---
|
||||
|
||||
# 5. Code Standards
|
||||
|
||||
## 5.1 Error Handling
|
||||
|
||||
* use `thiserror`
|
||||
* no `Box<dyn Error>` in libraries
|
||||
|
||||
---
|
||||
|
||||
## 5.2 Public API Rules
|
||||
|
||||
* prefer `Into<T>` over concrete types
|
||||
* all public items require doc comments
|
||||
|
||||
---
|
||||
|
||||
## 5.3 Derive Order
|
||||
|
||||
```rust id="derive_order"
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5.4 Performance Rules
|
||||
|
||||
* NO `clone()` in hot paths
|
||||
* profile before optimizing
|
||||
|
||||
---
|
||||
|
||||
## 5.5 SQL Rules
|
||||
|
||||
* ONLY `sqlx::query!`
|
||||
* NO raw SQL strings
|
||||
|
||||
---
|
||||
|
||||
# 6. Build & Verification Rules
|
||||
|
||||
These are mandatory before ANY commit.
|
||||
|
||||
```bash id="build_rules"
|
||||
cargo test --workspace
|
||||
|
||||
# Lint — MUST pass clean (zero warnings)
|
||||
cargo clippy --workspace -- -D warnings
|
||||
|
||||
# Run sync server locally
|
||||
cargo run -p solitaire_server
|
||||
|
||||
# Check a single crate
|
||||
cargo test -p solitaire_core
|
||||
cargo clippy -p solitaire_core -- -D warnings
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hard Rules
|
||||
# 7. Git Workflow Rules
|
||||
|
||||
- `solitaire_core` and `solitaire_sync` must never gain Bevy or network dependencies.
|
||||
- No `unwrap()` or `panic!()` in game logic. All state transitions return `Result<_, MoveError>`.
|
||||
- Audio assets are embedded at compile time using `include_bytes!()` in `audio_plugin.rs`.
|
||||
- Card faces (52 PNGs in `assets/cards/faces/`), card backs (`assets/cards/backs/back_N.png`), board backgrounds (`assets/backgrounds/bg_N.png`), and the UI font (`assets/fonts/main.ttf`) are loaded at runtime via `AssetServer::load()` and stored as `Handle<Image>`/`Handle<Font>` in the `CardImageSet`, `BackgroundImageSet`, and `FontResource` resources. The `assets/` directory must ship alongside the binary.
|
||||
- Asset-loading systems take `Option<Res<AssetServer>>` so they degrade cleanly under `MinimalPlugins` (tests). When `CardImageSet` is absent, `card_plugin` falls back to a `Text2d` rank+suit overlay; when `BackgroundImageSet` is absent, the board falls back to a solid colour.
|
||||
- Atomic file writes only: write to `filename.json.tmp`, then `rename()`.
|
||||
- Passwords and tokens are stored in the OS keychain via the `keyring` crate — never in plaintext files or logs.
|
||||
- Sync runs on `AsyncComputeTaskPool` — never block the Bevy main thread.
|
||||
- All sync backends implement the `SyncProvider` trait. The `SyncPlugin` is backend-agnostic — never `match` on `SyncBackend` inside a Bevy system.
|
||||
- `cargo clippy --workspace -- -D warnings` must pass clean after every change.
|
||||
- `cargo test --workspace` must pass after every change.
|
||||
## Commit format
|
||||
|
||||
```text id="commit_fmt"
|
||||
type(scope): description
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
* feat(core): add draw-three rules
|
||||
* fix(engine): correct drag z-order
|
||||
* test(core): undo boundary cases
|
||||
|
||||
---
|
||||
|
||||
## Code Style
|
||||
## Commit conditions
|
||||
|
||||
- Use `thiserror` for error types. Never `Box<dyn Error>` in library crates.
|
||||
- Prefer `Into<T>` over concrete types in public API function parameters.
|
||||
- All public items must have doc comments (`///`). Private items: comment only when non-obvious.
|
||||
- Derive order convention: `#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]`
|
||||
- Bevy systems: one responsibility per system. Use `Events` for cross-system communication, never shared mutable state.
|
||||
- SQL queries: use `sqlx::query!` macros (compile-time checked), not raw string queries.
|
||||
- No `clone()` calls in hot paths (game loop systems). Profile before optimising elsewhere.
|
||||
* tests must pass
|
||||
* clippy must be clean
|
||||
|
||||
NEVER commit otherwise
|
||||
|
||||
---
|
||||
|
||||
## Bevy Conventions
|
||||
# 8. Change Control (ASK BEFORE DOING)
|
||||
|
||||
- One `Plugin` per major feature: `CardPlugin`, `AudioPlugin`, `AchievementPlugin`, `UIPlugin`, `SyncPlugin`.
|
||||
- Resources own shared state. Events communicate between systems. Components own per-entity data.
|
||||
- All UI screens are built with Bevy UI (`bevy::ui`). Never mix UI layout and game logic in the same system.
|
||||
- Layout is recomputed on `WindowResized` — never assume a fixed window size.
|
||||
- **UI-first.** Every player-triggered action (new game, undo, draw, pause, open stats / settings / help / profile / leaderboard, switch mode, etc.) must be reachable from a visible UI control. Keyboard shortcuts are optional accelerators — never the sole entry point. New gameplay features ship with the UI control alongside the system that backs it; do not merge a feature that is keyboard-only.
|
||||
Claude must request confirmation before:
|
||||
|
||||
* adding dependencies
|
||||
* modifying `solitaire_sync`
|
||||
* changing DB schema
|
||||
* introducing `unsafe`
|
||||
* changing merge strategy
|
||||
|
||||
---
|
||||
|
||||
## Git Workflow
|
||||
# 9. System Mental Model (IMPORTANT)
|
||||
|
||||
- Commit after each passing phase, not after every file change.
|
||||
- Commit message format: `type(scope): description`
|
||||
- `feat(core): add draw-three mode validation`
|
||||
- `fix(engine): card z-order during drag`
|
||||
- `test(core): undo stack boundary conditions`
|
||||
- `chore(server): add sqlx migration 002`
|
||||
- Never commit with failing tests or clippy warnings.
|
||||
- Never commit secrets, `.env` files, or `*.db` files.
|
||||
```text id="mental_model"
|
||||
Core (rules + deterministic logic)
|
||||
↓
|
||||
Engine (Bevy orchestration)
|
||||
↓
|
||||
Data layer (persistence + sync)
|
||||
↓
|
||||
Server (optional external system)
|
||||
```
|
||||
|
||||
Core is always the source of truth.
|
||||
|
||||
---
|
||||
|
||||
## Ask Before Doing
|
||||
# 10. Known Platform Pitfalls
|
||||
|
||||
- Adding a new crate dependency (discuss alternatives first).
|
||||
- Changing a type in `solitaire_sync` (breaking change on both client and server).
|
||||
- Altering the database schema (requires a new sqlx migration).
|
||||
- Introducing `unsafe` code anywhere.
|
||||
- Changing the merge strategy in `solitaire_sync::merge()`.
|
||||
Must always be handled explicitly:
|
||||
|
||||
* Bevy `Time` uses `f32`
|
||||
* `sqlx::migrate!()` path is crate-relative
|
||||
* `dirs::data_dir()` may return `None`
|
||||
* Linux may lack keyring backend
|
||||
|
||||
---
|
||||
|
||||
## Lessons Learned
|
||||
# 11. Forbidden Patterns
|
||||
|
||||
> Add entries here when Claude makes a mistake so it isn't repeated.
|
||||
* game logic inside Bevy systems
|
||||
* duplication across crates
|
||||
* blocking async calls in ECS
|
||||
* insecure credential storage
|
||||
* bypassing core logic layer
|
||||
|
||||
- Bevy's `Time` resource uses `f32` seconds; convert to `u64` only when writing to `StatsSnapshot`.
|
||||
- `sqlx::migrate!()` macro path is relative to the crate root, not the workspace root.
|
||||
- `keyring` on Linux requires a running secret service (e.g. GNOME Keyring or KWallet) — handle `Error::NoStorageAccess` gracefully and fall back to prompting the user.
|
||||
- `dirs::data_dir()` returns `None` on some minimal Linux environments — always handle the `None` case explicitly, do not unwrap.
|
||||
---
|
||||
|
||||
# 12. Execution Rules for Claude
|
||||
|
||||
When generating code:
|
||||
|
||||
1. respect crate boundaries
|
||||
2. minimize diff size
|
||||
3. do not expand scope
|
||||
4. follow existing patterns
|
||||
5. preserve invariants
|
||||
|
||||
If unclear:
|
||||
→ ask before acting
|
||||
|
||||
---
|
||||
|
||||
# 13. Relationship to ARCHITECTURE.md
|
||||
|
||||
| File | Role |
|
||||
| --------------- | ------------------------- |
|
||||
| CLAUDE.md | execution + constraints |
|
||||
| ARCHITECTURE.md | system design truth |
|
||||
| Both combined | full system understanding |
|
||||
|
||||
---
|
||||
# 14. Context Injection System (AUTOMATIC SCOPE FILTER)
|
||||
|
||||
## 14.1 Purpose
|
||||
|
||||
Before generating any response, Claude MUST construct a **minimal relevant context set**.
|
||||
|
||||
This prevents:
|
||||
|
||||
* architectural drift
|
||||
* irrelevant spec loading
|
||||
* over-engineering
|
||||
* cross-crate confusion
|
||||
|
||||
---
|
||||
|
||||
## 14.2 Input Classification Step (MANDATORY)
|
||||
|
||||
Every request MUST be classified into exactly one task type:
|
||||
|
||||
```text id="task_types"
|
||||
feature
|
||||
bugfix
|
||||
refactor
|
||||
system_design
|
||||
bevy_system
|
||||
core_logic
|
||||
sync
|
||||
optimization
|
||||
test
|
||||
debug
|
||||
```
|
||||
|
||||
If uncertain → ask clarification.
|
||||
|
||||
---
|
||||
|
||||
## 14.3 Context Selection Engine
|
||||
|
||||
After classification, Claude MUST include ONLY the relevant sections below.
|
||||
|
||||
---
|
||||
|
||||
## 14.4 Context Map (CORE RULESET)
|
||||
|
||||
### feature
|
||||
|
||||
Include:
|
||||
|
||||
* §2 Hard Global Constraints
|
||||
* §3 Engine Rules
|
||||
* ARCHITECTURE.md (crate of target feature only)
|
||||
* relevant data models (GameState, SyncPayload if needed)
|
||||
|
||||
---
|
||||
|
||||
### bugfix
|
||||
|
||||
Include:
|
||||
|
||||
* §2 Hard Global Constraints
|
||||
* §5 Code Standards
|
||||
* affected crate boundaries
|
||||
* relevant system (engine/core/sync only)
|
||||
|
||||
---
|
||||
|
||||
### refactor
|
||||
|
||||
Include:
|
||||
|
||||
* §3 Engine Rules
|
||||
* §5 Code Standards
|
||||
* §11 Forbidden Patterns
|
||||
* target crate boundaries
|
||||
|
||||
---
|
||||
|
||||
### system_design
|
||||
|
||||
Include:
|
||||
|
||||
* ARCHITECTURE.md (FULL)
|
||||
* §9 Mental Model
|
||||
* §1 System Architecture Mapping
|
||||
|
||||
---
|
||||
|
||||
### core_logic
|
||||
|
||||
Include:
|
||||
|
||||
* solitaire_core rules only
|
||||
* GameState model
|
||||
* MoveError model
|
||||
* §2.1–2.3 constraints
|
||||
|
||||
---
|
||||
|
||||
### bevy_system
|
||||
|
||||
Include:
|
||||
|
||||
* §3 Engine Rules
|
||||
* ECS rules (Events/Resources/Components)
|
||||
* UI-first constraint
|
||||
* relevant plugin system only
|
||||
|
||||
---
|
||||
|
||||
### sync
|
||||
|
||||
Include:
|
||||
|
||||
* SyncProvider trait
|
||||
* merge strategy rules
|
||||
* solitaire_sync models
|
||||
* §2.6 Sync Rules
|
||||
|
||||
---
|
||||
|
||||
### optimization
|
||||
|
||||
Include:
|
||||
|
||||
* target crate only
|
||||
* §5.4 Performance Rules
|
||||
* hot path constraints
|
||||
|
||||
---
|
||||
|
||||
### test
|
||||
|
||||
Include:
|
||||
|
||||
* §6 Build Rules
|
||||
* relevant module
|
||||
* expected invariants
|
||||
|
||||
---
|
||||
|
||||
### debug
|
||||
|
||||
Include:
|
||||
|
||||
* target file/module only
|
||||
* §2.3 Error Policy
|
||||
* runtime assumptions relevant to failure
|
||||
|
||||
---
|
||||
|
||||
## 14.5 Context Compression Rules
|
||||
|
||||
Claude MUST obey:
|
||||
|
||||
* never include full ARCHITECTURE.md unless system_design
|
||||
* max 2 crates per response unless explicitly required
|
||||
* prefer function-level context over file-level context
|
||||
* exclude unrelated plugins/systems
|
||||
|
||||
---
|
||||
|
||||
## 14.6 Context Priority Order
|
||||
|
||||
When space is limited:
|
||||
|
||||
1. Hard Constraints (§2)
|
||||
2. Target crate rules
|
||||
3. Data models
|
||||
4. Only then: architecture snippets
|
||||
|
||||
---
|
||||
|
||||
## 14.7 “No Context Pollution” Rule
|
||||
|
||||
Claude must NOT include:
|
||||
|
||||
* unrelated crates
|
||||
* unrelated plugins
|
||||
* unused data models
|
||||
* full architecture dumps
|
||||
* speculative systems
|
||||
|
||||
---
|
||||
|
||||
## 14.8 Self-Check Before Execution
|
||||
|
||||
Before writing code, Claude MUST verify:
|
||||
|
||||
* [ ] Is only relevant context included?
|
||||
* [ ] Is at least one hard constraint present?
|
||||
* [ ] Am I touching more than one crate unnecessarily?
|
||||
* [ ] Am I duplicating ARCHITECTURE.md content?
|
||||
|
||||
If any fail → revise context selection.
|
||||
|
||||
---
|
||||
|
||||
## 14.9 Injection Output Format (Internal Model)
|
||||
|
||||
Claude should behave as if it constructed:
|
||||
|
||||
```text id="ctx_format"
|
||||
[SELECTED TASK TYPE]
|
||||
|
||||
[MINIMAL REQUIRED RULES]
|
||||
|
||||
[MINIMAL ARCHITECTURE SLICES]
|
||||
|
||||
[RELEVANT MODELS]
|
||||
|
||||
[REQUEST]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14.10 Relationship to ARCHITECTURE.md
|
||||
|
||||
* ARCHITECTURE.md = source of truth
|
||||
* CLAUDE.md = execution constraints
|
||||
* THIS SECTION = filtering layer between them
|
||||
|
||||
---
|
||||
|
||||
# END CONTEXT INJECTION SYSTEM
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
# CLAUDE_PROMPT_PACK.md
|
||||
|
||||
version: 1.0
|
||||
|
||||
---
|
||||
|
||||
# 0. GLOBAL INSTRUCTION (prepend to every prompt)
|
||||
|
||||
```
|
||||
You must follow CLAUDE_SPEC.md strictly.
|
||||
|
||||
Rules:
|
||||
- Do not expand scope beyond what is defined
|
||||
- Do not refactor unrelated code
|
||||
- Do not introduce new dependencies
|
||||
- Prefer minimal, surgical changes
|
||||
- Use existing patterns in the codebase
|
||||
- Return minimal diffs or changed functions only
|
||||
|
||||
Before writing code:
|
||||
1. List relevant constraints from CLAUDE_SPEC.md
|
||||
2. Identify risks
|
||||
3. Then implement
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 1. FEATURE IMPLEMENTATION
|
||||
|
||||
```
|
||||
# TASK: Feature Implementation
|
||||
|
||||
feature: "<name>"
|
||||
|
||||
goal:
|
||||
"<clear outcome>"
|
||||
|
||||
scope:
|
||||
crates: []
|
||||
systems: []
|
||||
files: []
|
||||
|
||||
non_goals:
|
||||
- ""
|
||||
|
||||
constraints:
|
||||
- must follow CLAUDE_SPEC.md
|
||||
- event-driven architecture required
|
||||
- no blocking operations
|
||||
- no cross-crate leakage
|
||||
|
||||
acceptance_criteria:
|
||||
- ""
|
||||
- ""
|
||||
|
||||
edge_cases:
|
||||
- ""
|
||||
|
||||
---
|
||||
|
||||
## Required Patterns
|
||||
|
||||
Use this pattern for systems:
|
||||
<PASTE EXISTING SYSTEM SNIPPET HERE>
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
intent:
|
||||
plan:
|
||||
constraints_used:
|
||||
risks:
|
||||
|
||||
code_changes:
|
||||
(minimal diffs only)
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 2. BUGFIX
|
||||
|
||||
```
|
||||
# TASK: Bug Fix
|
||||
|
||||
bug_description:
|
||||
"<what is broken>"
|
||||
|
||||
expected_behavior:
|
||||
"<correct behavior>"
|
||||
|
||||
root_cause_hint (optional):
|
||||
""
|
||||
|
||||
scope:
|
||||
crates: []
|
||||
files: []
|
||||
|
||||
constraints:
|
||||
- minimal fix only
|
||||
- no refactors unless required
|
||||
- must add regression protection if applicable
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Identify root cause
|
||||
2. Fix it minimally
|
||||
3. Preserve all invariants
|
||||
4. Do not change unrelated logic
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
analysis:
|
||||
root_cause:
|
||||
fix_strategy:
|
||||
|
||||
code_changes:
|
||||
(minimal diff)
|
||||
|
||||
regression_test (only if high-value):
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 3. REFACTOR
|
||||
|
||||
```
|
||||
# TASK: Refactor
|
||||
|
||||
target:
|
||||
"<what is being improved>"
|
||||
|
||||
goal:
|
||||
"<what improves>"
|
||||
|
||||
scope:
|
||||
crates: []
|
||||
files: []
|
||||
|
||||
non_goals:
|
||||
- no behavior changes
|
||||
- no new features
|
||||
|
||||
constraints:
|
||||
- must preserve behavior exactly
|
||||
- must respect crate boundaries
|
||||
- must not duplicate logic
|
||||
|
||||
---
|
||||
|
||||
## Refactor Type
|
||||
|
||||
- [ ] simplify logic
|
||||
- [ ] reduce duplication
|
||||
- [ ] improve readability
|
||||
- [ ] performance (non-invasive)
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
analysis:
|
||||
issues_found:
|
||||
|
||||
refactor_plan:
|
||||
|
||||
code_changes:
|
||||
(diff only)
|
||||
|
||||
verification:
|
||||
- behavior unchanged: yes/no
|
||||
- invariants preserved: yes/no
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 4. SYSTEM DESIGN (NEW FEATURE)
|
||||
|
||||
```
|
||||
# TASK: System Design
|
||||
|
||||
feature:
|
||||
"<name>"
|
||||
|
||||
goal:
|
||||
"<what problem it solves>"
|
||||
|
||||
constraints:
|
||||
- must fit existing architecture
|
||||
- must follow plugin + event model
|
||||
- must not violate crate boundaries
|
||||
|
||||
---
|
||||
|
||||
## Required Output
|
||||
|
||||
design:
|
||||
|
||||
components:
|
||||
- plugins:
|
||||
- systems:
|
||||
- events:
|
||||
- resources:
|
||||
|
||||
data_flow:
|
||||
(step-by-step)
|
||||
|
||||
integration_points:
|
||||
- where it connects to existing systems
|
||||
|
||||
risks:
|
||||
- ""
|
||||
|
||||
tradeoffs:
|
||||
- ""
|
||||
|
||||
---
|
||||
|
||||
## DO NOT
|
||||
|
||||
- write full implementation
|
||||
- modify unrelated systems
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 5. NEW BEVY SYSTEM
|
||||
|
||||
```
|
||||
# TASK: Add Bevy System
|
||||
|
||||
system_name:
|
||||
""
|
||||
|
||||
trigger:
|
||||
(event or condition)
|
||||
|
||||
reads:
|
||||
[Resources]
|
||||
|
||||
writes:
|
||||
[Resources]
|
||||
|
||||
emits:
|
||||
[Events]
|
||||
|
||||
constraints:
|
||||
- must be event-driven
|
||||
- must not directly mutate unrelated state
|
||||
- must be single responsibility
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
system_signature:
|
||||
|
||||
implementation:
|
||||
(code only)
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 6. CORE LOGIC FUNCTION (solitaire_core)
|
||||
|
||||
```
|
||||
# TASK: Core Logic Implementation
|
||||
|
||||
function:
|
||||
"<name>"
|
||||
|
||||
goal:
|
||||
"<what it does>"
|
||||
|
||||
rules:
|
||||
- no IO
|
||||
- no async
|
||||
- no Bevy
|
||||
- deterministic
|
||||
|
||||
invariants:
|
||||
- ""
|
||||
- ""
|
||||
|
||||
errors:
|
||||
- ""
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
constraints_checked:
|
||||
|
||||
implementation:
|
||||
(code only)
|
||||
|
||||
edge_case_handling:
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 7. SYNC / MERGE LOGIC
|
||||
|
||||
```
|
||||
# TASK: Sync Logic
|
||||
|
||||
goal:
|
||||
"<what is being merged or synced>"
|
||||
|
||||
constraints:
|
||||
- must be deterministic
|
||||
- must be idempotent
|
||||
- must be lossless
|
||||
- must not delete data
|
||||
|
||||
rules:
|
||||
- counters → max
|
||||
- times → min
|
||||
- collections → union
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
analysis:
|
||||
|
||||
merge_logic:
|
||||
|
||||
code_changes:
|
||||
|
||||
invariants_verified:
|
||||
- deterministic
|
||||
- idempotent
|
||||
- lossless
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 8. PERFORMANCE OPTIMIZATION
|
||||
|
||||
```
|
||||
# TASK: Optimization
|
||||
|
||||
target:
|
||||
"<what is slow>"
|
||||
|
||||
constraints:CLAUDE_WORKFLOW.md
|
||||
- no behavior change
|
||||
- no architecture change
|
||||
- minimal code changes
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
analysis:
|
||||
bottleneck:
|
||||
|
||||
optimization_strategy:
|
||||
|
||||
code_changes:
|
||||
|
||||
impact_estimate:
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 9. TEST GENERATION (STRICT MODE)
|
||||
|
||||
```
|
||||
# TASK: Test Generation
|
||||
|
||||
target:
|
||||
"<function/system>"
|
||||
|
||||
reason:
|
||||
- bugfix | complex logic | invariant protection
|
||||
|
||||
constraints:
|
||||
- no redundant tests
|
||||
- must test real behavior
|
||||
- must fail if logic breaks
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
test_cases:
|
||||
- ""
|
||||
|
||||
test_code:
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 10. DEBUGGING / INVESTIGATION
|
||||
|
||||
```
|
||||
# TASK: Debug
|
||||
|
||||
problem:
|
||||
"<symptom>"
|
||||
|
||||
context:
|
||||
"<relevant code or system>"
|
||||
|
||||
---
|
||||
|
||||
## Required Steps
|
||||
|
||||
1. List possible causes
|
||||
2. Narrow down most likely
|
||||
3. Suggest verification steps
|
||||
4. Provide minimal fix
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
hypotheses:
|
||||
|
||||
most_likely:
|
||||
|
||||
verification_steps:
|
||||
|
||||
fix:
|
||||
|
||||
notes:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 11. HARD CONSTRAINT OVERRIDE (RARE)
|
||||
|
||||
```
|
||||
# TASK: Exception Handling
|
||||
|
||||
reason:
|
||||
"<why constraints must be bent>"
|
||||
|
||||
requested_exception:
|
||||
"<rule being broken>"
|
||||
|
||||
justification:
|
||||
"<why unavoidable>"
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
analysis:
|
||||
|
||||
alternatives_considered:
|
||||
|
||||
final_decision:
|
||||
|
||||
risk:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 12. STOP CONDITIONS (always append)
|
||||
|
||||
```
|
||||
Stop when:
|
||||
- acceptance criteria are met
|
||||
- code is minimal and correct
|
||||
|
||||
Do NOT:
|
||||
- expand scope
|
||||
- refactor unrelated code
|
||||
- optimize prematurely
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# END
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
# CLAUDE_SPEC.md
|
||||
|
||||
version: 1.0
|
||||
|
||||
---
|
||||
|
||||
## 0. Global Rules
|
||||
|
||||
(Core determinism, panic policy, and event-driven engine constraints live in CLAUDE.md §2.1, §2.3, §3.1. Listed here only when they add information CLAUDE.md doesn't carry.)
|
||||
|
||||
rules:
|
||||
|
||||
* id: single_source_of_truth
|
||||
description: "GameStateResource is the only mutable game state in runtime"
|
||||
|
||||
* id: sync_is_additive
|
||||
description: "Remote data must never destructively overwrite local data"
|
||||
|
||||
---
|
||||
|
||||
## 1. Crate Graph
|
||||
|
||||
crates:
|
||||
solitaire_core:
|
||||
depends_on: [rand, serde, chrono]
|
||||
forbidden_deps: [bevy, reqwest, tokio, std::fs]
|
||||
|
||||
solitaire_sync:
|
||||
depends_on: [serde, serde_json, uuid, chrono]
|
||||
role: "shared_types"
|
||||
|
||||
solitaire_data:
|
||||
depends_on: [solitaire_core, solitaire_sync, reqwest, tokio, keyring]
|
||||
role: "persistence_and_sync"
|
||||
|
||||
solitaire_engine:
|
||||
depends_on: [bevy, kira, solitaire_core, solitaire_data]
|
||||
role: "runtime_engine"
|
||||
|
||||
solitaire_server:
|
||||
depends_on: [solitaire_sync, axum, sqlx, jsonwebtoken]
|
||||
role: "backend"
|
||||
|
||||
solitaire_app:
|
||||
depends_on: [solitaire_engine]
|
||||
role: "entrypoint"
|
||||
|
||||
---
|
||||
|
||||
## 2. Data Ownership
|
||||
|
||||
ownership:
|
||||
GameState:
|
||||
owner: solitaire_core
|
||||
mutable_in: solitaire_engine
|
||||
access_pattern: "via GameStateResource only"
|
||||
|
||||
StatsSnapshot:
|
||||
owner: solitaire_data
|
||||
|
||||
PlayerProgress:
|
||||
owner: solitaire_data
|
||||
|
||||
AchievementRecord:
|
||||
owner: solitaire_data
|
||||
|
||||
SyncPayload:
|
||||
owner: solitaire_sync
|
||||
|
||||
---
|
||||
|
||||
## 3. State Transitions
|
||||
|
||||
state_machine:
|
||||
GameState:
|
||||
transitions:
|
||||
- action: move_cards
|
||||
returns: Result<GameState, MoveError>
|
||||
|
||||
```
|
||||
- action: draw
|
||||
returns: Result<GameState, MoveError>
|
||||
|
||||
- action: undo
|
||||
returns: Result<GameState, MoveError>
|
||||
|
||||
invariants:
|
||||
- "52 cards always exist"
|
||||
- "no duplicate card IDs"
|
||||
- "all cards belong to exactly one pile"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Event System
|
||||
|
||||
events:
|
||||
|
||||
input:
|
||||
- MoveRequestEvent
|
||||
- DrawRequestEvent
|
||||
- UndoRequestEvent
|
||||
- NewGameRequestEvent
|
||||
|
||||
state:
|
||||
- StateChangedEvent
|
||||
- GameWonEvent
|
||||
|
||||
meta:
|
||||
- AchievementUnlockedEvent
|
||||
- SyncCompleteEvent
|
||||
|
||||
rules:
|
||||
|
||||
* "Input events trigger core logic"
|
||||
* "Core logic emits state events"
|
||||
* "UI reacts to state events only"
|
||||
|
||||
---
|
||||
|
||||
## 5. Sync Contract
|
||||
|
||||
sync:
|
||||
|
||||
provider_trait:
|
||||
methods:
|
||||
- pull() -> SyncPayload
|
||||
- push(payload) -> SyncResponse
|
||||
|
||||
guarantees:
|
||||
- "non-blocking during gameplay"
|
||||
- "blocking allowed on exit only"
|
||||
|
||||
merge:
|
||||
rules:
|
||||
counters: "max"
|
||||
best_times: "min"
|
||||
collections: "union"
|
||||
achievements: "never removed"
|
||||
|
||||
```
|
||||
properties:
|
||||
- deterministic
|
||||
- idempotent
|
||||
- lossless
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Persistence
|
||||
|
||||
storage:
|
||||
|
||||
format: json
|
||||
|
||||
files:
|
||||
- stats.json
|
||||
- progress.json
|
||||
- achievements.json
|
||||
- settings.json
|
||||
- game_state.json
|
||||
|
||||
guarantees:
|
||||
- atomic_write: true
|
||||
- crash_safe: true
|
||||
|
||||
---
|
||||
|
||||
## 7. Engine Rules
|
||||
|
||||
engine:
|
||||
|
||||
mutation_rules:
|
||||
- "Only GameLogicSystem mutates GameState"
|
||||
- "UI systems are read-only"
|
||||
|
||||
threading:
|
||||
- "sync runs on AsyncComputeTaskPool"
|
||||
- "main thread must never block"
|
||||
|
||||
plugins:
|
||||
pattern: "feature_isolation"
|
||||
communication: "events"
|
||||
|
||||
---
|
||||
|
||||
## 8. Server Contract
|
||||
|
||||
server:
|
||||
|
||||
auth:
|
||||
method: jwt
|
||||
access_expiry: 24h
|
||||
refresh_expiry: 30d
|
||||
|
||||
endpoints:
|
||||
- POST /api/auth/register
|
||||
- POST /api/auth/login
|
||||
- GET /api/sync/pull
|
||||
- POST /api/sync/push
|
||||
|
||||
limits:
|
||||
payload_max: 1MB
|
||||
rate_limit: "10 req/min auth routes"
|
||||
|
||||
---
|
||||
|
||||
## 9. Achievement System
|
||||
|
||||
achievements:
|
||||
|
||||
definition_location: solitaire_core
|
||||
state_location: solitaire_data
|
||||
|
||||
types:
|
||||
- condition_based
|
||||
- event_driven
|
||||
|
||||
rule:
|
||||
- "achievements cannot be revoked"
|
||||
|
||||
---
|
||||
|
||||
## 10. Testing Rules
|
||||
|
||||
testing:
|
||||
|
||||
philosophy:
|
||||
- "test real failures"
|
||||
- "avoid redundant tests"
|
||||
|
||||
required_coverage:
|
||||
solitaire_core:
|
||||
- move_validation
|
||||
- undo_integrity
|
||||
- win_detection
|
||||
|
||||
```
|
||||
solitaire_sync:
|
||||
- merge_correctness
|
||||
- idempotency
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Prohibited Patterns
|
||||
|
||||
(See CLAUDE.md §11 for the canonical forbidden-patterns list.)
|
||||
|
||||
---
|
||||
|
||||
## 12. Extension Points
|
||||
|
||||
extensibility:
|
||||
|
||||
sync_backends:
|
||||
pattern: "implement SyncProvider"
|
||||
|
||||
game_modes:
|
||||
location: solitaire_core::GameMode
|
||||
|
||||
plugins:
|
||||
rule: "new feature = new plugin"
|
||||
|
||||
---
|
||||
|
||||
## 13. Validation Checklist (for Claude)
|
||||
|
||||
validation:
|
||||
|
||||
* check: "crate dependency rules respected"
|
||||
* check: "no panics in core"
|
||||
* check: "events used for cross-system communication"
|
||||
* check: "GameState mutations centralized"
|
||||
* check: "merge function properties preserved"
|
||||
* check: "no blocking operations in main loop"
|
||||
|
||||
---
|
||||
|
||||
## 14. Mental Model
|
||||
|
||||
model:
|
||||
|
||||
layers:
|
||||
- core
|
||||
- engine
|
||||
- data
|
||||
- server
|
||||
|
||||
flow:
|
||||
- input -> engine -> core -> engine -> ui
|
||||
- data <-> sync <-> server
|
||||
@@ -0,0 +1,335 @@
|
||||
# CLAUDE_WORKFLOW.md
|
||||
|
||||
version: 1.0
|
||||
|
||||
---
|
||||
|
||||
## 0. Overview
|
||||
|
||||
This workflow defines a **two-agent system**:
|
||||
|
||||
* **Builder Agent** → writes and modifies code
|
||||
* **Guardian Agent** → enforces architecture + rejects invalid changes
|
||||
|
||||
No code is considered valid unless it passes Guardian validation.
|
||||
|
||||
---
|
||||
|
||||
## 1. Agent Roles
|
||||
|
||||
### 1.1 Builder Agent
|
||||
|
||||
role: "code_generation"
|
||||
|
||||
responsibilities:
|
||||
|
||||
* implement features
|
||||
* refactor code
|
||||
* generate tests (only when justified)
|
||||
* follow CLAUDE_SPEC.md
|
||||
|
||||
constraints:
|
||||
|
||||
* cannot bypass validation
|
||||
* must declare intent before writing code
|
||||
|
||||
output_contract:
|
||||
must_produce:
|
||||
- change_summary
|
||||
- files_modified
|
||||
- reasoning (short)
|
||||
- code_diff
|
||||
|
||||
---
|
||||
|
||||
### 1.2 Guardian Agent
|
||||
|
||||
role: "architecture_enforcement"
|
||||
|
||||
responsibilities:
|
||||
|
||||
* validate against CLAUDE_SPEC.md
|
||||
* detect violations
|
||||
* reject or approve changes
|
||||
* suggest minimal fixes (not full rewrites)
|
||||
|
||||
constraints:
|
||||
|
||||
* no feature implementation
|
||||
* no large rewrites
|
||||
* must be deterministic
|
||||
|
||||
output_contract:
|
||||
must_produce:
|
||||
- status: APPROVED | REJECTED
|
||||
- violations[]
|
||||
- required_fixes[]
|
||||
- optional_improvements[]
|
||||
|
||||
---
|
||||
|
||||
## 2. Workflow Pipeline
|
||||
|
||||
```text
|
||||
User Request
|
||||
↓
|
||||
Builder Agent (proposal + code)
|
||||
↓
|
||||
Guardian Agent (validation)
|
||||
↓
|
||||
IF approved → commit
|
||||
IF rejected → feedback → Builder retry
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Builder Protocol
|
||||
|
||||
### Step 1 — Intent Declaration
|
||||
|
||||
Builder MUST start with:
|
||||
|
||||
```yaml
|
||||
intent:
|
||||
feature: "<name>"
|
||||
crates_touched: []
|
||||
systems_affected: []
|
||||
risk_level: low|medium|high
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 2 — Plan
|
||||
|
||||
```yaml
|
||||
plan:
|
||||
- step: "..."
|
||||
- step: "..."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 3 — Implementation
|
||||
|
||||
* Only modify declared crates
|
||||
* Follow ownership rules
|
||||
* Use events for cross-system communication
|
||||
|
||||
---
|
||||
|
||||
### Step 4 — Output
|
||||
|
||||
```yaml
|
||||
change_summary: "..."
|
||||
|
||||
files_modified:
|
||||
- path: ...
|
||||
change: "..."
|
||||
|
||||
violations_self_check:
|
||||
- none | list
|
||||
|
||||
notes: "short reasoning"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Guardian Protocol
|
||||
|
||||
### Step 1 — Spec Validation
|
||||
|
||||
Check against:
|
||||
|
||||
* crate boundaries
|
||||
* mutation rules
|
||||
* event system usage
|
||||
* sync guarantees
|
||||
* forbidden patterns
|
||||
|
||||
---
|
||||
|
||||
### Step 2 — Invariant Validation
|
||||
|
||||
Must verify:
|
||||
|
||||
* GameState invariants preserved
|
||||
* no new panic paths
|
||||
* no blocking calls in engine
|
||||
* merge properties unchanged
|
||||
|
||||
---
|
||||
|
||||
### Step 3 — Output Decision
|
||||
|
||||
#### APPROVED
|
||||
|
||||
```yaml
|
||||
status: APPROVED
|
||||
|
||||
notes:
|
||||
- "no violations"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### REJECTED
|
||||
|
||||
```yaml
|
||||
status: REJECTED
|
||||
|
||||
violations:
|
||||
- id: core_purity_violation
|
||||
file: "solitaire_core/src/..."
|
||||
reason: "uses std::fs"
|
||||
|
||||
required_fixes:
|
||||
- "move IO to solitaire_data"
|
||||
|
||||
optional_improvements:
|
||||
- "simplify event naming"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Enforcement Rules
|
||||
|
||||
### Hard Fail (automatic rejection)
|
||||
|
||||
* core crate uses IO / Bevy / network
|
||||
* GameState mutated outside GameLogicSystem
|
||||
* blocking async on main thread
|
||||
* duplicate logic across crates
|
||||
* merge function altered incorrectly
|
||||
|
||||
---
|
||||
|
||||
### Soft Fail (allowed but flagged)
|
||||
|
||||
* unnecessary complexity
|
||||
* redundant tests
|
||||
* minor architectural drift
|
||||
|
||||
---
|
||||
|
||||
## 6. Iteration Loop
|
||||
|
||||
Max attempts per task: **3**
|
||||
|
||||
```text
|
||||
Attempt 1 → Reject → Fix
|
||||
Attempt 2 → Reject → Fix
|
||||
Attempt 3 → Final decision
|
||||
```
|
||||
|
||||
If still failing:
|
||||
→ escalate to user
|
||||
|
||||
---
|
||||
|
||||
## 7. Diff Strategy
|
||||
|
||||
Builder MUST produce:
|
||||
|
||||
* minimal diffs
|
||||
* no unrelated refactors
|
||||
* no formatting-only changes
|
||||
|
||||
---
|
||||
|
||||
## 8. Test Strategy Integration
|
||||
|
||||
Builder rules:
|
||||
|
||||
* only add tests if:
|
||||
|
||||
* fixing a bug
|
||||
* protecting complex logic
|
||||
* validating invariants
|
||||
|
||||
Guardian rejects:
|
||||
|
||||
* redundant tests
|
||||
* no-op tests
|
||||
|
||||
---
|
||||
|
||||
## 9. Optional Extensions
|
||||
|
||||
### 9.1 Third Agent (Optimizer)
|
||||
|
||||
role: performance + cleanup
|
||||
|
||||
runs AFTER approval:
|
||||
|
||||
* reduce allocations
|
||||
* simplify logic
|
||||
* improve ECS scheduling
|
||||
|
||||
---
|
||||
|
||||
### 9.2 CI Integration
|
||||
|
||||
Pipeline:
|
||||
|
||||
```text
|
||||
Builder → Guardian → cargo check → clippy → tests
|
||||
```
|
||||
|
||||
Guardian runs BEFORE compilation to catch structural issues early.
|
||||
|
||||
---
|
||||
|
||||
## 10. Example Interaction
|
||||
|
||||
### Builder
|
||||
|
||||
```yaml
|
||||
intent:
|
||||
feature: "undo stack limit fix"
|
||||
crates_touched: [solitaire_core]
|
||||
risk_level: low
|
||||
```
|
||||
|
||||
```yaml
|
||||
change_summary: "limit undo stack to 64 entries"
|
||||
|
||||
files_modified:
|
||||
- solitaire_core/src/game_state.rs
|
||||
|
||||
notes: "prevents unbounded memory growth"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Guardian
|
||||
|
||||
```yaml
|
||||
status: APPROVED
|
||||
|
||||
notes:
|
||||
- "respects core constraints"
|
||||
- "no invariant violations"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Mental Model
|
||||
|
||||
* Builder = **creative**
|
||||
* Guardian = **strict**
|
||||
|
||||
Builder explores
|
||||
Guardian enforces
|
||||
|
||||
Neither replaces the other.
|
||||
|
||||
---
|
||||
|
||||
## 12. Success Criteria
|
||||
|
||||
System is working if:
|
||||
|
||||
* architectural violations go to ~0
|
||||
* code stays consistent across features
|
||||
* refactors become safe
|
||||
* complexity grows sub-linearly
|
||||
Generated
+308
-14
@@ -44,7 +44,7 @@ dependencies = [
|
||||
"accesskit_consumer",
|
||||
"hashbrown 0.15.5",
|
||||
"objc2 0.5.2",
|
||||
"objc2-app-kit",
|
||||
"objc2-app-kit 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
@@ -126,6 +126,19 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.4"
|
||||
@@ -313,6 +326,23 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
|
||||
dependencies = [
|
||||
"clipboard-win",
|
||||
"log",
|
||||
"objc2 0.6.4",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.60.2",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
version = "1.9.1"
|
||||
@@ -702,7 +732,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"console_error_panic_hook",
|
||||
"ctrlc",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"log",
|
||||
"thiserror 2.0.18",
|
||||
"variadics_please",
|
||||
@@ -736,7 +766,7 @@ dependencies = [
|
||||
"crossbeam-channel",
|
||||
"derive_more",
|
||||
"disqualified",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"either",
|
||||
"futures-io",
|
||||
"futures-lite",
|
||||
@@ -784,7 +814,7 @@ dependencies = [
|
||||
"bevy_utils",
|
||||
"bevy_window",
|
||||
"derive_more",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"thiserror 2.0.18",
|
||||
@@ -1183,7 +1213,7 @@ dependencies = [
|
||||
"bevy_utils",
|
||||
"derive_more",
|
||||
"disqualified",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"erased-serde",
|
||||
"foldhash 0.2.0",
|
||||
"glam 0.30.10",
|
||||
@@ -1242,7 +1272,7 @@ dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"encase",
|
||||
"fixedbitset",
|
||||
"glam 0.30.10",
|
||||
@@ -1837,6 +1867,18 @@ dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "calloop-wayland-source"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
|
||||
dependencies = [
|
||||
"calloop",
|
||||
"rustix 0.38.44",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.1.2"
|
||||
@@ -1972,6 +2014,15 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
|
||||
dependencies = [
|
||||
"error-code",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.58"
|
||||
@@ -2683,6 +2734,12 @@ version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "downcast-rs"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
|
||||
|
||||
[[package]]
|
||||
name = "downcast-rs"
|
||||
version = "2.0.2"
|
||||
@@ -2882,6 +2939,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "error-code"
|
||||
version = "3.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
|
||||
|
||||
[[package]]
|
||||
name = "etcetera"
|
||||
version = "0.8.0"
|
||||
@@ -4968,6 +5031,18 @@ dependencies = [
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-app-kit"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"objc2 0.6.4",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-audio-toolbox"
|
||||
version = "0.3.2"
|
||||
@@ -5065,6 +5140,19 @@ dependencies = [
|
||||
"objc2 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-graphics"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"dispatch2",
|
||||
"objc2 0.6.4",
|
||||
"objc2-core-foundation",
|
||||
"objc2-io-surface",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-image"
|
||||
version = "0.2.2"
|
||||
@@ -5121,6 +5209,17 @@ dependencies = [
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-io-surface"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"objc2 0.6.4",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-link-presentation"
|
||||
version = "0.2.2"
|
||||
@@ -5129,7 +5228,7 @@ checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
|
||||
dependencies = [
|
||||
"block2 0.5.1",
|
||||
"objc2 0.5.2",
|
||||
"objc2-app-kit",
|
||||
"objc2-app-kit 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
@@ -5724,6 +5823,15 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "958f21e8e7ceb5a1aa7fa87fab28e7c75976e0bfe7e23ff069e0a260f894067d"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.9"
|
||||
@@ -6097,7 +6205,7 @@ dependencies = [
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.12.0",
|
||||
"usvg",
|
||||
"zune-jpeg",
|
||||
]
|
||||
@@ -6434,6 +6542,19 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "sctk-adwaita"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
|
||||
dependencies = [
|
||||
"ab_glyph",
|
||||
"log",
|
||||
"memmap2",
|
||||
"smithay-client-toolkit",
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.7.3"
|
||||
@@ -6778,6 +6899,31 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smithay-client-toolkit"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"calloop",
|
||||
"calloop-wayland-source",
|
||||
"cursor-icon",
|
||||
"libc",
|
||||
"log",
|
||||
"memmap2",
|
||||
"rustix 0.38.44",
|
||||
"thiserror 1.0.69",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-csd-frame",
|
||||
"wayland-cursor",
|
||||
"wayland-protocols",
|
||||
"wayland-protocols-wlr",
|
||||
"wayland-scanner",
|
||||
"xkeysym",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smol_str"
|
||||
version = "0.2.2"
|
||||
@@ -6856,6 +7002,7 @@ dependencies = [
|
||||
name = "solitaire_engine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-trait",
|
||||
"bevy",
|
||||
"chrono",
|
||||
@@ -6869,7 +7016,7 @@ dependencies = [
|
||||
"solitaire_sync",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.12.0",
|
||||
"tokio",
|
||||
"usvg",
|
||||
"uuid",
|
||||
@@ -7456,7 +7603,7 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"crossbeam-channel",
|
||||
"datasketches",
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"fastdivide",
|
||||
"fnv",
|
||||
"fs4",
|
||||
@@ -7508,7 +7655,7 @@ version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c57166f5bcfd478f370ab8445afb4678dce44801fa5ce5c451aaf8595583c5dc"
|
||||
dependencies = [
|
||||
"downcast-rs",
|
||||
"downcast-rs 2.0.2",
|
||||
"fastdivide",
|
||||
"itertools 0.14.0",
|
||||
"serde",
|
||||
@@ -7696,6 +7843,20 @@ dependencies = [
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia"
|
||||
version = "0.11.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"arrayvec",
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"tiny-skia-path 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia"
|
||||
version = "0.12.0"
|
||||
@@ -7708,7 +7869,18 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia-path"
|
||||
version = "0.11.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"bytemuck",
|
||||
"strict-num",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8479,7 +8651,7 @@ dependencies = [
|
||||
"siphasher",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
"tiny-skia-path 0.12.0",
|
||||
"ttf-parser",
|
||||
"unicode-bidi",
|
||||
"unicode-script",
|
||||
@@ -8685,6 +8857,114 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"downcast-rs 1.2.1",
|
||||
"rustix 1.1.4",
|
||||
"scoped-tls",
|
||||
"smallvec",
|
||||
"wayland-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-client"
|
||||
version = "0.31.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"rustix 1.1.4",
|
||||
"wayland-backend",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-csd-frame"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"cursor-icon",
|
||||
"wayland-backend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-cursor"
|
||||
version = "0.31.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
|
||||
dependencies = [
|
||||
"rustix 1.1.4",
|
||||
"wayland-client",
|
||||
"xcursor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols"
|
||||
version = "0.32.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-plasma"
|
||||
version = "0.3.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-wlr"
|
||||
version = "0.3.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-scanner"
|
||||
version = "0.31.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quick-xml",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-sys"
|
||||
version = "0.31.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
|
||||
dependencies = [
|
||||
"dlib",
|
||||
"log",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.97"
|
||||
@@ -9500,6 +9780,7 @@ version = "0.30.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"android-activity",
|
||||
"atomic-waker",
|
||||
"bitflags 2.11.1",
|
||||
@@ -9514,9 +9795,10 @@ dependencies = [
|
||||
"dpi",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"memmap2",
|
||||
"ndk",
|
||||
"objc2 0.5.2",
|
||||
"objc2-app-kit",
|
||||
"objc2-app-kit 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2-ui-kit",
|
||||
"orbclient",
|
||||
@@ -9525,11 +9807,17 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"redox_syscall 0.4.1",
|
||||
"rustix 0.38.44",
|
||||
"sctk-adwaita",
|
||||
"smithay-client-toolkit",
|
||||
"smol_str",
|
||||
"tracing",
|
||||
"unicode-segmentation",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-protocols-plasma",
|
||||
"web-sys",
|
||||
"web-time",
|
||||
"windows-sys 0.52.0",
|
||||
@@ -9697,6 +9985,12 @@ version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
|
||||
|
||||
[[package]]
|
||||
name = "xcursor"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b"
|
||||
|
||||
[[package]]
|
||||
name = "xkbcommon-dl"
|
||||
version = "0.4.2"
|
||||
|
||||
+7
-1
@@ -30,6 +30,7 @@ dirs = "6"
|
||||
keyring = "4"
|
||||
keyring-core = "1"
|
||||
reqwest = { version = "0.13", features = ["json", "rustls", "rustls-native-certs"], default-features = false }
|
||||
arboard = { version = "3", default-features = false }
|
||||
|
||||
solitaire_core = { path = "solitaire_core" }
|
||||
solitaire_sync = { path = "solitaire_sync" }
|
||||
@@ -53,11 +54,16 @@ bevy = { version = "0.18", default-features = false, features = [
|
||||
"bevy_window",
|
||||
"custom_cursor",
|
||||
"reflect_auto_register",
|
||||
# default_platform (desktop subset; no android/wayland/webgl/gilrs/sysinfo)
|
||||
# default_platform (desktop subset; no android/webgl/gilrs/sysinfo)
|
||||
"std",
|
||||
"bevy_winit",
|
||||
"default_font",
|
||||
"multi_threaded",
|
||||
# winit prefers Wayland when WAYLAND_DISPLAY is set on the
|
||||
# session and falls through to X11 otherwise. Without `wayland`,
|
||||
# winit-on-Wayland-session falls back to XWayland which renders
|
||||
# the game in an X11 frame inside the Wayland compositor.
|
||||
"wayland",
|
||||
"x11",
|
||||
# common_api
|
||||
"bevy_color",
|
||||
|
||||
+136
-67
@@ -1,111 +1,180 @@
|
||||
# Solitaire Quest — Session Handoff
|
||||
|
||||
**Last updated:** 2026-05-06 (post-v0.17.0) — v0.17.0 cut on top of v0.16.0 bundling the solver-driven hints (`87275bf`) and the replay-rate slider (`53e3b81`). An async-solver attempt earlier in the session was rolled back when an agent left 3 failing tests during interruption — flagged as carryover. Test-to-work ratio noted as a quality signal: future agent briefs scale back to behaviour-level tests only, not stdlib/serde-derive coverage.
|
||||
**Last updated:** 2026-05-06 (post-v0.19.0) — Tagged + pushed at
|
||||
`6037596`. v0.19.0 closes the v0.18.0 punch list (async H-key hint,
|
||||
persistent replay share URLs), expands desktop platform fit (Wayland
|
||||
session support + monitor-aware default window size), polishes the
|
||||
win-celebration and double-click animation paths, and clears two
|
||||
test-flake contributors. A short-lived "Rusty Pixel" pixel-art card
|
||||
theme was prototyped and reverted in the same window.
|
||||
|
||||
## Status at pause
|
||||
|
||||
- **HEAD on origin:** v0.17.0's tag commit.
|
||||
- **Working tree:** clean apart from untracked `CARD_PLAN.md` (intentional).
|
||||
- **Build:** `cargo clippy --workspace --all-targets -- -D warnings` clean.
|
||||
- **Tests:** **1208 passed / 0 failed** across the workspace.
|
||||
- **Tags on origin:** `v0.9.0` through `v0.17.0`.
|
||||
- **HEAD on origin:** `6037596` (post-tag commit; the tag itself
|
||||
points at this commit).
|
||||
- **Working tree:** modified — `CHANGELOG.md` and
|
||||
`SESSION_HANDOFF.md` carry the v0.19.0 promotion + this refresh,
|
||||
ready to commit.
|
||||
- **Build:** `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
clean (verified this session).
|
||||
- **Tests:** **1170 passing / 0 failing** across the workspace
|
||||
(verified this session). One known flake remains:
|
||||
`solitaire_engine::sync_plugin::tests::pull_failure_sets_error_status`
|
||||
occasionally fails when cargo-test parallelism starves the
|
||||
`AsyncComputeTaskPool` within the test's 5-update budget. Same
|
||||
shape as the auto-save flake before v0.19.0's hardening; could be
|
||||
fixed similarly with a wall-clock-bounded loop.
|
||||
- **Tags on origin:** `v0.9.0` through `v0.18.0` (v0.19.0 ready to
|
||||
push once committed).
|
||||
|
||||
## Where we are
|
||||
|
||||
v0.16.0 is the smallest meaningful release in a while — a focused round on how modals feel rather than what they contain. The originating bug was "I can't scroll on the Achievements list"; the sweep that followed found four other modals with the same problem plus three smaller modal-feel gaps (no pointer cursor on buttons, focus arriving a frame late, no click-outside-to-dismiss).
|
||||
v0.18.0's resume-prompt menu (A–D) is closed:
|
||||
|
||||
Every overlay screen now: scrolls if its content can overflow at 800×600, shows a hand cursor when you hover any button, has its primary auto-focused the moment the modal appears so the very first Tab/Enter is meaningful, and (for read-only screens) dismisses when you click outside the card.
|
||||
- ~~**A — Tag v0.18.0:**~~ shipped at `bfcd05f`.
|
||||
- ~~**B — Solver-on-`AsyncComputeTaskPool` for the H-key hint:**~~
|
||||
shipped at `3e11e9e`.
|
||||
- **C — Desktop packaging:** still gated on artwork + signing
|
||||
certs. Icon export PNGs (11 sizes, 16–1024 px) sit in
|
||||
`artwork/` from the v0.18-era export; not yet wired into the
|
||||
Bevy window or assembled into `.icns` / `.ico`. App icon is
|
||||
the first natural step.
|
||||
- ~~**D — Persistent share link:**~~ shipped at `42d90b1`.
|
||||
|
||||
The post-v0.15.0 next-round candidates are still mostly open — solver-driven hints, replay-rate slider, solver progress overlay, async solver, "won previously" indicator, replay sharing. Direction is open.
|
||||
The Rusty Pixel theme arc is documented as a sub-history but
|
||||
not part of v0.19.0's content:
|
||||
|
||||
| Commit | Status |
|
||||
|---|---|
|
||||
| `de47511` PNG-format thumbnail support | reverted |
|
||||
| `17e3112` `pixel_art: bool` field + nearest-sampling opt-in | reverted |
|
||||
| `21ec03b` bundle Rusty Pixel as `embedded://` theme | reverted |
|
||||
| `aad8bb9` / `e41def8` / `0b3140a` reverts | landed |
|
||||
|
||||
The arc remains in commit history for archaeology but the
|
||||
codebase reaches v0.19.0's HEAD identical to where it would be if
|
||||
the arc had never landed.
|
||||
|
||||
### Design direction (unchanged)
|
||||
|
||||
- **Tone:** Balatro — chunky readable type, theatrical hierarchy, satisfying micro-interactions.
|
||||
- **Palette:** Midnight Purple base + Balatro yellow primary + warm magenta secondary.
|
||||
- See `~/.claude/projects/-home-manage-Rusty-Solitare/memory/project_ux_overhaul_2026-04.md` (machine-local).
|
||||
- **Tone:** Balatro — chunky readable type, theatrical hierarchy,
|
||||
satisfying micro-interactions.
|
||||
- **Palette:** Midnight Purple base + Balatro yellow primary + warm
|
||||
magenta secondary.
|
||||
|
||||
### Canonical remote
|
||||
|
||||
`github.com/funman300/Rusty_Solitaire` is the canonical repo. Always push there.
|
||||
`github.com/funman300/Rusty_Solitaire` is the canonical repo.
|
||||
Always push there.
|
||||
|
||||
## v0.17.0 (shipped 2026-05-06)
|
||||
## v0.19.0 (2026-05-06)
|
||||
|
||||
| Area | Commit | What landed |
|
||||
| Area | Commits | What landed |
|
||||
|---|---|---|
|
||||
| Solver-driven hints | `87275bf` | The H-key hint asks the solver for the actual best first move via `try_solve_with_first_move` / `try_solve_from_state`. Heuristic stays as fallback. Median 2 ms per H press. |
|
||||
| Replay-rate slider | `53e3b81` | Settings → Gameplay slider tunes `replay_move_interval_secs` 0.10–1.00 s in 0.05 s steps; default 0.45 s. Read per frame from `SettingsResource`. |
|
||||
|
||||
## v0.16.0 (shipped 2026-05-06)
|
||||
|
||||
| Area | Commit | What landed |
|
||||
|---|---|---|
|
||||
| Modal scroll | `7a3032b` | Achievements / Help / Stats / Profile / Leaderboard bodies now carry `Overflow::scroll_y()` + a `max_height` constraint + a per-plugin `*Scrollable` marker. Sibling `scroll_*_panel` systems route `MouseWheel` into the body's `ScrollPosition`. Mirrors the existing `SettingsPanelScrollable` pattern. Home modal not scrolled — five mode cards + Cancel are sized to fit by design. |
|
||||
| Pointer cursor | `cd54ce1` | `update_cursor_icon` gains a fourth branch: `SystemCursorIcon::Pointer` whenever any `Interaction::Hovered`/`Pressed` button is detected and no card drag is active. Branch order Grabbing → Pointer → Grab → Default. Pure `pick_cursor_icon(is_dragging, any_button_hovered, any_card_hovered)` helper unit-tests the priority. |
|
||||
| Same-frame focus | `48e4121` | `attach_focusable_to_modal_buttons` and `auto_focus_on_modal_open` moved from `Update` to `PostUpdate`. The schedule boundary supplies the sync point so a click-handler in `Update` that spawns a modal has its `Commands` materialised before attach runs. `FocusedButton` is populated before `app.update()` returns; the very first Tab/Enter after open lands on a populated resource. |
|
||||
| Scrim dismiss core | `a54201e` | New `ScrimDismissible` marker on `ModalScrim` opts a modal into click-outside-to-close. `dismiss_modal_on_scrim_click` system in `ui_modal` despawns the topmost dismissible scrim on a left-mouse press whose cursor lands on the scrim and outside every `ModalCard`. Stats / Achievements / Help opted in. |
|
||||
| Scrim dismiss tail | `cbf2483` | One-line opt-in (capture scrim + insert marker) for Profile / Leaderboard / Home, completing all six read-only modals. |
|
||||
| Async H-key hint | `3e11e9e` | New `pending_hint.rs` module: `PendingHintTask` resource, `poll_pending_hint_task` + `drop_pending_hint_on_state_change` systems, cancel-on-replace, stale-state guard via `move_count_at_spawn`. Removes the last synchronous solver hot path. |
|
||||
| Persistent share URLs | `42d90b1` | `Replay.share_url: Option<String>` with `#[serde(default)]`. `poll_replay_upload_result` writes into `replays[0].share_url` + persists. Stats Copy button reads from selected replay. `LastSharedReplayUrl` deleted. |
|
||||
| Auto-save flake fix | `91b7605` | `test_app` clears `PendingRestoredGame(None)` after plugin build; test re-arms the timer in a bounded loop. No production-code change. |
|
||||
| Wayland support | `b57db01` | Adds `wayland` to Bevy features. winit prefers Wayland when `WAYLAND_DISPLAY` is set, falls back to X11. Native Wayland surface instead of XWayland frame. |
|
||||
| Smart default window size | `b57db01` | New `apply_smart_default_window_size` Update system queries `PrimaryMonitor` and resizes the window to ~70 % of monitor's logical size on the first frame. Skipped when saved geometry was applied. |
|
||||
| Win-celebration cleanup | `55c235b` | Drops the duplicate "You Win" toast that rendered behind the WinSummary modal. Cards-fly-off cascade kept; toast removed. |
|
||||
| Double-click reject animation | `d7ffb16` | Single-card double-clicks with no destination now play the same shake + sound as multi-card stack misses. Both priorities' failure paths converge on one `MoveRejectedEvent` write. |
|
||||
| Double-click animation dedup | `6037596` | Drops the redundant `StateChangedEvent` write in `end_drag`'s uncommitted-drag branch; previously raced an in-flight CardAnim and restarted the slide visibly. |
|
||||
|
||||
## Open punch list
|
||||
|
||||
### Release prep
|
||||
### Carried forward
|
||||
|
||||
1. **Desktop packaging** per `ARCHITECTURE.md §17`. Arch PKGBUILD exists in `/home/manage/solitaire-quest-pkgbuild/` (separate repo). Pending: app icon, macOS `.icns` + notarisation cert, Windows `.ico` + Authenticode cert, AppImage recipe.
|
||||
- **Desktop packaging** per `ARCHITECTURE.md §17`. Eleven icon
|
||||
PNG sizes (16, 24, 32, 48, 64, 96, 128, 192, 256, 512, 1024)
|
||||
exported via `artwork/Icon Export.html` sit in `artwork/`
|
||||
pending wiring. Pending: actual Bevy window-icon hookup,
|
||||
macOS `.icns` assembly via `iconutil`, Windows `.ico` via
|
||||
`magick convert`, Linux hicolor PNG hierarchy install,
|
||||
AppImage recipe, macOS notarisation cert, Windows
|
||||
Authenticode cert.
|
||||
|
||||
### Process note (raised this session)
|
||||
### Possible next-round candidates
|
||||
|
||||
Recent agent briefs reflexively asked for ≥3 tests per feature, which produced low-value coverage on trivial settings fields (default-value tests, serde-derive round-trips, clamp tests that just exercise stdlib `clamp`). Future agent briefs should ask only for tests that pin **behaviour contracts or regressions on real bugs** — not coverage of language/library mechanics.
|
||||
- **App icon round** — wire the icon into the Bevy window via
|
||||
`Window::icon`, generate `.icns` and `.ico` from the existing
|
||||
PNGs. Half-day task; doesn't depend on signing certs.
|
||||
- **`pull_failure_sets_error_status` flake fix** — same pattern
|
||||
as the auto-save flake. Wall-clock-bounded loop instead of
|
||||
fixed 5-update budget. ~10 lines.
|
||||
- **Settings UI for "open at this size on launch"** — once the
|
||||
smart-default-size system is shipping, expose a checkbox to
|
||||
*disable* it (player who specifically wants 1280×800 every
|
||||
time). Trivial.
|
||||
- **Persistent share link URL on selector caption** — surface
|
||||
whether the currently-selected replay has a `share_url`
|
||||
populated (e.g. "Replay 3 / 8 \u{2022} Shareable") so players
|
||||
know which entries the Copy button can copy.
|
||||
|
||||
### Carryover candidates — still open
|
||||
### Process notes (from this round)
|
||||
|
||||
- **Solver-on-AsyncComputeTaskPool** — current solver runs synchronously on the main thread. Worst-case 50 attempts × 120 ms = 6 s of UI stall on pathological seeds. **An attempt this session was rolled back** when an agent was interrupted leaving 3 failing tests; redoing this needs more careful scoping (smaller pieces, real cancel-and-test flow, NOT a parallel agent split). Worth taking next.
|
||||
- **Per-deal "won previously" indicator** — the rolling replay history's seeds make this easy: when a new game starts on a seed the player has already won, surface a tiny indicator on the HUD.
|
||||
- **Replay sharing** — `replays.json` is per-machine. Allow a player to copy a replay's URL (already wired via `solitaire_server`) and post it elsewhere. The web-viewer already exists.
|
||||
- **Async port template (worked again):** the H-key port
|
||||
followed `d489e7a`'s `PendingNewGameSeed` shape one-to-one
|
||||
and the second async port required no new infrastructure.
|
||||
Future async ports (e.g. moving `try_solve_with_first_move`'s
|
||||
full-search variant, if it ever surfaces in the picker UI)
|
||||
should follow the same shape.
|
||||
- **Rusty Pixel reverted cleanly:** `git revert` of three
|
||||
contiguous feature commits produced a clean three-revert
|
||||
sequence with no manual conflict resolution. Bisect remains
|
||||
fast over the full v0.19.0 history because the reverts are
|
||||
individual commits, not a squash.
|
||||
- **Defensive event writes pattern:** the
|
||||
`auto_save_writes_after_30_seconds` flake AND the
|
||||
`end_drag` double-animation bug shared a root cause:
|
||||
defensive `MessageWriter` writes that originally covered an
|
||||
edge case which no longer holds, but became load-bearing
|
||||
once another system started paying attention to the event.
|
||||
Worth a periodic pass: any event write that doesn't
|
||||
correspond to a real state change is a candidate for
|
||||
removal.
|
||||
|
||||
## Resume prompt
|
||||
|
||||
```
|
||||
You are a senior Rust + Bevy developer working on Solitaire Quest.
|
||||
Working directory: <Rusty_Solitaire clone path on this machine — local
|
||||
directory may still be named Rusty_Solitare from earlier; that's fine>.
|
||||
Branch: master. Direction is OPEN — v0.16.0 just shipped covering
|
||||
modal scroll fixes, pointer cursor, same-frame focus, and scrim-click
|
||||
dismiss across all six read-only modals.
|
||||
Working directory: <Rusty_Solitaire clone path on this machine>.
|
||||
Branch: master. v0.19.0 just shipped. The next natural item is
|
||||
desktop-packaging follow-through, starting with the app icon.
|
||||
|
||||
State: HEAD at v0.17.0 (solver hints + replay-rate slider on top
|
||||
of v0.16.0). Working tree clean apart from untracked CARD_PLAN.md
|
||||
(intentional).
|
||||
Build: cargo clippy --workspace --all-targets -- -D warnings clean.
|
||||
Tests: 1208 passed / 0 failed.
|
||||
State: HEAD at 6037596 + the v0.19.0 docs commit on top (this
|
||||
session). Tag v0.19.0 points at the docs commit.
|
||||
|
||||
READ FIRST (in order, before doing anything):
|
||||
1. SESSION_HANDOFF.md — v0.16.0 changelog + open punch list
|
||||
2. CHANGELOG.md — release-by-release record
|
||||
3. CLAUDE.md — hard rules (UI-first, no panics, etc.)
|
||||
4. ARCHITECTURE.md — crate responsibilities + data flow
|
||||
5. ~/.claude/projects/<this-project>/memory/MEMORY.md
|
||||
— saved feedback / project context (machine-local;
|
||||
may be missing on a fresh machine)
|
||||
1. SESSION_HANDOFF.md — this file
|
||||
2. CHANGELOG.md — [Unreleased] is empty; [0.19.0] just landed
|
||||
3. CLAUDE.md — unified-3.0 rule set
|
||||
4. CLAUDE_SPEC.md — formal architecture spec
|
||||
5. ARCHITECTURE.md — crate responsibilities + data flow
|
||||
6. ~/.claude/projects/<this-project>/memory/MEMORY.md
|
||||
— saved feedback / project context
|
||||
(machine-local; may be missing on a
|
||||
fresh machine)
|
||||
|
||||
DECISION TO ASK THE PLAYER FIRST:
|
||||
A. Solver-on-AsyncComputeTaskPool with progress toast + cancel.
|
||||
A previous attempt was rolled back when an agent left 3
|
||||
failing tests; redoing it needs smaller pieces. Eliminates the
|
||||
worst-case 6 s UI stall — highest gameplay impact left.
|
||||
B. Per-deal "won previously" HUD indicator using the rolling
|
||||
replay history's seeds.
|
||||
C. Replay sharing — copyable URL via the existing web viewer.
|
||||
D. Take the deferred desktop-packaging item (needs artwork +
|
||||
signing certs from the user).
|
||||
A. App icon — wire artwork/icon-{size}.png into Bevy's
|
||||
Window::icon, generate .icns + .ico, drop into Linux
|
||||
hicolor hierarchy. Half-day task. No cert dependency.
|
||||
B. Desktop packaging continued — AppImage recipe, .desktop
|
||||
file, install scripts. Larger task; unlocks distro
|
||||
packaging. No cert dependency.
|
||||
C. macOS / Windows signing cert acquisition — needs user
|
||||
action; agent can't drive.
|
||||
D. `pull_failure_sets_error_status` flake fix — small, well-
|
||||
scoped. Same pattern as the v0.19.0 auto-save flake fix.
|
||||
|
||||
WORKFLOW NOTES:
|
||||
- Commits use:
|
||||
git -c user.name=funman300 -c user.email=root@vscode.infinity \
|
||||
commit -m "..."
|
||||
- When attributing playtester feedback in commits/docs, use "Quat"
|
||||
not "Rhys" (saved feedback memory).
|
||||
- Use the system git config (already correct).
|
||||
- When attributing playtester feedback in commits/docs, use
|
||||
"Quat" not "Rhys" (saved feedback memory).
|
||||
- Sub-agents stage + verify only; orchestrator commits.
|
||||
- Every commit must pass build / clippy / test before pushing.
|
||||
- Push to GitHub (origin) — that is the canonical remote.
|
||||
- Push to GitHub (origin) — gh auth setup-git is already
|
||||
wired on this machine.
|
||||
|
||||
OPEN AT THE START: ask which of A–D. Don't pick unilaterally.
|
||||
```
|
||||
|
||||
@@ -3,7 +3,9 @@ use std::io::Write;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{MonitorSelection, PresentMode, WindowPosition};
|
||||
use bevy::window::{
|
||||
Monitor, MonitorSelection, PresentMode, PrimaryMonitor, PrimaryWindow, WindowPosition,
|
||||
};
|
||||
use solitaire_data::{load_settings_from, provider_for_backend, settings_file_path, Settings};
|
||||
use solitaire_engine::{
|
||||
register_theme_asset_sources, AchievementPlugin, AnimationPlugin, AssetSourcesPlugin,
|
||||
@@ -43,8 +45,10 @@ fn main() {
|
||||
|
||||
// Restore the previous window geometry if the player has one saved.
|
||||
// Otherwise open at the platform default (1280×800, centred on the
|
||||
// primary monitor). The window_geometry field is None on first run
|
||||
// and after upgrading from a build that didn't persist geometry.
|
||||
// primary monitor) — `apply_smart_default_window_size` will resize
|
||||
// up to a monitor-relative target on the first frame so HiDPI / 4K
|
||||
// sessions don't end up with a comparatively tiny window.
|
||||
let had_saved_geometry = settings.window_geometry.is_some();
|
||||
let (window_resolution, window_position) = match settings.window_geometry {
|
||||
Some(geom) => (
|
||||
(geom.width, geom.height).into(),
|
||||
@@ -129,7 +133,7 @@ fn main() {
|
||||
.add_plugins(TimeAttackPlugin)
|
||||
.add_plugins(HudPlugin)
|
||||
.add_plugins(HelpPlugin)
|
||||
.add_plugins(HomePlugin)
|
||||
.add_plugins(HomePlugin::default())
|
||||
.add_plugins(ProfilePlugin)
|
||||
.add_plugins(PausePlugin)
|
||||
.add_plugins(SettingsPlugin::default())
|
||||
@@ -141,8 +145,78 @@ fn main() {
|
||||
.add_plugins(UiModalPlugin)
|
||||
.add_plugins(UiFocusPlugin)
|
||||
.add_plugins(UiTooltipPlugin)
|
||||
.add_plugins(SplashPlugin)
|
||||
.run();
|
||||
.add_plugins(SplashPlugin);
|
||||
|
||||
// Smart default window sizing: when no saved geometry was loaded,
|
||||
// resize the freshly-opened 1280×800 window to ~70 % of the primary
|
||||
// monitor's logical size on the first frame. Without this, a 4K
|
||||
// monitor opens the same 1280×800 window that a 1080p monitor
|
||||
// does — visually tiny relative to screen. Skipped entirely when
|
||||
// saved geometry was applied; the player's preference always wins.
|
||||
if !had_saved_geometry {
|
||||
app.add_systems(Update, apply_smart_default_window_size);
|
||||
}
|
||||
|
||||
app.run();
|
||||
}
|
||||
|
||||
/// One-shot Update system that runs only on launches without saved
|
||||
/// window geometry. Resizes the primary window to a fraction of the
|
||||
/// primary monitor's *logical* size — bigger monitors get bigger
|
||||
/// windows automatically. Logical size already accounts for the OS's
|
||||
/// HiDPI scale factor, so a 2880×1800 Retina display reporting
|
||||
/// scale_factor 2.0 yields a 1440×900 logical size and a 1008×630
|
||||
/// target window — same physical inches as a 1920×1080 monitor with
|
||||
/// scale_factor 1.0 yielding 1344×756.
|
||||
///
|
||||
/// Uses `Local<bool>` to make itself one-shot rather than introducing
|
||||
/// a dedicated resource. The Update tick is necessary because Bevy
|
||||
/// populates the `Monitor` entities asynchronously after winit's
|
||||
/// Resumed event fires; they may not exist on the first Startup pass.
|
||||
fn apply_smart_default_window_size(
|
||||
mut applied: Local<bool>,
|
||||
monitors: Query<&Monitor, With<PrimaryMonitor>>,
|
||||
mut windows: Query<&mut Window, With<PrimaryWindow>>,
|
||||
) {
|
||||
if *applied {
|
||||
return;
|
||||
}
|
||||
let Ok(monitor) = monitors.single() else {
|
||||
// Primary monitor not yet spawned by bevy_winit. Try again
|
||||
// next frame; the cost is one early-exit per tick until
|
||||
// monitors arrive (typically frame 1 or 2).
|
||||
return;
|
||||
};
|
||||
let Ok(mut window) = windows.single_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let scale = monitor.scale_factor as f32;
|
||||
if scale <= 0.0 {
|
||||
// Defensive: a zero or negative scale factor would NaN the
|
||||
// arithmetic below. Bail and accept the default size.
|
||||
*applied = true;
|
||||
return;
|
||||
}
|
||||
let logical_w = monitor.physical_width as f32 / scale;
|
||||
let logical_h = monitor.physical_height as f32 / scale;
|
||||
|
||||
// Target 70 % of monitor in each dimension, clamped to the
|
||||
// existing 800×600 minimum and the monitor's own logical size
|
||||
// (so we never request a window larger than the screen).
|
||||
let target_w = (logical_w * 0.7).clamp(800.0, logical_w);
|
||||
let target_h = (logical_h * 0.7).clamp(600.0, logical_h);
|
||||
|
||||
// Resize only when the change is meaningful — at exactly 1280×800
|
||||
// on a 1920×1080 monitor the new target is 1344×756 (only ~5 %
|
||||
// wider), worth the resize; at the same default on an 800×600
|
||||
// monitor the clamp pins us at 800×600 and we shouldn't resize.
|
||||
let curr_w = window.resolution.width();
|
||||
let curr_h = window.resolution.height();
|
||||
if (curr_w - target_w).abs() > 8.0 || (curr_h - target_h).abs() > 8.0 {
|
||||
window.resolution.set(target_w, target_h);
|
||||
}
|
||||
*applied = true;
|
||||
}
|
||||
|
||||
/// Wraps the default panic hook with one that also appends a crash log
|
||||
|
||||
@@ -77,16 +77,6 @@ pub struct Card {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rank_value_ace_is_one() {
|
||||
assert_eq!(Rank::Ace.value(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_value_king_is_thirteen() {
|
||||
assert_eq!(Rank::King.value(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_values_are_sequential() {
|
||||
let ranks = [
|
||||
@@ -100,26 +90,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suit_red_is_diamonds_and_hearts() {
|
||||
assert!(Suit::Diamonds.is_red());
|
||||
assert!(Suit::Hearts.is_red());
|
||||
assert!(!Suit::Clubs.is_red());
|
||||
assert!(!Suit::Spades.is_red());
|
||||
fn suit_red_and_black_are_complementary() {
|
||||
for suit in [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades] {
|
||||
assert_ne!(suit.is_red(), suit.is_black(), "{suit:?} must be exactly one of red/black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suit_black_is_clubs_and_spades() {
|
||||
assert!(Suit::Clubs.is_black());
|
||||
assert!(Suit::Spades.is_black());
|
||||
assert!(!Suit::Diamonds.is_black());
|
||||
assert!(!Suit::Hearts.is_black());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_face_up_field_reflects_construction() {
|
||||
let card = Card { id: 0, suit: Suit::Hearts, rank: Rank::Ace, face_up: false };
|
||||
assert!(!card.face_up);
|
||||
let card2 = Card { id: 1, suit: Suit::Spades, rank: Rank::King, face_up: true };
|
||||
assert!(card2.face_up);
|
||||
assert!(Suit::Diamonds.is_red() && Suit::Hearts.is_red());
|
||||
assert!(Suit::Clubs.is_black() && Suit::Spades.is_black());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,11 +815,6 @@ mod tests {
|
||||
assert!(g.undo_stack_len() <= 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_count_starts_at_zero() {
|
||||
assert_eq!(new_game().undo_count, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_count_increments_on_each_undo() {
|
||||
let mut g = new_game();
|
||||
@@ -900,11 +895,6 @@ mod tests {
|
||||
assert_eq!(g.score, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zen_mode_default_is_classic_via_default_trait() {
|
||||
assert_eq!(GameMode::default(), GameMode::Classic);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zen_mode_field_persists_through_construction() {
|
||||
let g = GameState::new_with_mode(1, DrawMode::DrawThree, GameMode::Zen);
|
||||
@@ -956,12 +946,6 @@ mod tests {
|
||||
assert!(g.undo().is_ok(), "undo must be permitted in TimeAttack mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_attack_score_starts_at_zero() {
|
||||
let g = GameState::new_with_mode(42, DrawMode::DrawOne, GameMode::TimeAttack);
|
||||
assert_eq!(g.score, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_attack_draw_three_combination() {
|
||||
// TimeAttack + DrawThree is a valid combination; verify construction.
|
||||
|
||||
@@ -90,9 +90,4 @@ mod tests {
|
||||
seeds.dedup();
|
||||
assert_eq!(seeds.len(), len_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn challenge_count_matches_seed_list_length() {
|
||||
assert_eq!(challenge_count() as usize, CHALLENGE_SEEDS.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,13 +56,13 @@ pub trait SyncProvider: Send + Sync {
|
||||
async fn delete_account(&self) -> Result<(), SyncError> {
|
||||
Ok(())
|
||||
}
|
||||
/// Upload a winning replay to the backend so it's available for web
|
||||
/// playback at `<server>/replays/<id>`. Default returns
|
||||
/// `UnsupportedPlatform` so backends without a server (e.g.
|
||||
/// `LocalOnlyProvider`) are silently no-op'd by the engine's
|
||||
/// push-on-win system, matching the same pattern `pull` / `push`
|
||||
/// follow.
|
||||
async fn push_replay(&self, _replay: &crate::replay::Replay) -> Result<(), SyncError> {
|
||||
/// Upload a winning replay to the backend. On success, returns the
|
||||
/// shareable web URL the player can copy to their clipboard
|
||||
/// (`<server>/replays/<id>`). Default returns `UnsupportedPlatform`
|
||||
/// so backends without a server (e.g. `LocalOnlyProvider`) are
|
||||
/// silently no-op'd by the engine's push-on-win system, matching
|
||||
/// the same pattern `pull` / `push` follow.
|
||||
async fn push_replay(&self, _replay: &crate::replay::Replay) -> Result<String, SyncError> {
|
||||
Err(SyncError::UnsupportedPlatform)
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ impl SyncProvider for Box<dyn SyncProvider + Send + Sync> {
|
||||
async fn delete_account(&self) -> Result<(), SyncError> {
|
||||
(**self).delete_account().await
|
||||
}
|
||||
async fn push_replay(&self, replay: &crate::replay::Replay) -> Result<(), SyncError> {
|
||||
async fn push_replay(&self, replay: &crate::replay::Replay) -> Result<String, SyncError> {
|
||||
(**self).push_replay(replay).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,21 +162,6 @@ mod tests {
|
||||
|
||||
// --- Persistence ---
|
||||
|
||||
#[test]
|
||||
fn round_trip_save_and_load() {
|
||||
let path = tmp_path("round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
|
||||
let mut p = PlayerProgress::default();
|
||||
p.add_xp(1234);
|
||||
p.unlocked_card_backs.push(2);
|
||||
save_progress_to(&path, &p).expect("save");
|
||||
let loaded = load_progress_from(&path);
|
||||
assert_eq!(loaded.total_xp, 1234);
|
||||
assert_eq!(loaded.level, p.level);
|
||||
assert!(loaded.unlocked_card_backs.contains(&2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_from_missing_file_returns_default() {
|
||||
let path = tmp_path("missing_xyz");
|
||||
|
||||
@@ -138,6 +138,15 @@ pub struct Replay {
|
||||
/// Ordered move list. Each entry is what the player did, replayable
|
||||
/// against a fresh `GameState` constructed from the seed.
|
||||
pub moves: Vec<ReplayMove>,
|
||||
/// Public share URL for this replay on the active sync backend, set
|
||||
/// by `sync_plugin::poll_replay_upload_result` when the upload
|
||||
/// task resolves. `None` when the player won on a local-only
|
||||
/// backend, the upload failed, or the replay pre-dates v0.19.0
|
||||
/// share-link persistence. `#[serde(default)]` keeps older
|
||||
/// `replays.json` files loadable without bumping
|
||||
/// [`REPLAY_SCHEMA_VERSION`].
|
||||
#[serde(default)]
|
||||
pub share_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Replay {
|
||||
@@ -162,6 +171,7 @@ impl Replay {
|
||||
final_score,
|
||||
recorded_at,
|
||||
moves,
|
||||
share_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -481,6 +491,34 @@ mod tests {
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// Backwards-compat: a `Replay` record persisted before v0.19.0
|
||||
/// share-link persistence carries no `share_url` field on disk.
|
||||
/// `#[serde(default)]` must let it deserialise cleanly with
|
||||
/// `share_url == None`, so existing players don't see their
|
||||
/// rolling history wiped on the v0.19.0 update.
|
||||
#[test]
|
||||
fn replay_loads_when_share_url_field_is_absent() {
|
||||
let pre_v019_json = format!(
|
||||
r#"{{
|
||||
"schema_version": {schema},
|
||||
"seed": 1,
|
||||
"draw_mode": "DrawOne",
|
||||
"mode": "Classic",
|
||||
"time_seconds": 60,
|
||||
"final_score": 100,
|
||||
"recorded_at": "2025-01-01",
|
||||
"moves": []
|
||||
}}"#,
|
||||
schema = REPLAY_SCHEMA_VERSION,
|
||||
);
|
||||
let parsed: Replay = serde_json::from_str(&pre_v019_json)
|
||||
.expect("pre-v0.19.0 replay JSON must still deserialise");
|
||||
assert!(
|
||||
parsed.share_url.is_none(),
|
||||
"missing share_url field must default to None",
|
||||
);
|
||||
}
|
||||
|
||||
/// Atomic-write contract — `.tmp` must not be left behind after
|
||||
/// `save_latest_replay_to` returns. Mirrors the same check that
|
||||
/// guards `save_game_state_to` in `storage.rs`.
|
||||
|
||||
@@ -422,19 +422,6 @@ mod tests {
|
||||
env::temp_dir().join(format!("solitaire_settings_test_{name}.json"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_are_reasonable() {
|
||||
let s = Settings::default();
|
||||
assert!((s.sfx_volume - 0.8).abs() < 1e-6);
|
||||
assert!((s.music_volume - 0.5).abs() < 1e-6);
|
||||
assert!(!s.first_run_complete);
|
||||
assert_eq!(s.draw_mode, DrawMode::DrawOne);
|
||||
assert_eq!(s.animation_speed, AnimSpeed::Normal);
|
||||
assert_eq!(s.theme, Theme::Green);
|
||||
assert_eq!(s.sync_backend, SyncBackend::Local);
|
||||
assert!((s.tooltip_delay_secs - default_tooltip_delay()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjust_sfx_volume_clamps() {
|
||||
let mut s = Settings { sfx_volume: 0.5, ..Default::default() };
|
||||
@@ -467,77 +454,6 @@ mod tests {
|
||||
assert!(s.first_run_complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitized_clamps_music_volume() {
|
||||
let s = Settings { music_volume: 2.0, ..Default::default() }.sanitized();
|
||||
assert_eq!(s.music_volume, 1.0);
|
||||
|
||||
let s2 = Settings { music_volume: -0.5, ..Default::default() }.sanitized();
|
||||
assert_eq!(s2.music_volume, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_save_and_load() {
|
||||
let path = tmp_path("round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
sfx_volume: 0.42,
|
||||
first_run_complete: true,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(loaded, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_save_and_load_full_settings() {
|
||||
let path = tmp_path("round_trip_full");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
draw_mode: DrawMode::DrawThree,
|
||||
sfx_volume: 0.3,
|
||||
music_volume: 0.7,
|
||||
animation_speed: AnimSpeed::Fast,
|
||||
theme: Theme::Dark,
|
||||
sync_backend: SyncBackend::SolitaireServer {
|
||||
url: "https://example.com".to_string(),
|
||||
username: "testuser".to_string(),
|
||||
},
|
||||
selected_card_back: 0,
|
||||
selected_background: 0,
|
||||
first_run_complete: true,
|
||||
color_blind_mode: false,
|
||||
window_geometry: None,
|
||||
selected_theme_id: "default".to_string(),
|
||||
shown_achievement_onboarding: false,
|
||||
tooltip_delay_secs: default_tooltip_delay(),
|
||||
time_bonus_multiplier: default_time_bonus_multiplier(),
|
||||
winnable_deals_only: false,
|
||||
replay_move_interval_secs: default_replay_move_interval_secs(),
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(loaded, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_preserves_non_default_cosmetic_selections() {
|
||||
// selected_card_back and selected_background must survive save→load with
|
||||
// non-zero values — zero is the default and not a meaningful regression check.
|
||||
let path = tmp_path("cosmetic_selections");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
selected_card_back: 3,
|
||||
selected_background: 2,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(loaded.selected_card_back, 3);
|
||||
assert_eq!(loaded.selected_background, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_from_missing_file_returns_default() {
|
||||
let path = tmp_path("missing_xyz");
|
||||
@@ -554,250 +470,6 @@ mod tests {
|
||||
assert_eq!(s, Settings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_from_old_format_uses_defaults_for_new_fields() {
|
||||
// Simulate a settings.json written by an older version that only had
|
||||
// sfx_volume and first_run_complete.
|
||||
let path = tmp_path("old_format");
|
||||
fs::write(
|
||||
&path,
|
||||
br#"{ "sfx_volume": 0.6, "first_run_complete": true }"#,
|
||||
)
|
||||
.expect("write");
|
||||
let s = load_settings_from(&path);
|
||||
assert!((s.sfx_volume - 0.6).abs() < 1e-6);
|
||||
assert!(s.first_run_complete);
|
||||
// New fields should fall back to their defaults.
|
||||
assert!((s.music_volume - 0.5).abs() < 1e-6);
|
||||
assert_eq!(s.animation_speed, AnimSpeed::Normal);
|
||||
assert_eq!(s.theme, Theme::Green);
|
||||
assert_eq!(s.sync_backend, SyncBackend::Local);
|
||||
assert_eq!(s.draw_mode, DrawMode::DrawOne);
|
||||
assert_eq!(s.selected_card_back, 0, "cosmetic card-back must default to 0 on old format");
|
||||
assert_eq!(s.selected_background, 0, "cosmetic background must default to 0 on old format");
|
||||
assert!(!s.color_blind_mode, "color_blind_mode must default to false on old format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_blind_mode_defaults_to_false_when_field_absent() {
|
||||
// Simulate a JSON file that has no color_blind_mode field.
|
||||
let json = br#"{ "sfx_volume": 0.7 }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(!s.color_blind_mode, "color_blind_mode must be false when absent from JSON");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_blind_mode_round_trips() {
|
||||
let path = tmp_path("color_blind");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
color_blind_mode: true,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(loaded.color_blind_mode, "color_blind_mode must survive a save/load round-trip");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Task #62 — selected_card_back
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_card_back_default_is_zero() {
|
||||
assert_eq!(Settings::default().selected_card_back, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_card_back_serializes_round_trip() {
|
||||
let path = tmp_path("card_back_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
selected_card_back: 2,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(loaded.selected_card_back, 2, "selected_card_back must survive serde round-trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Task #63 — selected_background
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_background_default_is_zero() {
|
||||
assert_eq!(Settings::default().selected_background, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_background_serializes_round_trip() {
|
||||
let path = tmp_path("background_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
selected_background: 3,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(loaded.selected_background, 3, "selected_background must survive serde round-trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// window_geometry — persisted window size/position
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_window_geometry_default_is_none() {
|
||||
assert!(
|
||||
Settings::default().window_geometry.is_none(),
|
||||
"default window_geometry must be None so first launch uses platform defaults"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_with_window_geometry_round_trip() {
|
||||
let path = tmp_path("window_geometry_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let geom = WindowGeometry {
|
||||
width: 1440,
|
||||
height: 900,
|
||||
x: 120,
|
||||
y: 80,
|
||||
};
|
||||
let s = Settings {
|
||||
window_geometry: Some(geom),
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert_eq!(
|
||||
loaded.window_geometry,
|
||||
Some(geom),
|
||||
"window_geometry must survive serde round-trip"
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_window_geometry_deserializes_to_none() {
|
||||
// A settings.json written by an older version of the game will be
|
||||
// missing this field entirely. `#[serde(default)]` on the field
|
||||
// must yield `None` rather than failing the whole deserialise.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
s.window_geometry.is_none(),
|
||||
"legacy settings.json missing window_geometry must deserialize to None"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_geometry_explicit_null_deserializes_to_none() {
|
||||
// An explicit `"window_geometry": null` is also valid input that
|
||||
// must yield None — keeps tooling that hand-edits the file safe.
|
||||
let json = br#"{ "window_geometry": null }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(s.window_geometry.is_none());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// shown_achievement_onboarding — first-win cue one-shot guard
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_shown_achievement_onboarding_default_is_false() {
|
||||
assert!(
|
||||
!Settings::default().shown_achievement_onboarding,
|
||||
"default shown_achievement_onboarding must be false so the cue fires once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_shown_achievement_onboarding_round_trip() {
|
||||
let path = tmp_path("achievement_onboarding_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
shown_achievement_onboarding: true,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(
|
||||
loaded.shown_achievement_onboarding,
|
||||
"shown_achievement_onboarding must survive serde round-trip"
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_shown_achievement_onboarding_deserializes_to_false() {
|
||||
// A settings.json written by an older version of the game will be
|
||||
// missing this field entirely. `#[serde(default)]` on the field
|
||||
// must yield `false` — the cue then fires on the next win, but
|
||||
// only when stats.games_won == 1, so existing players who have
|
||||
// already won past their first game won't see the toast either.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
!s.shown_achievement_onboarding,
|
||||
"legacy settings.json missing shown_achievement_onboarding must deserialize to false"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// tooltip_delay_secs — player-tunable tooltip hover delay
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_tooltip_delay_default_is_existing_baseline() {
|
||||
// The existing baseline pre-slider is 0.5 s, matching the
|
||||
// `MOTION_TOOLTIP_DELAY_SECS` constant in
|
||||
// `solitaire_engine::ui_theme`. The default must not regress.
|
||||
let s = Settings::default();
|
||||
assert!(
|
||||
(s.tooltip_delay_secs - 0.5).abs() < 1e-6,
|
||||
"tooltip_delay_secs default must be 0.5 (the pre-slider baseline), got {}",
|
||||
s.tooltip_delay_secs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_tooltip_delay_round_trip() {
|
||||
let path = tmp_path("tooltip_delay_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
tooltip_delay_secs: 1.2,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(
|
||||
(loaded.tooltip_delay_secs - 1.2).abs() < 1e-6,
|
||||
"tooltip_delay_secs must survive serde round-trip; got {}",
|
||||
loaded.tooltip_delay_secs
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_tooltip_delay_deserializes_to_default() {
|
||||
// A settings.json written before this field existed must
|
||||
// deserialize cleanly to the existing 0.5 s baseline rather
|
||||
// than failing the whole load or yielding a zero value.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
(s.tooltip_delay_secs - default_tooltip_delay()).abs() < 1e-6,
|
||||
"legacy settings.json missing tooltip_delay_secs must deserialize to default ({}), got {}",
|
||||
default_tooltip_delay(),
|
||||
s.tooltip_delay_secs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjust_tooltip_delay_clamps_to_range() {
|
||||
let mut s = Settings { tooltip_delay_secs: 0.5, ..Default::default() };
|
||||
@@ -811,90 +483,6 @@ mod tests {
|
||||
assert_eq!(s.tooltip_delay_secs, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitized_clamps_out_of_range_tooltip_delay() {
|
||||
// Negative or oversized values from a hand-edited file must be
|
||||
// clamped on load.
|
||||
let s = Settings {
|
||||
tooltip_delay_secs: -0.4,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s.tooltip_delay_secs, TOOLTIP_DELAY_MIN_SECS);
|
||||
|
||||
let s2 = Settings {
|
||||
tooltip_delay_secs: 99.0,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s2.tooltip_delay_secs, TOOLTIP_DELAY_MAX_SECS);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// time_bonus_multiplier — cosmetic win-modal time-bonus weight
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_time_bonus_multiplier_default_is_one() {
|
||||
let s = Settings::default();
|
||||
assert!(
|
||||
(s.time_bonus_multiplier - 1.0).abs() < 1e-6,
|
||||
"default time_bonus_multiplier must be 1.0 (no change to displayed bonus), got {}",
|
||||
s.time_bonus_multiplier
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_time_bonus_multiplier_round_trip() {
|
||||
let path = tmp_path("time_bonus_multiplier_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
time_bonus_multiplier: 1.5,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(
|
||||
(loaded.time_bonus_multiplier - 1.5).abs() < 1e-6,
|
||||
"time_bonus_multiplier must survive serde round-trip; got {}",
|
||||
loaded.time_bonus_multiplier
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_time_bonus_multiplier_deserializes_to_one() {
|
||||
// A settings.json written before this field existed must
|
||||
// deserialize cleanly to the existing 1.0 baseline so old
|
||||
// players see no change to their win-modal bonuses.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
(s.time_bonus_multiplier - 1.0).abs() < 1e-6,
|
||||
"legacy settings.json missing time_bonus_multiplier must deserialize to 1.0, got {}",
|
||||
s.time_bonus_multiplier
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_time_bonus_multiplier_clamps_to_range() {
|
||||
// Negative or oversized values from a hand-edited file must be
|
||||
// clamped on load.
|
||||
let s = Settings {
|
||||
time_bonus_multiplier: -0.5,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s.time_bonus_multiplier, TIME_BONUS_MULTIPLIER_MIN);
|
||||
|
||||
let s2 = Settings {
|
||||
time_bonus_multiplier: 99.0,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s2.time_bonus_multiplier, TIME_BONUS_MULTIPLIER_MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjust_time_bonus_multiplier_clamps_and_rounds() {
|
||||
let mut s = Settings { time_bonus_multiplier: 1.0, ..Default::default() };
|
||||
@@ -923,121 +511,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// winnable_deals_only — solver-backed deal filter toggle
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_winnable_deals_only_default_is_false() {
|
||||
// Off by default — the solver adds latency we shouldn't impose
|
||||
// on every player without their consent.
|
||||
assert!(
|
||||
!Settings::default().winnable_deals_only,
|
||||
"default winnable_deals_only must be false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_winnable_deals_only_round_trip() {
|
||||
let path = tmp_path("winnable_deals_only_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
winnable_deals_only: true,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(
|
||||
loaded.winnable_deals_only,
|
||||
"winnable_deals_only must survive serde round-trip"
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_winnable_deals_only_deserializes_to_false() {
|
||||
// A settings.json written before this field existed must
|
||||
// deserialize cleanly to `false` (the default-off behaviour)
|
||||
// rather than failing the whole load or surprising the player
|
||||
// by switching the toggle on.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
!s.winnable_deals_only,
|
||||
"legacy settings.json missing winnable_deals_only must deserialize to false"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// replay_move_interval_secs — player-tunable replay playback speed
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn settings_replay_move_interval_default_is_zero_point_four_five() {
|
||||
// The pre-slider baseline is 0.45 s/move, matching
|
||||
// `solitaire_engine::replay_playback::REPLAY_MOVE_INTERVAL_SECS`.
|
||||
// The default must not regress for players who never touch
|
||||
// the slider.
|
||||
let s = Settings::default();
|
||||
assert!(
|
||||
(s.replay_move_interval_secs - 0.45).abs() < 1e-6,
|
||||
"replay_move_interval_secs default must be 0.45 (the pre-slider baseline), got {}",
|
||||
s.replay_move_interval_secs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_replay_move_interval_round_trip() {
|
||||
let path = tmp_path("replay_move_interval_round_trip");
|
||||
let _ = fs::remove_file(&path);
|
||||
let s = Settings {
|
||||
replay_move_interval_secs: 0.20,
|
||||
..Settings::default()
|
||||
};
|
||||
save_settings_to(&path, &s).expect("save");
|
||||
let loaded = load_settings_from(&path);
|
||||
assert!(
|
||||
(loaded.replay_move_interval_secs - 0.20).abs() < 1e-6,
|
||||
"replay_move_interval_secs must survive serde round-trip; got {}",
|
||||
loaded.replay_move_interval_secs
|
||||
);
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_without_replay_move_interval_deserializes_to_default() {
|
||||
// A settings.json written before this field existed must
|
||||
// deserialize cleanly to the existing 0.45 s baseline so old
|
||||
// players see no change to replay playback speed.
|
||||
let json = br#"{ "sfx_volume": 0.7, "first_run_complete": true }"#;
|
||||
let s: Settings = serde_json::from_slice(json).unwrap_or_default();
|
||||
assert!(
|
||||
(s.replay_move_interval_secs - default_replay_move_interval_secs()).abs() < 1e-6,
|
||||
"legacy settings.json missing replay_move_interval_secs must deserialize to default ({}), got {}",
|
||||
default_replay_move_interval_secs(),
|
||||
s.replay_move_interval_secs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_replay_move_interval_clamps_to_range() {
|
||||
// Negative or oversized values from a hand-edited file must be
|
||||
// clamped on load.
|
||||
let s = Settings {
|
||||
replay_move_interval_secs: 5.0,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s.replay_move_interval_secs, REPLAY_MOVE_INTERVAL_MAX_SECS);
|
||||
|
||||
let s2 = Settings {
|
||||
replay_move_interval_secs: -1.0,
|
||||
..Settings::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(s2.replay_move_interval_secs, REPLAY_MOVE_INTERVAL_MIN_SECS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjust_replay_move_interval_clamps_and_rounds() {
|
||||
let mut s = Settings { replay_move_interval_secs: 0.45, ..Default::default() };
|
||||
|
||||
@@ -358,13 +358,12 @@ impl SyncProvider for SolitaireServerClient {
|
||||
extract_leaderboard_body(resp).await
|
||||
}
|
||||
|
||||
/// Upload a winning replay to `POST /api/replays`. Mirrors the
|
||||
/// `push` auth flow: 401 triggers a token refresh and one retry.
|
||||
/// Non-success statuses are surfaced as the relevant `SyncError`
|
||||
/// variant so the engine's push-on-win system can downgrade
|
||||
/// network/auth failures into a quiet log without aborting the
|
||||
/// game flow.
|
||||
async fn push_replay(&self, replay: &Replay) -> Result<(), SyncError> {
|
||||
/// Upload a winning replay to `POST /api/replays`. On success the
|
||||
/// server returns `{ "id": "<uuid>" }`; this method composes that
|
||||
/// id with the configured base URL into the player-shareable
|
||||
/// `<base>/replays/<id>` link and returns it. Mirrors the `push`
|
||||
/// auth flow: 401 triggers a token refresh and one retry.
|
||||
async fn push_replay(&self, replay: &Replay) -> Result<String, SyncError> {
|
||||
let token = self.access_token()?;
|
||||
let url = format!("{}/api/replays", self.base_url);
|
||||
|
||||
@@ -388,22 +387,38 @@ impl SyncProvider for SolitaireServerClient {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| SyncError::Network(e.to_string()))?;
|
||||
return check_replay_status(resp.status());
|
||||
return self.share_url_from_response(resp).await;
|
||||
}
|
||||
|
||||
check_replay_status(resp.status())
|
||||
self.share_url_from_response(resp).await
|
||||
}
|
||||
}
|
||||
|
||||
fn check_replay_status(status: reqwest::StatusCode) -> Result<(), SyncError> {
|
||||
if status.is_success() {
|
||||
Ok(())
|
||||
} else if status == reqwest::StatusCode::UNAUTHORIZED
|
||||
impl SolitaireServerClient {
|
||||
/// Pulled out of `push_replay` so both the first attempt and the
|
||||
/// post-401-retry attempt go through the same parse path.
|
||||
async fn share_url_from_response(
|
||||
&self,
|
||||
resp: reqwest::Response,
|
||||
) -> Result<String, SyncError> {
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
return Err(if status == reqwest::StatusCode::UNAUTHORIZED
|
||||
|| status == reqwest::StatusCode::FORBIDDEN
|
||||
{
|
||||
Err(SyncError::Auth(format!("server returned {status}")))
|
||||
SyncError::Auth(format!("server returned {status}"))
|
||||
} else {
|
||||
Err(SyncError::Network(format!("server returned {status}")))
|
||||
SyncError::Network(format!("server returned {status}"))
|
||||
});
|
||||
}
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| SyncError::Serialization(e.to_string()))?;
|
||||
let id = body["id"].as_str().ok_or_else(|| {
|
||||
SyncError::Serialization("upload response missing `id`".into())
|
||||
})?;
|
||||
Ok(format!("{}/replays/{}", self.base_url, id))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ tiny-skia = { workspace = true }
|
||||
ron = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
arboard = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
async-trait = { workspace = true }
|
||||
|
||||
@@ -474,9 +474,29 @@ fn spawn_achievements_screen(
|
||||
..default()
|
||||
};
|
||||
|
||||
let any_unlocked = records.iter().any(|r| r.unlocked);
|
||||
|
||||
let scrim = spawn_modal(commands, AchievementsScreen, Z_MODAL_PANEL, |card| {
|
||||
spawn_modal_header(card, header, font_res);
|
||||
|
||||
// First-time hint — shown until the player has unlocked anything.
|
||||
// The list itself describes individual rewards, but a top-level
|
||||
// explanation gives newer players context for the otherwise dense
|
||||
// greyed-out grid.
|
||||
if !any_unlocked {
|
||||
card.spawn((
|
||||
Text::new(
|
||||
"Complete games and try new modes to unlock achievements and rewards.",
|
||||
),
|
||||
TextFont {
|
||||
font: font_res.map(|f| f.0.clone()).unwrap_or_default(),
|
||||
font_size: TYPE_CAPTION,
|
||||
..default()
|
||||
},
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
}
|
||||
|
||||
// Scrollable body — the achievements list grows to ~19 rows which
|
||||
// overflows the modal on the 800x600 minimum window. Wrapping the
|
||||
// row list in an `Overflow::scroll_y()` Node with a constrained
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::card_animation::{sample_curve, CardAnimation, MotionCurve};
|
||||
use crate::card_plugin::CardEntity;
|
||||
use crate::challenge_plugin::ChallengeAdvancedEvent;
|
||||
use crate::daily_challenge_plugin::{DailyChallengeCompletedEvent, DailyGoalAnnouncementEvent};
|
||||
use crate::events::{InfoToastEvent, NewGameConfirmEvent, XpAwardedEvent};
|
||||
use crate::events::{InfoToastEvent, XpAwardedEvent};
|
||||
use crate::events::{AchievementUnlockedEvent, GameWonEvent};
|
||||
use crate::game_plugin::GameMutation;
|
||||
use crate::layout::LayoutResource;
|
||||
@@ -61,7 +61,6 @@ fn anim_speed_to_secs(speed: &AnimSpeed) -> f32 {
|
||||
scaled_duration(MOTION_SLIDE_SECS, *speed)
|
||||
}
|
||||
|
||||
const WIN_TOAST_SECS: f32 = 4.0;
|
||||
const ACHIEVEMENT_TOAST_SECS: f32 = 3.0;
|
||||
const LEVELUP_TOAST_SECS: f32 = 3.0;
|
||||
const DAILY_TOAST_SECS: f32 = 3.0;
|
||||
@@ -161,7 +160,6 @@ impl Plugin for AnimationPlugin {
|
||||
.add_message::<TimeAttackEndedEvent>()
|
||||
.add_message::<ChallengeAdvancedEvent>()
|
||||
.add_message::<SettingsChangedEvent>()
|
||||
.add_message::<NewGameConfirmEvent>()
|
||||
.add_message::<InfoToastEvent>()
|
||||
.add_message::<XpAwardedEvent>()
|
||||
.init_resource::<EffectiveSlideDuration>()
|
||||
@@ -183,7 +181,6 @@ impl Plugin for AnimationPlugin {
|
||||
handle_challenge_toast,
|
||||
handle_settings_toast,
|
||||
handle_auto_complete_toast,
|
||||
handle_new_game_confirm_toast,
|
||||
handle_xp_awarded_toast,
|
||||
tick_toasts,
|
||||
(enqueue_toasts, drive_toast_display).chain(),
|
||||
@@ -268,9 +265,15 @@ fn handle_win_cascade(
|
||||
layout: Option<Res<LayoutResource>>,
|
||||
settings: Option<Res<SettingsResource>>,
|
||||
) {
|
||||
let Some(ev) = events.read().next() else {
|
||||
// Drain the event reader; the cascade visual is the only thing
|
||||
// this system contributes — the post-win "You Won!" modal
|
||||
// (`win_summary_plugin`) consumes the same `GameWonEvent` and
|
||||
// carries score / time / achievements / XP itself, so a duplicate
|
||||
// toast saying "You Win! Score X Time Y" rendered behind the modal
|
||||
// in earlier builds. Removed.
|
||||
if events.read().next().is_none() {
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
let margin = layout.as_ref().map_or(800.0, |l| l.0.card_size.x * 8.0);
|
||||
|
||||
@@ -286,11 +289,6 @@ fn handle_win_cascade(
|
||||
Vec3::new(-margin, 0.0, 300.0),
|
||||
];
|
||||
|
||||
let m = ev.time_seconds / 60;
|
||||
let s = ev.time_seconds % 60;
|
||||
let win_msg = format!("You Win! Score: {} Time: {m}:{s:02}", ev.score);
|
||||
spawn_toast(&mut commands, win_msg, WIN_TOAST_SECS);
|
||||
|
||||
let step = settings
|
||||
.as_ref()
|
||||
.map_or(CASCADE_STAGGER_NORMAL, |s| cascade_step_secs(s.0.animation_speed));
|
||||
@@ -459,15 +457,6 @@ fn handle_auto_complete_toast(
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_new_game_confirm_toast(
|
||||
mut commands: Commands,
|
||||
mut events: MessageReader<NewGameConfirmEvent>,
|
||||
) {
|
||||
for _ in events.read() {
|
||||
spawn_toast(&mut commands, "Press N again to start a new game".to_string(), 3.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every incoming `InfoToastEvent` and appends its text to `ToastQueue`.
|
||||
///
|
||||
/// This is the first half of the two-system toast queue (Task #67). The queue
|
||||
|
||||
@@ -207,13 +207,6 @@ pub struct ToggleLeaderboardRequestEvent;
|
||||
#[derive(Message, Debug, Clone)]
|
||||
pub struct SyncCompleteEvent(pub Result<SyncResponse, String>);
|
||||
|
||||
/// Fired by `InputPlugin` when N is pressed while a game is in progress
|
||||
/// but confirmation has not yet been received. The animation plugin shows
|
||||
/// a "Press N again to confirm" toast. A second N press within the
|
||||
/// confirmation window sends `NewGameRequestEvent`.
|
||||
#[derive(Message, Debug, Clone, Copy, Default)]
|
||||
pub struct NewGameConfirmEvent;
|
||||
|
||||
/// Generic informational toast message. Any system can fire this to display
|
||||
/// a short string to the player, e.g. "Locked — reach level 5".
|
||||
#[derive(Message, Debug, Clone)]
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
//!
|
||||
//! # Task #69 — Animated card deal on new game start
|
||||
//!
|
||||
//! When `NewGameRequestEvent` fires (on a fresh game, `move_count == 0`) or
|
||||
//! `NewGameConfirmEvent` fires, `start_deal_anim` reads `LayoutResource` and
|
||||
//! When `NewGameRequestEvent` fires (on a fresh game, `move_count == 0`),
|
||||
//! `start_deal_anim` reads `LayoutResource` and
|
||||
//! inserts a `CardAnim` on every card entity, sliding each card from the stock
|
||||
//! pile's position to its current (final) position with a per-card stagger
|
||||
//! derived from the current `AnimSpeed` setting plus a deterministic ±10 %
|
||||
|
||||
@@ -10,6 +10,7 @@ use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::tasks::{futures_lite::future, AsyncComputeTaskPool, Task};
|
||||
use chrono::Utc;
|
||||
use solitaire_core::game_state::{DrawMode, GameMode, GameState};
|
||||
use solitaire_core::pile::PileType;
|
||||
@@ -72,6 +73,32 @@ pub struct GameStatePath(pub Option<PathBuf>);
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct ReplayPath(pub Option<PathBuf>);
|
||||
|
||||
/// Holds the saved-on-disk in-progress game between plugin build and
|
||||
/// the player's answer to the "Continue or start a new game?" prompt.
|
||||
///
|
||||
/// Some(game) at startup means a previously-saved game existed and had
|
||||
/// real moves on it. The restore-prompt modal swaps it into
|
||||
/// `GameStateResource` if the player picks Continue, or drops it (and
|
||||
/// lets `handle_new_game` clean up the disk file) on New Game. None for
|
||||
/// first-launch installs and for save files that contain a fresh deal
|
||||
/// with no moves yet — there's nothing meaningful to "continue" there.
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct PendingRestoredGame(pub Option<GameState>);
|
||||
|
||||
/// Marker on the "Welcome back — Continue or start a new game?" modal
|
||||
/// scrim. Despawning the scrim cascades to the card and children, so a
|
||||
/// single `commands.entity(scrim).despawn()` tears the modal down.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct RestorePromptScreen;
|
||||
|
||||
/// Marker on the modal's primary "Continue" button.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct RestoreContinueButton;
|
||||
|
||||
/// Marker on the modal's secondary "New game" button.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct RestoreNewGameButton;
|
||||
|
||||
/// In-memory accumulator for [`ReplayMove`] entries during the current
|
||||
/// game. Cleared on every new-game start; frozen into a [`Replay`] and
|
||||
/// flushed to disk by [`record_replay_on_win`] when the player wins.
|
||||
@@ -109,11 +136,32 @@ impl GamePlugin {
|
||||
impl Plugin for GamePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let path = game_state_file_path();
|
||||
// Restore any saved in-progress game, falling back to a fresh deal.
|
||||
let initial_state = path
|
||||
.as_deref()
|
||||
.and_then(load_game_state_from)
|
||||
.unwrap_or_else(|| GameState::new(seed_from_system_time(), DrawMode::DrawOne));
|
||||
// Try to load any saved in-progress game. We don't want to
|
||||
// silently restore a half-played game on launch — the player
|
||||
// should get to decide between continuing and starting fresh.
|
||||
// So: if there IS a saved game with progress and it isn't
|
||||
// already won, hold it in `PendingRestoredGame` and let the
|
||||
// restore-prompt modal swap it into `GameStateResource` if
|
||||
// the player picks Continue. Otherwise put it directly into
|
||||
// `GameStateResource` (existing behaviour for un-played /
|
||||
// won deals which there's nothing to ask about).
|
||||
let saved = path.as_deref().and_then(load_game_state_from);
|
||||
let prompt_worthy = saved
|
||||
.as_ref()
|
||||
.is_some_and(|g| g.move_count > 0 && !g.is_won);
|
||||
let (initial_state, pending_restore) = if prompt_worthy {
|
||||
(
|
||||
GameState::new(seed_from_system_time(), DrawMode::DrawOne),
|
||||
saved,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
saved.unwrap_or_else(|| {
|
||||
GameState::new(seed_from_system_time(), DrawMode::DrawOne)
|
||||
}),
|
||||
None,
|
||||
)
|
||||
};
|
||||
|
||||
// One-shot migration from the legacy single-slot
|
||||
// `latest_replay.json` to the rolling history at `replays.json`.
|
||||
@@ -136,7 +184,9 @@ impl Plugin for GamePlugin {
|
||||
app.insert_resource(GameStateResource(initial_state))
|
||||
.insert_resource(GameStatePath(path))
|
||||
.insert_resource(ReplayPath(history_path))
|
||||
.insert_resource(PendingRestoredGame(pending_restore))
|
||||
.init_resource::<RecordingReplay>()
|
||||
.init_resource::<PendingNewGameSeed>()
|
||||
.init_resource::<DragState>()
|
||||
.init_resource::<SyncStatusResource>()
|
||||
.add_message::<MoveRequestEvent>()
|
||||
@@ -150,6 +200,10 @@ impl Plugin for GamePlugin {
|
||||
.add_message::<crate::events::AchievementUnlockedEvent>()
|
||||
.add_message::<FoundationCompletedEvent>()
|
||||
.add_message::<InfoToastEvent>()
|
||||
.add_systems(
|
||||
Update,
|
||||
poll_pending_new_game_seed.before(GameMutation),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
@@ -167,6 +221,11 @@ impl Plugin for GamePlugin {
|
||||
.add_systems(Update, handle_confirm_button_input.after(GameMutation))
|
||||
.add_systems(Update, handle_game_over_input.after(GameMutation))
|
||||
.add_systems(Update, handle_game_over_button_input.after(GameMutation))
|
||||
// Restore prompt: spawn the modal once the splash is gone,
|
||||
// route Continue / New Game intents back into the existing
|
||||
// GameMutation flow.
|
||||
.add_systems(Update, spawn_restore_prompt_if_pending)
|
||||
.add_systems(Update, handle_restore_prompt.before(GameMutation))
|
||||
.init_resource::<AutoSaveTimer>()
|
||||
.add_systems(Update, tick_elapsed_time)
|
||||
.add_systems(Update, auto_save_game_state)
|
||||
@@ -193,16 +252,20 @@ pub fn advance_elapsed(
|
||||
}
|
||||
|
||||
/// Increment `GameState.elapsed_seconds` once per real-world second while
|
||||
/// the game is in progress (not won) and not paused. Stops counting on
|
||||
/// win so the final time reflects how long the player took to solve the
|
||||
/// deal; stops while the pause overlay is open.
|
||||
/// the game is in progress (not won), not paused, and the launch /
|
||||
/// mode-picker Home modal isn't covering the board. Stops counting on
|
||||
/// win so the final time reflects how long the player took to solve
|
||||
/// the deal; stops while the pause overlay is open; stops while Home
|
||||
/// is up so the timer doesn't tick under the picker before the player
|
||||
/// has actually committed to a deal.
|
||||
fn tick_elapsed_time(
|
||||
time: Res<Time>,
|
||||
mut game: ResMut<GameStateResource>,
|
||||
mut accumulator: Local<f32>,
|
||||
paused: Option<Res<crate::pause_plugin::PausedResource>>,
|
||||
home_screens: Query<(), With<crate::home_plugin::HomeScreen>>,
|
||||
) {
|
||||
if paused.is_some_and(|p| p.0) {
|
||||
if paused.is_some_and(|p| p.0) || !home_screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
let is_won = game.0.is_won;
|
||||
@@ -237,6 +300,60 @@ fn seed_from_system_time() -> u64 {
|
||||
/// seed so the player still gets a deal — better a possibly-unwinnable
|
||||
/// hand than an infinite loop.
|
||||
///
|
||||
/// In-flight async work for "Winnable deals only" seed selection.
|
||||
///
|
||||
/// `handle_new_game` writes here when it needs the solver to vet a deal;
|
||||
/// `poll_pending_new_game_seed` reads from here, polls the task, and
|
||||
/// re-emits a `NewGameRequestEvent` with the chosen seed once the task
|
||||
/// completes. The desktop client's UI never blocks on the worst-case
|
||||
/// 50 × ~120 ms solver runs that can pile up on pathological deals.
|
||||
///
|
||||
/// At most one task is ever in flight: a fresh new-game request while
|
||||
/// a previous task is still running drops the previous task (Bevy's
|
||||
/// `Task` `Drop` cancels it cooperatively at the next await point) and
|
||||
/// queues the new one.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct PendingNewGameSeed {
|
||||
/// `Some` while a solver-vetted seed is being computed.
|
||||
inner: Option<PendingSeedTask>,
|
||||
}
|
||||
|
||||
/// One in-flight winnable-seed search plus the request fields that
|
||||
/// would have flowed through `handle_new_game` synchronously. The
|
||||
/// poll system replays them on a synthetic `NewGameRequestEvent` once
|
||||
/// the task completes — `seed: Some(...)` skips the solver branch on
|
||||
/// the second pass so we don't loop.
|
||||
struct PendingSeedTask {
|
||||
handle: Task<u64>,
|
||||
mode: Option<GameMode>,
|
||||
confirmed: bool,
|
||||
}
|
||||
|
||||
/// Update system: poll the in-flight winnable-seed search. When the
|
||||
/// task resolves, emit a synthetic `NewGameRequestEvent` carrying the
|
||||
/// chosen seed. Ordered `.before(GameMutation)` so `handle_new_game`
|
||||
/// picks up the synthetic event on the same frame, completing the
|
||||
/// new-game flow without a one-frame visual lag.
|
||||
fn poll_pending_new_game_seed(
|
||||
mut pending: ResMut<PendingNewGameSeed>,
|
||||
mut new_game_writer: MessageWriter<NewGameRequestEvent>,
|
||||
) {
|
||||
let Some(p) = pending.inner.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(seed) = future::block_on(future::poll_once(&mut p.handle)) else {
|
||||
return;
|
||||
};
|
||||
let mode = p.mode;
|
||||
let confirmed = p.confirmed;
|
||||
pending.inner = None;
|
||||
new_game_writer.write(NewGameRequestEvent {
|
||||
seed: Some(seed),
|
||||
mode,
|
||||
confirmed,
|
||||
});
|
||||
}
|
||||
|
||||
/// Pure helper extracted for testability — `new_game_with_solver_*`
|
||||
/// engine tests in the same file exercise this path.
|
||||
pub(crate) fn choose_winnable_seed(initial_seed: u64, draw_mode: &DrawMode) -> u64 {
|
||||
@@ -262,6 +379,7 @@ fn handle_new_game(
|
||||
mut game: ResMut<GameStateResource>,
|
||||
mut changed: MessageWriter<StateChangedEvent>,
|
||||
mut recording: ResMut<RecordingReplay>,
|
||||
mut pending_seed: ResMut<PendingNewGameSeed>,
|
||||
settings: Option<Res<crate::settings_plugin::SettingsResource>>,
|
||||
path: Option<Res<GameStatePath>>,
|
||||
font_res: Option<Res<FontResource>>,
|
||||
@@ -296,6 +414,13 @@ fn handle_new_game(
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
|
||||
// Drop any in-flight winnable-seed search now that we've
|
||||
// committed to acting on a new request. Its result was for
|
||||
// the previous user intent — the new request supersedes it
|
||||
// regardless of which branch we take below (synchronous
|
||||
// explicit-seed deal vs. another async solver search).
|
||||
pending_seed.inner = None;
|
||||
|
||||
let initial_seed = ev.seed.unwrap_or_else(seed_from_system_time);
|
||||
// Prefer the draw mode from Settings when starting a fresh game.
|
||||
// Fall back to the current game's draw mode in headless/test contexts
|
||||
@@ -323,11 +448,22 @@ fn handle_new_game(
|
||||
let winnable_only = settings
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.0.winnable_deals_only);
|
||||
let chosen_seed = if winnable_only && mode == GameMode::Classic && ev.seed.is_none() {
|
||||
choose_winnable_seed(initial_seed, &draw_mode)
|
||||
} else {
|
||||
initial_seed
|
||||
};
|
||||
if winnable_only && mode == GameMode::Classic && ev.seed.is_none() {
|
||||
let dm = draw_mode.clone();
|
||||
let task = AsyncComputeTaskPool::get()
|
||||
.spawn(async move { choose_winnable_seed(initial_seed, &dm) });
|
||||
pending_seed.inner = Some(PendingSeedTask {
|
||||
handle: task,
|
||||
mode: ev.mode,
|
||||
confirmed: ev.confirmed,
|
||||
});
|
||||
// Skip the rest of the new-game flow; the polling system
|
||||
// will re-emit a synthetic event with a chosen seed once
|
||||
// the task resolves.
|
||||
continue;
|
||||
}
|
||||
|
||||
let chosen_seed = initial_seed;
|
||||
|
||||
game.0 = GameState::new_with_mode(chosen_seed, draw_mode, mode);
|
||||
// Reset the in-flight replay buffer — a fresh deal starts with
|
||||
@@ -383,6 +519,132 @@ pub struct ConfirmNoButton;
|
||||
/// and "No (N)" — those were not real Button entities, so the player
|
||||
/// had no hover / press feedback and the modal felt like a debug panel
|
||||
/// (the user's smoke-test "#2 complaint").
|
||||
/// Update-schedule system: once the splash overlay is gone and there's
|
||||
/// a pending restored game waiting for the player's answer, spawn the
|
||||
/// "Welcome back — Continue or start a new game?" modal. Idempotent —
|
||||
/// the existing `RestorePromptScreen` query gates against duplicate
|
||||
/// spawns if Update fires before the player clicks.
|
||||
fn spawn_restore_prompt_if_pending(
|
||||
mut commands: Commands,
|
||||
pending: Res<PendingRestoredGame>,
|
||||
splash: Query<(), With<crate::splash_plugin::SplashRoot>>,
|
||||
existing: Query<(), With<RestorePromptScreen>>,
|
||||
font_res: Option<Res<FontResource>>,
|
||||
) {
|
||||
if pending.0.is_none() || !splash.is_empty() || !existing.is_empty() {
|
||||
return;
|
||||
}
|
||||
spawn_modal(
|
||||
&mut commands,
|
||||
RestorePromptScreen,
|
||||
ui_theme::Z_MODAL_PANEL,
|
||||
|card| {
|
||||
spawn_modal_header(card, "Welcome back", font_res.as_deref());
|
||||
spawn_modal_body_text(
|
||||
card,
|
||||
"You have an in-progress game. Continue where you left off, or start a new one?",
|
||||
ui_theme::TEXT_SECONDARY,
|
||||
font_res.as_deref(),
|
||||
);
|
||||
spawn_modal_actions(card, |actions| {
|
||||
spawn_modal_button(
|
||||
actions,
|
||||
RestoreNewGameButton,
|
||||
"New game",
|
||||
Some("N"),
|
||||
ButtonVariant::Secondary,
|
||||
font_res.as_deref(),
|
||||
);
|
||||
spawn_modal_button(
|
||||
actions,
|
||||
RestoreContinueButton,
|
||||
"Continue",
|
||||
Some("Enter"),
|
||||
ButtonVariant::Primary,
|
||||
font_res.as_deref(),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Click handlers + keyboard shortcuts for the restore prompt.
|
||||
///
|
||||
/// Continue (Enter / C) — swaps the saved game into `GameStateResource`
|
||||
/// and writes a `StateChangedEvent` so card sprites resync to the
|
||||
/// restored layout.
|
||||
/// New game (N) — drops the saved game and writes
|
||||
/// `NewGameRequestEvent { confirmed: true }`. The existing
|
||||
/// `handle_new_game` flow takes over: deletes `game_state.json`, deals
|
||||
/// a fresh game, fires `StateChangedEvent`. `confirmed: true` skips
|
||||
/// the abandon-current-game confirm dialog (the player has already
|
||||
/// confirmed by clicking New game here).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_restore_prompt(
|
||||
mut commands: Commands,
|
||||
keys: Option<Res<ButtonInput<KeyCode>>>,
|
||||
screens: Query<Entity, With<RestorePromptScreen>>,
|
||||
continue_buttons: Query<&Interaction, (With<RestoreContinueButton>, Changed<Interaction>)>,
|
||||
new_game_buttons: Query<&Interaction, (With<RestoreNewGameButton>, Changed<Interaction>)>,
|
||||
mut pending: ResMut<PendingRestoredGame>,
|
||||
mut game: ResMut<GameStateResource>,
|
||||
mut changed: MessageWriter<StateChangedEvent>,
|
||||
mut new_game: MessageWriter<NewGameRequestEvent>,
|
||||
mut launch_home_shown: Option<ResMut<crate::home_plugin::LaunchHomeShown>>,
|
||||
) {
|
||||
if screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Esc maps to Continue rather than New Game so a stray dismiss
|
||||
// press preserves the saved game — the data-preserving default is
|
||||
// the safer fallback when a player hits Esc reflexively to "close
|
||||
// this dialog" without reading it.
|
||||
let key_continue = keys.as_ref().is_some_and(|k| {
|
||||
k.just_pressed(KeyCode::Enter)
|
||||
|| k.just_pressed(KeyCode::KeyC)
|
||||
|| k.just_pressed(KeyCode::Escape)
|
||||
});
|
||||
let key_new = keys.as_ref().is_some_and(|k| k.just_pressed(KeyCode::KeyN));
|
||||
let click_continue = continue_buttons
|
||||
.iter()
|
||||
.any(|i| *i == Interaction::Pressed);
|
||||
let click_new = new_game_buttons.iter().any(|i| *i == Interaction::Pressed);
|
||||
|
||||
let resolved = if key_continue || click_continue {
|
||||
if let Some(restored) = pending.0.take() {
|
||||
game.0 = restored;
|
||||
changed.write(StateChangedEvent);
|
||||
}
|
||||
for entity in &screens {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
true
|
||||
} else if key_new || click_new {
|
||||
pending.0 = None;
|
||||
for entity in &screens {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
new_game.write(NewGameRequestEvent {
|
||||
seed: None,
|
||||
mode: None,
|
||||
confirmed: true,
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
// The player has just made an explicit launch-time choice (continue
|
||||
// saved game, or start a fresh deal). Suppress the launch-time Home
|
||||
// auto-show so it doesn't pop on top of the resolution they picked.
|
||||
// `M` still re-opens the picker on demand.
|
||||
if resolved
|
||||
&& let Some(ref mut shown) = launch_home_shown
|
||||
{
|
||||
shown.0 = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_confirm_dialog(
|
||||
commands: &mut Commands,
|
||||
original_request: NewGameRequestEvent,
|
||||
@@ -936,9 +1198,17 @@ fn auto_save_game_state(
|
||||
path: Option<Res<GameStatePath>>,
|
||||
mut timer: ResMut<AutoSaveTimer>,
|
||||
paused: Option<Res<crate::pause_plugin::PausedResource>>,
|
||||
pending: Res<PendingRestoredGame>,
|
||||
) {
|
||||
// Don't save if paused, game is won, or no moves have been made yet.
|
||||
if paused.is_some_and(|p| p.0) || game.0.is_won || game.0.move_count == 0 {
|
||||
// Don't save if paused, game is won, no moves have been made yet,
|
||||
// or there's a pending restore the player hasn't answered — saving
|
||||
// the fresh-deal placeholder we seeded GameStateResource with at
|
||||
// startup would clobber the real saved game on disk.
|
||||
if paused.is_some_and(|p| p.0)
|
||||
|| game.0.is_won
|
||||
|| game.0.move_count == 0
|
||||
|| pending.0.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
timer.0 += time.delta_secs();
|
||||
@@ -955,17 +1225,25 @@ fn auto_save_game_state(
|
||||
/// player can resume where they left off. Won games are not saved (the
|
||||
/// `save_game_state_to` helper skips them). Blocking on exit is acceptable
|
||||
/// because the game loop is already shutting down.
|
||||
///
|
||||
/// Special case: when `PendingRestoredGame` still holds a saved game the
|
||||
/// player never answered the restore prompt for, write THAT to disk
|
||||
/// instead of the live `GameStateResource`. Otherwise we'd clobber a
|
||||
/// real saved game with the fresh-deal placeholder we seeded
|
||||
/// `GameStateResource` with at startup.
|
||||
fn save_game_state_on_exit(
|
||||
mut exit_events: MessageReader<AppExit>,
|
||||
game: Res<GameStateResource>,
|
||||
path: Res<GameStatePath>,
|
||||
pending: Res<PendingRestoredGame>,
|
||||
) {
|
||||
if exit_events.is_empty() {
|
||||
return;
|
||||
}
|
||||
exit_events.clear();
|
||||
let Some(p) = path.0.as_deref() else { return };
|
||||
if let Err(e) = save_game_state_to(p, &game.0) {
|
||||
let to_save = pending.0.as_ref().unwrap_or(&game.0);
|
||||
if let Err(e) = save_game_state_to(p, to_save) {
|
||||
warn!("game_state: failed to save on exit: {e}");
|
||||
}
|
||||
}
|
||||
@@ -986,6 +1264,14 @@ mod tests {
|
||||
// plugin's build path; clearing them keeps tests self-contained.
|
||||
app.insert_resource(GameStatePath(None));
|
||||
app.insert_resource(ReplayPath(None));
|
||||
// Force `PendingRestoredGame` empty so production saved-game
|
||||
// state on the dev machine's disk (loaded by `GamePlugin::build`)
|
||||
// can't leak into per-test world state and trip the
|
||||
// `pending.0.is_some()` guard in `auto_save_game_state` /
|
||||
// `save_game_state_on_exit`. Without this clear, an
|
||||
// unrelated `~/.local/share/solitaire_quest/game_state.json`
|
||||
// would silently disable the auto-save path under test.
|
||||
app.insert_resource(PendingRestoredGame(None));
|
||||
// Override the system-time seed with a known value.
|
||||
app.world_mut()
|
||||
.resource_mut::<GameStateResource>()
|
||||
@@ -1238,6 +1524,16 @@ mod tests {
|
||||
}
|
||||
|
||||
/// auto_save_game_state writes to disk once the accumulator crosses 30 s.
|
||||
///
|
||||
/// The timer is pre-seeded just past the threshold and the test
|
||||
/// re-arms it before each `app.update()` in a small bounded loop:
|
||||
/// under `MinimalPlugins` the first frame's `Time::delta_secs()`
|
||||
/// can be 0.0 (or, under heavy parallel cargo-test load, large
|
||||
/// enough that the pre-seeded margin is consumed by it), so a
|
||||
/// single-frame check is fragile. Looping until the file appears
|
||||
/// (or hitting the bound) makes the test robust against
|
||||
/// first-frame Time variance without changing the underlying
|
||||
/// behaviour contract.
|
||||
#[test]
|
||||
fn auto_save_writes_after_30_seconds() {
|
||||
use solitaire_data::load_game_state_from;
|
||||
@@ -1253,10 +1549,18 @@ mod tests {
|
||||
.0
|
||||
.move_count = 1;
|
||||
|
||||
// Pre-seed the timer just past the threshold. The system will trigger
|
||||
// on the very next update() without needing to control Time::delta_secs().
|
||||
app.insert_resource(AutoSaveTimer(AUTO_SAVE_INTERVAL_SECS + 0.1));
|
||||
// Re-arm the timer past the threshold every frame and pump
|
||||
// updates until the save fires. Caps at 16 iterations — a
|
||||
// healthy run hits it on the first or second frame; the cap
|
||||
// prevents an infinite loop if a future regression skips
|
||||
// the save unconditionally.
|
||||
for _ in 0..16 {
|
||||
app.insert_resource(AutoSaveTimer(AUTO_SAVE_INTERVAL_SECS + 1.0));
|
||||
app.update();
|
||||
if path.exists() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(path.exists(), "auto-save file must exist after timer crosses threshold");
|
||||
let loaded = load_game_state_from(&path).expect("file must be loadable");
|
||||
@@ -2320,4 +2624,111 @@ mod tests {
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
/// Async-solver flow: a winnable-only request with no explicit
|
||||
/// seed must populate `PendingNewGameSeed` on the same frame the
|
||||
/// request fires (no main-thread stall waiting on the solver),
|
||||
/// and subsequent updates must clear the pending state and
|
||||
/// produce a new GameState.
|
||||
///
|
||||
/// Drives multiple `app.update()` calls because the polling
|
||||
/// system needs at least one tick after spawn to observe the
|
||||
/// task as ready and re-emit the synthetic event.
|
||||
#[test]
|
||||
fn winnable_seed_search_runs_async_and_completes_eventually() {
|
||||
let mut app = test_app(394);
|
||||
insert_settings(&mut app, true);
|
||||
|
||||
app.world_mut().write_message(NewGameRequestEvent {
|
||||
seed: None,
|
||||
mode: None,
|
||||
confirmed: false,
|
||||
});
|
||||
// First update: handle_new_game spawns the solver task and
|
||||
// returns. The GameStateResource is unchanged on this tick —
|
||||
// the player's previous game is still on screen, so the UI
|
||||
// doesn't visually stall.
|
||||
app.update();
|
||||
assert!(
|
||||
app.world().resource::<PendingNewGameSeed>().inner.is_some(),
|
||||
"first frame should have an in-flight solver task",
|
||||
);
|
||||
|
||||
// Pump frames until the polling system observes the task as
|
||||
// ready and re-emits the synthetic event. AsyncComputeTaskPool
|
||||
// is a shared pool across the whole `cargo test` run — when
|
||||
// dozens of tests execute in parallel the pool can take a
|
||||
// while to actually schedule our future. The yield_now() lets
|
||||
// the pool's worker threads make progress between our polls
|
||||
// without burning wall-clock time.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while app.world().resource::<PendingNewGameSeed>().inner.is_some() {
|
||||
app.update();
|
||||
std::thread::yield_now();
|
||||
if std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
app.world().resource::<PendingNewGameSeed>().inner.is_none(),
|
||||
"solver task should have completed within 15 s wall-clock",
|
||||
);
|
||||
// New game completed: a fresh deal carries 0 moves.
|
||||
assert_eq!(
|
||||
app.world().resource::<GameStateResource>().0.move_count,
|
||||
0,
|
||||
"completed new game must be in fresh-deal state",
|
||||
);
|
||||
}
|
||||
|
||||
/// Cancel-on-replace: a winnable-only request that arrives while
|
||||
/// a previous solver task is in flight must drop the previous
|
||||
/// task and queue the new one. The most recently-fired request
|
||||
/// is the one whose seed wins, regardless of which task started
|
||||
/// first.
|
||||
#[test]
|
||||
fn winnable_seed_search_drops_in_flight_task_on_new_request() {
|
||||
let mut app = test_app(394);
|
||||
insert_settings(&mut app, true);
|
||||
|
||||
// Fire the first request; first update spawns the task.
|
||||
app.world_mut().write_message(NewGameRequestEvent {
|
||||
seed: None,
|
||||
mode: None,
|
||||
confirmed: false,
|
||||
});
|
||||
app.update();
|
||||
assert!(
|
||||
app.world().resource::<PendingNewGameSeed>().inner.is_some(),
|
||||
"first request should be in flight",
|
||||
);
|
||||
|
||||
// Fire a SECOND request with an explicit seed before the
|
||||
// first task can complete. handle_new_game's `pending.inner =
|
||||
// None` line must drop the in-flight task; the explicit-seed
|
||||
// branch then bypasses the solver entirely. After this tick
|
||||
// the GameStateResource carries seed 12345, not whatever the
|
||||
// solver would have picked for the first request.
|
||||
app.world_mut().write_message(NewGameRequestEvent {
|
||||
seed: Some(12345),
|
||||
mode: None,
|
||||
confirmed: true,
|
||||
});
|
||||
app.update();
|
||||
|
||||
// Drive a few more ticks to drain any stragglers.
|
||||
for _ in 0..5 {
|
||||
app.update();
|
||||
}
|
||||
|
||||
assert!(
|
||||
app.world().resource::<PendingNewGameSeed>().inner.is_none(),
|
||||
"explicit-seed request must have cancelled the in-flight task",
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().resource::<GameStateResource>().0.seed,
|
||||
12345,
|
||||
"explicit-seed request takes precedence over the dropped solver task",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,25 +13,34 @@
|
||||
//! [`InfoToastEvent`] explaining the gate but does not launch the mode
|
||||
//! or close the overlay.
|
||||
|
||||
use bevy::input::mouse::{MouseScrollUnit, MouseWheel};
|
||||
use bevy::input::ButtonInput;
|
||||
use bevy::prelude::*;
|
||||
use solitaire_core::game_state::DrawMode;
|
||||
use solitaire_data::save_settings_to;
|
||||
|
||||
use crate::challenge_plugin::CHALLENGE_UNLOCK_LEVEL;
|
||||
use crate::daily_challenge_plugin::DailyChallengeResource;
|
||||
use crate::events::{
|
||||
InfoToastEvent, NewGameRequestEvent, StartChallengeRequestEvent,
|
||||
StartDailyChallengeRequestEvent, StartTimeAttackRequestEvent, StartZenRequestEvent,
|
||||
ToggleProfileRequestEvent,
|
||||
};
|
||||
use crate::font_plugin::FontResource;
|
||||
use crate::progress_plugin::ProgressResource;
|
||||
use crate::settings_plugin::{
|
||||
SettingsChangedEvent, SettingsResource, SettingsStoragePath,
|
||||
};
|
||||
use crate::stats_plugin::StatsResource;
|
||||
use crate::ui_focus::{Disabled, FocusGroup, Focusable};
|
||||
use crate::ui_modal::{
|
||||
spawn_modal, spawn_modal_actions, spawn_modal_button, spawn_modal_header, ButtonVariant,
|
||||
ScrimDismissible,
|
||||
};
|
||||
use crate::ui_theme::{
|
||||
ACCENT_PRIMARY, BG_ELEVATED_HI, BORDER_STRONG, BORDER_SUBTLE, RADIUS_MD, STATE_INFO,
|
||||
TEXT_DISABLED, TEXT_PRIMARY, TEXT_SECONDARY, TYPE_BODY, TYPE_BODY_LG, TYPE_CAPTION,
|
||||
VAL_SPACE_1, VAL_SPACE_2, VAL_SPACE_3, Z_MODAL_PANEL,
|
||||
ACCENT_PRIMARY, BG_ELEVATED, BG_ELEVATED_HI, BORDER_STRONG, BORDER_SUBTLE, RADIUS_MD,
|
||||
STATE_INFO, TEXT_DISABLED, TEXT_PRIMARY, TEXT_SECONDARY, TYPE_BODY, TYPE_BODY_LG,
|
||||
TYPE_CAPTION, TYPE_DISPLAY, VAL_SPACE_1, VAL_SPACE_2, VAL_SPACE_3, Z_MODAL_PANEL,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -47,6 +56,31 @@ pub struct HomeScreen;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct HomeCancelButton;
|
||||
|
||||
/// Marker on the player-stats chip strip at the top of the Home modal.
|
||||
/// Clicking the strip opens the Profile overlay so the player can drill
|
||||
/// into level / XP / cosmetics without first dismissing Home.
|
||||
#[derive(Component, Debug)]
|
||||
struct HomeProfileChip;
|
||||
|
||||
/// Marker on the "Draw 1" toggle button inside the Home modal's
|
||||
/// draw-mode row. Clicking flips `Settings.draw_mode` to `DrawOne` and
|
||||
/// fires `SettingsChangedEvent` so audio / UI dependents react.
|
||||
#[derive(Component, Debug)]
|
||||
struct HomeDrawOneButton;
|
||||
|
||||
/// Marker on the "Draw 3" toggle button inside the Home modal's
|
||||
/// draw-mode row. Mirror of [`HomeDrawOneButton`] for `DrawThree`.
|
||||
#[derive(Component, Debug)]
|
||||
struct HomeDrawThreeButton;
|
||||
|
||||
/// Marker on the scrollable inner Node containing the player chips,
|
||||
/// draw-mode row, and tile grid. Wrapping these in a scrollable
|
||||
/// container keeps the modal usable on small viewports — without it,
|
||||
/// the 3-row tile stack pushes the Cancel button off the bottom of
|
||||
/// the screen on 800x600 hardware. Mirrors `SettingsPanelScrollable`.
|
||||
#[derive(Component, Debug)]
|
||||
struct HomeScrollable;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private mode-card data shape
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -87,6 +121,38 @@ impl HomeMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unicode glyph rendered as the picture-tile centrepiece. Stand-in
|
||||
/// for real per-mode artwork — chosen for one-glyph-tells-the-mode
|
||||
/// readability rather than visual fidelity. Swap to `Image` nodes
|
||||
/// when art lands; the rest of the tile layout doesn't change.
|
||||
///
|
||||
/// Picks are constrained to **card suits** (U+2660-2666) and basic
|
||||
/// **Geometric Shapes** (U+25xx) — the two ranges the bundled
|
||||
/// FiraMono-Medium face actually covers. Earlier choices in
|
||||
/// Dingbats (★ ❀ ✦) and Misc Symbols (⌚) rendered as
|
||||
/// missing-glyph rectangles because FiraMono's coverage there is
|
||||
/// minimal.
|
||||
fn glyph(self) -> &'static str {
|
||||
match self {
|
||||
// Black club — card suit, the obvious solitaire mark.
|
||||
HomeMode::Classic => "\u{2663}",
|
||||
// Black diamond — Geometric Shapes; reads as the day's gem.
|
||||
HomeMode::Daily => "\u{25C6}",
|
||||
// White circle — Geometric Shapes; reads as the Zen enso.
|
||||
HomeMode::Zen => "\u{25CB}",
|
||||
// Black up-pointing triangle — Geometric Shapes; reads as
|
||||
// a mountain / a step up in difficulty.
|
||||
HomeMode::Challenge => "\u{25B2}",
|
||||
// Rightwards arrow — Arrows block (U+2190-21FF), a core
|
||||
// range every dev-oriented monospace font (FiraMono
|
||||
// included) ships. Reads as "go / fast-forward" for the
|
||||
// timed mode. Earlier ▶ (U+25B6) did not render; FiraMono
|
||||
// ships ▲ (up triangle) but evidently not the sideways
|
||||
// siblings.
|
||||
HomeMode::TimeAttack => "\u{2192}",
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyboard accelerator that dispatches the same launch event,
|
||||
/// shown in a small chip on the card.
|
||||
fn hotkey(self) -> &'static str {
|
||||
@@ -115,27 +181,69 @@ impl HomeMode {
|
||||
#[derive(Component, Debug)]
|
||||
struct HomeModeCard(HomeMode);
|
||||
|
||||
/// Tracks whether the launch-time Home modal has already been auto-shown
|
||||
/// for this app session. Flipped to `true` by [`spawn_home_on_launch`]
|
||||
/// the first time it spawns the modal, so the auto-show is one-shot per
|
||||
/// process — subsequent dismissals (Cancel / mode pick) don't trigger
|
||||
/// a respawn, but the player can still re-open the picker with `M`.
|
||||
///
|
||||
/// Other plugins (e.g. `game_plugin`'s restore-prompt handler) can flip
|
||||
/// the flag manually to suppress the launch auto-show when the player
|
||||
/// has already made a launch-time choice through a different surface.
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct LaunchHomeShown(pub bool);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plugin
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Registers the M-key toggle, the mode-card click handler, and the
|
||||
/// Cancel-button handler.
|
||||
pub struct HomePlugin;
|
||||
///
|
||||
/// `auto_show_on_launch` (default true) controls whether the picker
|
||||
/// auto-spawns once the splash clears at app start. Headless tests use
|
||||
/// [`HomePlugin::headless`] to opt out so each test starts with no
|
||||
/// modal in the world.
|
||||
pub struct HomePlugin {
|
||||
auto_show_on_launch: bool,
|
||||
}
|
||||
|
||||
impl Default for HomePlugin {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_show_on_launch: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HomePlugin {
|
||||
/// Test-only constructor that disables the launch-time auto-show.
|
||||
/// `MinimalPlugins` test setups don't include a splash, so the
|
||||
/// gating system would otherwise fire on the first tick and
|
||||
/// pre-spawn the modal that every test asserts is absent.
|
||||
pub fn headless() -> Self {
|
||||
Self {
|
||||
auto_show_on_launch: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Plugin for HomePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
// Be defensive about message registration so HomePlugin works
|
||||
// standalone in tests (the actual handlers live in
|
||||
// input_plugin / challenge_plugin / time_attack_plugin /
|
||||
// daily_challenge_plugin, but those plugins might not be
|
||||
// installed in a tightly-scoped headless app).
|
||||
app.add_message::<NewGameRequestEvent>()
|
||||
// Pre-mark the auto-show as already done in headless mode so the
|
||||
// gating system is a permanent no-op for tests.
|
||||
app.insert_resource(LaunchHomeShown(!self.auto_show_on_launch))
|
||||
.add_message::<NewGameRequestEvent>()
|
||||
.add_message::<StartZenRequestEvent>()
|
||||
.add_message::<StartChallengeRequestEvent>()
|
||||
.add_message::<StartTimeAttackRequestEvent>()
|
||||
.add_message::<StartDailyChallengeRequestEvent>()
|
||||
.add_message::<InfoToastEvent>()
|
||||
.add_message::<ToggleProfileRequestEvent>()
|
||||
.add_message::<SettingsChangedEvent>()
|
||||
// Defensively register MouseWheel so `scroll_home_panel`
|
||||
// runs cleanly under MinimalPlugins headless tests too.
|
||||
.add_message::<MouseWheel>()
|
||||
// `.chain()` because several systems (M-toggle, card click,
|
||||
// cancel button, digit-key shortcut) all read the
|
||||
// `HomeScreen` entity and may queue a despawn on it in the
|
||||
@@ -147,25 +255,92 @@ impl Plugin for HomePlugin {
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
spawn_home_on_launch,
|
||||
toggle_home_screen,
|
||||
attach_focusable_to_home_mode_cards,
|
||||
handle_home_card_click,
|
||||
handle_home_cancel_button,
|
||||
handle_home_profile_chip,
|
||||
handle_home_draw_mode_buttons,
|
||||
handle_home_digit_keys,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
)
|
||||
.add_systems(Update, scroll_home_panel);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-show on launch
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Auto-spawns the Home / mode-picker modal once per app session, so
|
||||
/// the player lands on a deliberate "what mode do I want to play"
|
||||
/// screen instead of the default Classic deal.
|
||||
///
|
||||
/// Gated on the launch-time UI being clear:
|
||||
///
|
||||
/// * `SplashRoot` must be gone — the splash owns the foreground during
|
||||
/// the brand beat and the home modal appearing under it would feel
|
||||
/// like a flash of half-rendered UI.
|
||||
/// * `RestorePromptScreen` must not be open and `PendingRestoredGame`
|
||||
/// must be empty — when the player has a saved in-progress game the
|
||||
/// restore prompt takes precedence; the home picker would compete
|
||||
/// with it for attention.
|
||||
/// * `HomeScreen` must not already exist (defensive — e.g. the player
|
||||
/// pressed `M` between ticks).
|
||||
/// * `LaunchHomeShown` flips to `true` after the first spawn so this
|
||||
/// system becomes a no-op for the rest of the session. Cancelling
|
||||
/// the modal therefore goes to the underlying default deal rather
|
||||
/// than respawning the picker.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn spawn_home_on_launch(
|
||||
mut commands: Commands,
|
||||
mut shown: ResMut<LaunchHomeShown>,
|
||||
splash: Query<(), With<crate::splash_plugin::SplashRoot>>,
|
||||
restore_prompts: Query<(), With<crate::game_plugin::RestorePromptScreen>>,
|
||||
pending_restore: Option<Res<crate::game_plugin::PendingRestoredGame>>,
|
||||
existing: Query<(), With<HomeScreen>>,
|
||||
progress: Option<Res<ProgressResource>>,
|
||||
stats: Option<Res<StatsResource>>,
|
||||
settings: Option<Res<SettingsResource>>,
|
||||
daily: Option<Res<DailyChallengeResource>>,
|
||||
font_res: Option<Res<FontResource>>,
|
||||
) {
|
||||
if shown.0
|
||||
|| !splash.is_empty()
|
||||
|| !restore_prompts.is_empty()
|
||||
|| pending_restore.as_ref().is_some_and(|p| p.0.is_some())
|
||||
|| !existing.is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
spawn_home_screen(
|
||||
&mut commands,
|
||||
build_home_context(
|
||||
progress.as_deref(),
|
||||
stats.as_deref(),
|
||||
settings.as_deref(),
|
||||
daily.as_deref(),
|
||||
font_res.as_deref(),
|
||||
),
|
||||
);
|
||||
shown.0 = true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M-key toggle
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn toggle_home_screen(
|
||||
mut commands: Commands,
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
progress: Option<Res<ProgressResource>>,
|
||||
stats: Option<Res<StatsResource>>,
|
||||
settings: Option<Res<SettingsResource>>,
|
||||
daily: Option<Res<DailyChallengeResource>>,
|
||||
font_res: Option<Res<FontResource>>,
|
||||
screens: Query<Entity, With<HomeScreen>>,
|
||||
) {
|
||||
@@ -175,8 +350,54 @@ fn toggle_home_screen(
|
||||
if let Ok(entity) = screens.single() {
|
||||
commands.entity(entity).despawn();
|
||||
} else {
|
||||
let level = progress.as_ref().map_or(0, |p| p.0.level);
|
||||
spawn_home_screen(&mut commands, level, font_res.as_deref());
|
||||
spawn_home_screen(
|
||||
&mut commands,
|
||||
build_home_context(
|
||||
progress.as_deref(),
|
||||
stats.as_deref(),
|
||||
settings.as_deref(),
|
||||
daily.as_deref(),
|
||||
font_res.as_deref(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a [`HomeContext`] from the live resources the Home modal
|
||||
/// reads. Falls back to safe defaults when a resource is missing
|
||||
/// (typical for `MinimalPlugins` headless tests that don't install
|
||||
/// every contributor plugin).
|
||||
fn build_home_context<'a>(
|
||||
progress: Option<&ProgressResource>,
|
||||
stats: Option<&StatsResource>,
|
||||
settings: Option<&SettingsResource>,
|
||||
daily: Option<&DailyChallengeResource>,
|
||||
font_res: Option<&'a FontResource>,
|
||||
) -> HomeContext<'a> {
|
||||
let daily_today = daily.map(|d| {
|
||||
let completed_today = progress
|
||||
.and_then(|p| p.0.daily_challenge_last_completed)
|
||||
.is_some_and(|d_last| d_last == d.date);
|
||||
DailyToday {
|
||||
date_label: d.date.format("%b %-d").to_string(),
|
||||
goal: d.goal_description.clone(),
|
||||
completed_today,
|
||||
}
|
||||
});
|
||||
|
||||
HomeContext {
|
||||
level: progress.map_or(0, |p| p.0.level),
|
||||
total_xp: progress.map_or(0, |p| p.0.total_xp),
|
||||
daily_streak: progress.map_or(0, |p| p.0.daily_challenge_streak),
|
||||
lifetime_score: stats.map_or(0, |s| s.0.lifetime_score),
|
||||
classic_best: stats.map_or(0, |s| s.0.classic_best_score),
|
||||
zen_best: stats.map_or(0, |s| s.0.zen_best_score),
|
||||
challenge_best: stats.map_or(0, |s| s.0.challenge_best_score),
|
||||
daily_today,
|
||||
draw_mode: settings
|
||||
.map(|s| s.0.draw_mode.clone())
|
||||
.unwrap_or(DrawMode::DrawOne),
|
||||
font_res,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,10 +472,22 @@ fn handle_home_card_click(
|
||||
|
||||
fn handle_home_cancel_button(
|
||||
mut commands: Commands,
|
||||
keys: Option<Res<ButtonInput<KeyCode>>>,
|
||||
cancel_buttons: Query<&Interaction, (With<HomeCancelButton>, Changed<Interaction>)>,
|
||||
screens: Query<Entity, With<HomeScreen>>,
|
||||
other_modal_scrims: Query<(), (With<crate::ui_modal::ModalScrim>, Without<HomeScreen>)>,
|
||||
) {
|
||||
if !cancel_buttons.iter().any(|i| *i == Interaction::Pressed) {
|
||||
if screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
let click = cancel_buttons.iter().any(|i| *i == Interaction::Pressed);
|
||||
let esc = keys.is_some_and(|k| k.just_pressed(KeyCode::Escape));
|
||||
// Esc only closes Home when it is the *topmost* modal. With Profile
|
||||
// (or any other ModalScrim) layered on top, the topmost owns the
|
||||
// dismissal — without this gate a single Esc closed the back
|
||||
// modal (Home) and left the front modal orphaned.
|
||||
let esc_targets_home = esc && other_modal_scrims.is_empty();
|
||||
if !click && !esc_targets_home {
|
||||
return;
|
||||
}
|
||||
for entity in &screens {
|
||||
@@ -262,6 +495,115 @@ fn handle_home_cancel_button(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Header chip + draw-mode button handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Routes mouse-wheel events into the Home modal's scrollable body
|
||||
/// while the modal is open. No-op when no `HomeScrollable` exists in
|
||||
/// the world (modal closed). Mirrors `scroll_settings_panel` and
|
||||
/// `scroll_leaderboard_panel`.
|
||||
fn scroll_home_panel(
|
||||
mut scroll_evr: MessageReader<MouseWheel>,
|
||||
mut scrollables: Query<&mut ScrollPosition, With<HomeScrollable>>,
|
||||
) {
|
||||
if scrollables.is_empty() {
|
||||
scroll_evr.clear();
|
||||
return;
|
||||
}
|
||||
let delta_y: f32 = scroll_evr
|
||||
.read()
|
||||
.map(|ev| match ev.unit {
|
||||
MouseScrollUnit::Line => ev.y * 50.0,
|
||||
MouseScrollUnit::Pixel => ev.y,
|
||||
})
|
||||
.sum();
|
||||
if delta_y == 0.0 {
|
||||
return;
|
||||
}
|
||||
for mut sp in scrollables.iter_mut() {
|
||||
sp.0.y = (sp.0.y - delta_y).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Click on the player-stats header chip → fire
|
||||
/// [`ToggleProfileRequestEvent`] so the Profile overlay opens on top
|
||||
/// of Home. Closing Profile (`P` / `Esc`) returns the player to the
|
||||
/// Home picker without losing their context.
|
||||
fn handle_home_profile_chip(
|
||||
chips: Query<&Interaction, (With<HomeProfileChip>, Changed<Interaction>)>,
|
||||
mut profile: MessageWriter<ToggleProfileRequestEvent>,
|
||||
) {
|
||||
if chips.iter().any(|i| *i == Interaction::Pressed) {
|
||||
profile.write(ToggleProfileRequestEvent);
|
||||
}
|
||||
}
|
||||
|
||||
/// Click on a draw-mode chip — flip `Settings.draw_mode`, persist,
|
||||
/// fire `SettingsChangedEvent`, and respawn the Home modal so the
|
||||
/// active-chip styling reflects the new state. Repaint by full
|
||||
/// rebuild keeps the helper code small (no per-entity colour
|
||||
/// surgery) and the modal is light enough to respawn cleanly.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_home_draw_mode_buttons(
|
||||
mut commands: Commands,
|
||||
one_buttons: Query<&Interaction, (With<HomeDrawOneButton>, Changed<Interaction>)>,
|
||||
three_buttons: Query<&Interaction, (With<HomeDrawThreeButton>, Changed<Interaction>)>,
|
||||
screens: Query<Entity, With<HomeScreen>>,
|
||||
mut settings: Option<ResMut<SettingsResource>>,
|
||||
storage_path: Option<Res<SettingsStoragePath>>,
|
||||
mut changed: MessageWriter<SettingsChangedEvent>,
|
||||
progress: Option<Res<ProgressResource>>,
|
||||
stats: Option<Res<StatsResource>>,
|
||||
daily: Option<Res<DailyChallengeResource>>,
|
||||
font_res: Option<Res<FontResource>>,
|
||||
) {
|
||||
if screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
let want_one = one_buttons.iter().any(|i| *i == Interaction::Pressed);
|
||||
let want_three = three_buttons.iter().any(|i| *i == Interaction::Pressed);
|
||||
if !want_one && !want_three {
|
||||
return;
|
||||
}
|
||||
let Some(settings) = settings.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let target = if want_one {
|
||||
DrawMode::DrawOne
|
||||
} else {
|
||||
DrawMode::DrawThree
|
||||
};
|
||||
if settings.0.draw_mode == target {
|
||||
return; // already in this mode — avoid a redundant respawn.
|
||||
}
|
||||
settings.0.draw_mode = target;
|
||||
if let Some(p) = storage_path
|
||||
&& let Some(path) = p.0.as_deref()
|
||||
&& let Err(e) = save_settings_to(path, &settings.0)
|
||||
{
|
||||
warn!("home: failed to persist draw-mode change: {e}");
|
||||
}
|
||||
changed.write(SettingsChangedEvent(settings.0.clone()));
|
||||
|
||||
// Repaint by despawn + respawn so the chip styling and any
|
||||
// dependent labels (none today, but Phase B may surface a
|
||||
// "Standard (Draw 1)" caption like MSSC) reflect the new state.
|
||||
for entity in &screens {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
spawn_home_screen(
|
||||
&mut commands,
|
||||
build_home_context(
|
||||
progress.as_deref(),
|
||||
stats.as_deref(),
|
||||
Some(settings),
|
||||
daily.as_deref(),
|
||||
font_res.as_deref(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Digit-key shortcuts (1-5) — modal-scoped
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -358,11 +700,84 @@ fn handle_home_digit_keys(
|
||||
// Spawn helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Spawns the Home modal with five mode cards plus a Cancel button.
|
||||
fn spawn_home_screen(commands: &mut Commands, level: u32, font_res: Option<&FontResource>) {
|
||||
/// Bundles the data the Home modal needs to render the new
|
||||
/// MSSC-inspired header chips, per-mode score chips, and draw-mode
|
||||
/// row. Built fresh by the two call sites (`spawn_home_on_launch`
|
||||
/// and `toggle_home_screen`) from the live progress / stats /
|
||||
/// settings resources, with sensible defaults when a resource is
|
||||
/// missing under `MinimalPlugins` headless tests.
|
||||
struct HomeContext<'a> {
|
||||
level: u32,
|
||||
total_xp: u64,
|
||||
lifetime_score: u64,
|
||||
classic_best: u32,
|
||||
zen_best: u32,
|
||||
challenge_best: u32,
|
||||
daily_streak: u32,
|
||||
daily_today: Option<DailyToday>,
|
||||
draw_mode: DrawMode,
|
||||
font_res: Option<&'a FontResource>,
|
||||
}
|
||||
|
||||
/// Today's daily-challenge metadata as the Home picker needs it. Only
|
||||
/// populated when both [`DailyChallengeResource`] is present (the
|
||||
/// plugin is wired) and we have something useful to show — otherwise
|
||||
/// the Daily card falls back to its baseline description without a
|
||||
/// dated callout.
|
||||
struct DailyToday {
|
||||
/// Short calendar label, e.g. `"May 6"`. Always populated.
|
||||
date_label: String,
|
||||
/// Server-supplied goal copy ("Win in under 5 minutes"). `None`
|
||||
/// when no server backend is wired or the fetch hasn't returned.
|
||||
goal: Option<String>,
|
||||
/// `true` when the player has already recorded today's daily.
|
||||
/// Surfaces a "Done" badge so the picker reads as reward-state
|
||||
/// rather than "you still owe today's run".
|
||||
completed_today: bool,
|
||||
}
|
||||
|
||||
/// Spawns the Home modal with the player-stats header strip, draw-mode
|
||||
/// row, five mode cards, and a Cancel button.
|
||||
fn spawn_home_screen(commands: &mut Commands, ctx: HomeContext<'_>) {
|
||||
let HomeContext { font_res, .. } = ctx;
|
||||
let scrim = spawn_modal(commands, HomeScreen, Z_MODAL_PANEL, |card| {
|
||||
spawn_modal_header(card, "Choose a Mode", font_res);
|
||||
|
||||
// Scrollable middle — chips + draw row + tile grid. Constrained
|
||||
// to 70vh so the modal fits on small viewports (the 5-tile
|
||||
// grid alone is ~540 px). Cancel button sits outside this
|
||||
// node so it's always one click away.
|
||||
card.spawn((
|
||||
HomeScrollable,
|
||||
ScrollPosition::default(),
|
||||
Node {
|
||||
flex_direction: FlexDirection::Column,
|
||||
row_gap: VAL_SPACE_3,
|
||||
width: Val::Percent(100.0),
|
||||
max_height: Val::Vh(70.0),
|
||||
overflow: Overflow::scroll_y(),
|
||||
..default()
|
||||
},
|
||||
))
|
||||
.with_children(|body| {
|
||||
spawn_home_header_chips(body, &ctx);
|
||||
spawn_draw_mode_row(body, &ctx);
|
||||
|
||||
// Mode tiles in a wrapping 2-column grid. Each tile takes 48%
|
||||
// of the row so column_gap fits comfortably; the 5 modes wrap
|
||||
// to a third row of one tile, which we leave left-aligned —
|
||||
// the asymmetry matches MSSC's "Daily Challenges / Today's
|
||||
// Event" half-cell on the right of their grid and keeps the
|
||||
// visual rhythm.
|
||||
body.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
flex_wrap: FlexWrap::Wrap,
|
||||
row_gap: VAL_SPACE_3,
|
||||
column_gap: VAL_SPACE_3,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|grid| {
|
||||
for mode in [
|
||||
HomeMode::Classic,
|
||||
HomeMode::Daily,
|
||||
@@ -370,8 +785,10 @@ fn spawn_home_screen(commands: &mut Commands, level: u32, font_res: Option<&Font
|
||||
HomeMode::Challenge,
|
||||
HomeMode::TimeAttack,
|
||||
] {
|
||||
spawn_mode_card(card, mode, level, font_res);
|
||||
spawn_mode_card(grid, mode, &ctx);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
spawn_modal_actions(card, |actions| {
|
||||
spawn_modal_button(
|
||||
@@ -388,6 +805,188 @@ fn spawn_home_screen(commands: &mut Commands, level: u32, font_res: Option<&Font
|
||||
commands.entity(scrim).insert(ScrimDismissible);
|
||||
}
|
||||
|
||||
/// Player-stats chip strip — Level, XP, Lifetime Score. Clickable as a
|
||||
/// whole to open the Profile overlay (mirrors the MSSC top-right
|
||||
/// avatar+rewards corner that surfaces level + premium status). Falls
|
||||
/// back to plain Text in headless contexts where `Button` interaction
|
||||
/// isn't driven by the input pipeline anyway.
|
||||
fn spawn_home_header_chips(parent: &mut ChildSpawnerCommands, ctx: &HomeContext<'_>) {
|
||||
let font_handle = ctx.font_res.map(|f| f.0.clone()).unwrap_or_default();
|
||||
let font_label = TextFont {
|
||||
font: font_handle.clone(),
|
||||
font_size: TYPE_CAPTION,
|
||||
..default()
|
||||
};
|
||||
let font_value = TextFont {
|
||||
font: font_handle,
|
||||
font_size: TYPE_BODY,
|
||||
..default()
|
||||
};
|
||||
|
||||
parent
|
||||
.spawn((
|
||||
HomeProfileChip,
|
||||
Button,
|
||||
Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
justify_content: JustifyContent::SpaceBetween,
|
||||
column_gap: VAL_SPACE_2,
|
||||
padding: UiRect::axes(VAL_SPACE_3, VAL_SPACE_2),
|
||||
border: UiRect::all(Val::Px(1.0)),
|
||||
border_radius: BorderRadius::all(Val::Px(RADIUS_MD)),
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
},
|
||||
BackgroundColor(BG_ELEVATED),
|
||||
BorderColor::all(BORDER_SUBTLE),
|
||||
))
|
||||
.with_children(|row| {
|
||||
for (label, value) in [
|
||||
("Level".to_string(), format_compact(ctx.level as u64)),
|
||||
("XP".to_string(), format_compact(ctx.total_xp)),
|
||||
("Score".to_string(), format_compact(ctx.lifetime_score)),
|
||||
] {
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Column,
|
||||
align_items: AlignItems::Center,
|
||||
row_gap: VAL_SPACE_1,
|
||||
..default()
|
||||
})
|
||||
.with_children(|col| {
|
||||
col.spawn((
|
||||
Text::new(label),
|
||||
font_label.clone(),
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
col.spawn((
|
||||
Text::new(value),
|
||||
font_value.clone(),
|
||||
TextColor(ACCENT_PRIMARY),
|
||||
));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw-mode row — "Draw 1" / "Draw 3" toggle. Affects the next Classic
|
||||
/// deal (the Settings value the new-game flow reads). Surfacing it on
|
||||
/// the Home modal keeps the per-game choice one tap away rather than
|
||||
/// buried in Settings, mirroring the dropdown MSSC puts on its
|
||||
/// difficulty picker.
|
||||
fn spawn_draw_mode_row(parent: &mut ChildSpawnerCommands, ctx: &HomeContext<'_>) {
|
||||
let font_handle = ctx.font_res.map(|f| f.0.clone()).unwrap_or_default();
|
||||
let font_label = TextFont {
|
||||
font: font_handle.clone(),
|
||||
font_size: TYPE_CAPTION,
|
||||
..default()
|
||||
};
|
||||
let font_btn = TextFont {
|
||||
font: font_handle,
|
||||
font_size: TYPE_BODY,
|
||||
..default()
|
||||
};
|
||||
|
||||
let active_one = matches!(ctx.draw_mode, DrawMode::DrawOne);
|
||||
|
||||
parent
|
||||
.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_3,
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
row.spawn((
|
||||
Text::new("Draw mode"),
|
||||
font_label.clone(),
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
spawn_draw_mode_chip::<HomeDrawOneButton>(
|
||||
row,
|
||||
HomeDrawOneButton,
|
||||
"Draw 1",
|
||||
active_one,
|
||||
&font_btn,
|
||||
);
|
||||
spawn_draw_mode_chip::<HomeDrawThreeButton>(
|
||||
row,
|
||||
HomeDrawThreeButton,
|
||||
"Draw 3",
|
||||
!active_one,
|
||||
&font_btn,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_draw_mode_chip<M: Component>(
|
||||
parent: &mut ChildSpawnerCommands,
|
||||
marker: M,
|
||||
label: &str,
|
||||
active: bool,
|
||||
font: &TextFont,
|
||||
) {
|
||||
let (bg, fg) = if active {
|
||||
(ACCENT_PRIMARY, BG_ELEVATED)
|
||||
} else {
|
||||
(BG_ELEVATED_HI, TEXT_PRIMARY)
|
||||
};
|
||||
parent
|
||||
.spawn((
|
||||
marker,
|
||||
Button,
|
||||
Node {
|
||||
padding: UiRect::axes(VAL_SPACE_3, VAL_SPACE_1),
|
||||
border: UiRect::all(Val::Px(1.0)),
|
||||
border_radius: BorderRadius::all(Val::Px(RADIUS_MD)),
|
||||
..default()
|
||||
},
|
||||
BackgroundColor(bg),
|
||||
BorderColor::all(BORDER_SUBTLE),
|
||||
))
|
||||
.with_children(|c| {
|
||||
c.spawn((Text::new(label.to_string()), font.clone(), TextColor(fg)));
|
||||
});
|
||||
}
|
||||
|
||||
/// Compact decimal formatter: `1234567` → `"1.2M"`, `12345` → `"12.3K"`,
|
||||
/// otherwise the raw number with thousands separators. Keeps chip text
|
||||
/// short enough to fit a 3-up header strip without wrapping.
|
||||
fn format_compact(n: u64) -> String {
|
||||
if n >= 1_000_000 {
|
||||
format!("{:.1}M", n as f64 / 1_000_000.0)
|
||||
} else if n >= 10_000 {
|
||||
format!("{:.1}K", n as f64 / 1_000.0)
|
||||
} else if n >= 1_000 {
|
||||
let (high, low) = (n / 1_000, n % 1_000);
|
||||
format!("{high},{low:03}")
|
||||
} else {
|
||||
n.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-mode score / streak chip text. `None` for modes where no
|
||||
/// per-mode best exists yet (Time Attack uses session scoring; modes
|
||||
/// with `0` recorded mean "no win yet" and we hide the chip rather
|
||||
/// than show a 0).
|
||||
fn score_chip_text_for(mode: HomeMode, ctx: &HomeContext<'_>) -> Option<String> {
|
||||
match mode {
|
||||
HomeMode::Classic if ctx.classic_best > 0 => {
|
||||
Some(format!("Best {}", format_compact(ctx.classic_best as u64)))
|
||||
}
|
||||
HomeMode::Zen if ctx.zen_best > 0 => {
|
||||
Some(format!("Best {}", format_compact(ctx.zen_best as u64)))
|
||||
}
|
||||
HomeMode::Challenge if ctx.challenge_best > 0 => {
|
||||
Some(format!("Best {}", format_compact(ctx.challenge_best as u64)))
|
||||
}
|
||||
HomeMode::Daily if ctx.daily_streak > 0 => {
|
||||
Some(format!("Streak {}", ctx.daily_streak))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tab-walk order for each mode card, matching the visual top-to-bottom
|
||||
/// stack inside the Home modal. Lower numbers receive focus first under
|
||||
/// `Focusable`'s sort.
|
||||
@@ -459,9 +1058,11 @@ fn attach_focusable_to_home_mode_cards(
|
||||
fn spawn_mode_card(
|
||||
parent: &mut ChildSpawnerCommands,
|
||||
mode: HomeMode,
|
||||
level: u32,
|
||||
font_res: Option<&FontResource>,
|
||||
ctx: &HomeContext<'_>,
|
||||
) {
|
||||
let level = ctx.level;
|
||||
let font_res = ctx.font_res;
|
||||
let score_chip = score_chip_text_for(mode, ctx);
|
||||
let unlocked = mode.is_unlocked(level);
|
||||
let font_handle = font_res.map(|f| f.0.clone()).unwrap_or_default();
|
||||
let font_title = TextFont {
|
||||
@@ -475,10 +1076,17 @@ fn spawn_mode_card(
|
||||
..default()
|
||||
};
|
||||
let font_chip = TextFont {
|
||||
font: font_handle,
|
||||
font: font_handle.clone(),
|
||||
font_size: TYPE_CAPTION,
|
||||
..default()
|
||||
};
|
||||
// Glyph rendered at display size — Unicode emoji standing in for
|
||||
// the per-mode artwork. Centred at the top of the tile.
|
||||
let font_glyph = TextFont {
|
||||
font: font_handle,
|
||||
font_size: TYPE_DISPLAY,
|
||||
..default()
|
||||
};
|
||||
|
||||
// Locked cards mute their text to communicate the disabled state at
|
||||
// a glance; the explicit "Unlocks at level N" caption underneath
|
||||
@@ -486,6 +1094,7 @@ fn spawn_mode_card(
|
||||
let title_color = if unlocked { TEXT_PRIMARY } else { TEXT_DISABLED };
|
||||
let desc_color = if unlocked { TEXT_SECONDARY } else { TEXT_DISABLED };
|
||||
let border_color = if unlocked { BORDER_SUBTLE } else { BORDER_STRONG };
|
||||
let glyph_color = if unlocked { ACCENT_PRIMARY } else { TEXT_DISABLED };
|
||||
|
||||
parent
|
||||
.spawn((
|
||||
@@ -496,9 +1105,13 @@ fn spawn_mode_card(
|
||||
Button,
|
||||
Node {
|
||||
flex_direction: FlexDirection::Column,
|
||||
row_gap: VAL_SPACE_1,
|
||||
row_gap: VAL_SPACE_2,
|
||||
padding: UiRect::all(VAL_SPACE_3),
|
||||
width: Val::Percent(100.0),
|
||||
// 48% per tile + the row's column_gap = a clean 2-up
|
||||
// grid that wraps to a single tile on the third row.
|
||||
width: Val::Percent(48.0),
|
||||
min_height: Val::Px(180.0),
|
||||
align_items: AlignItems::Center,
|
||||
border: UiRect::all(Val::Px(1.0)),
|
||||
border_radius: BorderRadius::all(Val::Px(RADIUS_MD)),
|
||||
..default()
|
||||
@@ -507,12 +1120,20 @@ fn spawn_mode_card(
|
||||
BorderColor::all(border_color),
|
||||
))
|
||||
.with_children(|c| {
|
||||
// Centerpiece glyph — placeholder for real per-mode art.
|
||||
c.spawn((
|
||||
Text::new(mode.glyph().to_string()),
|
||||
font_glyph.clone(),
|
||||
TextColor(glyph_color),
|
||||
));
|
||||
|
||||
// Title row — title text on the left, hotkey chip on the right.
|
||||
c.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
justify_content: JustifyContent::SpaceBetween,
|
||||
column_gap: VAL_SPACE_3,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -562,6 +1183,59 @@ fn spawn_mode_card(
|
||||
TextColor(desc_color),
|
||||
));
|
||||
|
||||
// Per-mode score / streak chip — populated only when the
|
||||
// player has data for this mode. Hidden on a 0 best so a
|
||||
// fresh profile doesn't show "Best 0" everywhere.
|
||||
if let Some(text) = score_chip.clone()
|
||||
&& unlocked
|
||||
{
|
||||
c.spawn((
|
||||
Text::new(text),
|
||||
font_chip.clone(),
|
||||
TextColor(ACCENT_PRIMARY),
|
||||
Node {
|
||||
margin: UiRect::top(VAL_SPACE_1),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
// Daily-only "Today's Event" caption — date, optional
|
||||
// server goal, and a "Done" badge once the player has
|
||||
// already recorded today's completion. Only renders for
|
||||
// the Daily card when DailyChallengeResource is present.
|
||||
if matches!(mode, HomeMode::Daily)
|
||||
&& unlocked
|
||||
&& let Some(today) = ctx.daily_today.as_ref()
|
||||
{
|
||||
let date_text = if today.completed_today {
|
||||
format!("Today, {} \u{2022} Done", today.date_label)
|
||||
} else {
|
||||
format!("Today, {}", today.date_label)
|
||||
};
|
||||
let date_color = if today.completed_today {
|
||||
ACCENT_PRIMARY
|
||||
} else {
|
||||
STATE_INFO
|
||||
};
|
||||
c.spawn((
|
||||
Text::new(date_text),
|
||||
font_chip.clone(),
|
||||
TextColor(date_color),
|
||||
Node {
|
||||
margin: UiRect::top(VAL_SPACE_1),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
if let Some(goal) = today.goal.as_ref() {
|
||||
c.spawn((
|
||||
Text::new(format!("Goal: {goal}")),
|
||||
font_chip.clone(),
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Locked footnote — explicit copy so the gate is unambiguous.
|
||||
if !unlocked {
|
||||
c.spawn((
|
||||
@@ -602,7 +1276,7 @@ mod tests {
|
||||
.add_plugins(GamePlugin)
|
||||
.add_plugins(TablePlugin)
|
||||
.add_plugins(ProgressPlugin::headless())
|
||||
.add_plugins(HomePlugin);
|
||||
.add_plugins(HomePlugin::headless());
|
||||
app.init_resource::<ButtonInput<KeyCode>>();
|
||||
app.update();
|
||||
app
|
||||
@@ -892,7 +1566,7 @@ mod tests {
|
||||
.add_plugins(GamePlugin)
|
||||
.add_plugins(TablePlugin)
|
||||
.add_plugins(ProgressPlugin::headless())
|
||||
.add_plugins(HomePlugin);
|
||||
.add_plugins(HomePlugin::headless());
|
||||
app.init_resource::<ButtonInput<KeyCode>>();
|
||||
app.update();
|
||||
app
|
||||
|
||||
@@ -62,6 +62,18 @@ pub struct HudMode;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct HudChallenge;
|
||||
|
||||
/// Marker on the "won this deal before" indicator text node.
|
||||
///
|
||||
/// Displays `"✓ Won before"` when the current deal's seed + draw_mode +
|
||||
/// mode triple matches one of the entries in `ReplayHistoryResource`.
|
||||
/// Empty string otherwise (including won games — the score readout
|
||||
/// already conveys the win on the active deal). Only meaningful for
|
||||
/// Classic / Zen / Challenge — daily-challenge and time-attack seeds
|
||||
/// are filtered out implicitly because their replay entries always
|
||||
/// carry a different mode tag.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct HudWonPreviously;
|
||||
|
||||
/// Marker on the undo-count text node.
|
||||
///
|
||||
/// Shows how many undos have been used this game. Displayed in amber when
|
||||
@@ -194,6 +206,16 @@ pub const SCORE_FLOATER_THRESHOLD: i32 = 50;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct ActionButton;
|
||||
|
||||
/// Marker on rows inside a popover panel ([`ModesPopover`] or
|
||||
/// [`MenuPopover`]). Popover rows already carry `ActionButton` so the
|
||||
/// hover/press paint path applies to them, but the auto-fade applied
|
||||
/// to the top-level action bar must NOT also fade these rows — the
|
||||
/// popover only renders when the player has explicitly opened it, so
|
||||
/// its content should always be at full opacity. `apply_action_fade`
|
||||
/// excludes entities with this marker via `Without<PopoverRow>`.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct PopoverRow;
|
||||
|
||||
/// Marker on the "New Game" action button anchored top-right of the play
|
||||
/// area. Click fires [`NewGameRequestEvent`]; the existing
|
||||
/// `ConfirmNewGameScreen` modal handles confirmation when a game is in
|
||||
@@ -302,6 +324,7 @@ impl Plugin for HudPlugin {
|
||||
.init_resource::<HudActionFade>()
|
||||
.add_systems(Startup, (spawn_hud_band, spawn_hud, spawn_action_buttons))
|
||||
.add_systems(Update, update_hud.after(GameMutation))
|
||||
.add_systems(Update, update_won_previously.after(GameMutation))
|
||||
.add_systems(Update, announce_auto_complete.after(GameMutation))
|
||||
.add_systems(Update, update_selection_hud)
|
||||
.add_systems(
|
||||
@@ -481,6 +504,15 @@ fn spawn_hud(font_res: Option<Res<FontResource>>, mut commands: Commands) {
|
||||
font_body.clone(),
|
||||
TextColor(STATE_INFO),
|
||||
));
|
||||
t2.spawn((
|
||||
HudWonPreviously,
|
||||
Tooltip::new(
|
||||
"You've won this deal before. Same seed in your replay history.",
|
||||
),
|
||||
Text::new(""),
|
||||
font_body.clone(),
|
||||
TextColor(STATE_SUCCESS),
|
||||
));
|
||||
});
|
||||
|
||||
// Tier 3 — penalty / bonus. Undos and Recycles share the
|
||||
@@ -834,6 +866,7 @@ fn spawn_modes_popover(
|
||||
.spawn((
|
||||
option,
|
||||
ActionButton,
|
||||
PopoverRow,
|
||||
Button,
|
||||
Tooltip::new(tooltip),
|
||||
Node {
|
||||
@@ -987,6 +1020,7 @@ fn spawn_menu_popover(commands: &mut Commands, font_res: Option<&FontResource>)
|
||||
.spawn((
|
||||
option,
|
||||
ActionButton,
|
||||
PopoverRow,
|
||||
Button,
|
||||
Tooltip::new(tooltip),
|
||||
Node {
|
||||
@@ -1117,9 +1151,20 @@ fn update_action_fade(
|
||||
/// `Last` (after `paint_action_buttons`) so a hover-state change in the
|
||||
/// same frame doesn't override the fade with an opaque idle / hover
|
||||
/// colour.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn apply_action_fade(
|
||||
fade: Res<HudActionFade>,
|
||||
mut buttons: Query<(&Children, &mut BackgroundColor), With<ActionButton>>,
|
||||
// Excludes `PopoverRow` so the auto-fade only applies to the
|
||||
// top-level action bar buttons. Popover rows live inside an
|
||||
// explicitly-opened dropdown panel and need to stay visible
|
||||
// regardless of the bar's fade state — without the exclusion
|
||||
// the rows fade to invisible while the popover container stays
|
||||
// visible, leaving a solid background block with no readable
|
||||
// content.
|
||||
mut buttons: Query<
|
||||
(&Children, &mut BackgroundColor),
|
||||
(With<ActionButton>, Without<PopoverRow>),
|
||||
>,
|
||||
mut text_q: Query<&mut TextColor>,
|
||||
) {
|
||||
for (children, mut bg) in &mut buttons {
|
||||
@@ -1480,6 +1525,42 @@ fn lerp_text_color(from: Color, to: Color, t: f32) -> Color {
|
||||
)
|
||||
}
|
||||
|
||||
/// Sets the [`HudWonPreviously`] text to "✓ Won before" whenever the
|
||||
/// current deal's seed + draw_mode + mode triple matches an entry in
|
||||
/// the rolling [`ReplayHistory`]. Cleared while the active game is won
|
||||
/// (the on-screen "Game won!" cue already conveys victory) and on
|
||||
/// fresh deals the player hasn't won before.
|
||||
///
|
||||
/// Lives in its own system rather than `update_hud` to keep this
|
||||
/// orthogonal: `update_hud`'s query disambiguation is already busy
|
||||
/// enough; threading another marker through every Without filter
|
||||
/// would touch ~10 unrelated queries for no benefit.
|
||||
fn update_won_previously(
|
||||
game: Res<GameStateResource>,
|
||||
// Optional because the HUD plugin's headless tests run without
|
||||
// `StatsPlugin` and therefore without this resource. With the
|
||||
// resource absent there's no history to compare against; the
|
||||
// indicator just stays empty.
|
||||
history: Option<Res<crate::stats_plugin::ReplayHistoryResource>>,
|
||||
mut q: Query<&mut Text, With<HudWonPreviously>>,
|
||||
) {
|
||||
let Ok(mut text) = q.single_mut() else {
|
||||
return;
|
||||
};
|
||||
let won_before = !game.0.is_won
|
||||
&& history.as_ref().is_some_and(|h| {
|
||||
h.0.replays.iter().any(|r| {
|
||||
r.seed == game.0.seed
|
||||
&& r.draw_mode == game.0.draw_mode
|
||||
&& r.mode == game.0.mode
|
||||
})
|
||||
});
|
||||
let next = if won_before { "\u{2713} Won before" } else { "" };
|
||||
if text.0 != next {
|
||||
text.0 = next.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||
fn update_hud(
|
||||
game: Res<GameStateResource>,
|
||||
|
||||
@@ -40,10 +40,10 @@ use solitaire_core::game_state::DrawMode;
|
||||
use crate::challenge_plugin::CHALLENGE_UNLOCK_LEVEL;
|
||||
use crate::events::{
|
||||
DrawRequestEvent, ForfeitRequestEvent, HintVisualEvent, InfoToastEvent, MoveRejectedEvent,
|
||||
MoveRequestEvent, NewGameConfirmEvent, NewGameRequestEvent, StartZenRequestEvent,
|
||||
StateChangedEvent, UndoRequestEvent,
|
||||
MoveRequestEvent, NewGameRequestEvent, StartZenRequestEvent, StateChangedEvent,
|
||||
UndoRequestEvent,
|
||||
};
|
||||
use crate::game_plugin::GameMutation;
|
||||
use crate::game_plugin::{ConfirmNewGameScreen, GameMutation, RestorePromptScreen};
|
||||
use crate::pause_plugin::PausedResource;
|
||||
use crate::progress_plugin::ProgressResource;
|
||||
use crate::layout::{Layout, LayoutResource};
|
||||
@@ -64,22 +64,6 @@ const DRAG_Z: f32 = 500.0;
|
||||
#[derive(Resource, Debug, Clone, Default)]
|
||||
pub struct HintSolverConfig(pub solitaire_core::solver::SolverConfig);
|
||||
|
||||
/// Shared countdown state for the new-game double-press confirmation
|
||||
/// flow.
|
||||
///
|
||||
/// Using a resource (instead of `Local`) lets the keyboard sub-systems
|
||||
/// share the same countdown state without needing to pass values
|
||||
/// between them. Forfeit no longer has a keyboard countdown — `G` now
|
||||
/// fires `ForfeitRequestEvent` and `PausePlugin` shows a real
|
||||
/// `ForfeitConfirmScreen` modal.
|
||||
#[derive(Resource, Debug, Default)]
|
||||
struct KeyboardConfirmState {
|
||||
/// Seconds remaining in the new-game confirmation window (> 0 while open).
|
||||
new_game_countdown: f32,
|
||||
/// True while we are waiting for the second N press to confirm a new game.
|
||||
new_game_pending: bool,
|
||||
}
|
||||
|
||||
/// Registers keyboard, mouse, and touch input systems.
|
||||
///
|
||||
/// Mouse drag pipeline (ordered, left-to-right):
|
||||
@@ -100,8 +84,7 @@ impl Plugin for InputPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<HintCycleIndex>()
|
||||
.init_resource::<HintSolverConfig>()
|
||||
.init_resource::<KeyboardConfirmState>()
|
||||
.add_message::<NewGameConfirmEvent>()
|
||||
.init_resource::<crate::pending_hint::PendingHintTask>()
|
||||
.add_message::<StartZenRequestEvent>()
|
||||
.add_message::<InfoToastEvent>()
|
||||
.add_message::<ForfeitRequestEvent>()
|
||||
@@ -127,13 +110,21 @@ impl Plugin for InputPlugin {
|
||||
.chain(),
|
||||
)
|
||||
.add_systems(Update, handle_fullscreen)
|
||||
.add_systems(Update, reset_hint_cycle_on_state_change);
|
||||
.add_systems(Update, reset_hint_cycle_on_state_change)
|
||||
// Async hint pipeline: state-change drop runs before the
|
||||
// poll system so a move applied this frame cancels any
|
||||
// in-flight task before its result can be surfaced.
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
crate::pending_hint::drop_pending_hint_on_state_change,
|
||||
crate::pending_hint::poll_pending_hint_task,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds after the first N press during which a second N confirms new game.
|
||||
const NEW_GAME_CONFIRM_WINDOW: f32 = 3.0;
|
||||
|
||||
/// Bundles the event writers needed by the core keyboard handler.
|
||||
///
|
||||
/// Keeping these in a [`SystemParam`] avoids hitting Bevy's 16-parameter limit.
|
||||
@@ -141,43 +132,39 @@ const NEW_GAME_CONFIRM_WINDOW: f32 = 3.0;
|
||||
struct CoreKeyboardMessages<'w> {
|
||||
undo: MessageWriter<'w, UndoRequestEvent>,
|
||||
new_game: MessageWriter<'w, NewGameRequestEvent>,
|
||||
confirm_event: MessageWriter<'w, NewGameConfirmEvent>,
|
||||
info_toast: MessageWriter<'w, InfoToastEvent>,
|
||||
draw: MessageWriter<'w, DrawRequestEvent>,
|
||||
}
|
||||
|
||||
/// Handles the core keyboard shortcuts: U (undo), N (new game + confirmation
|
||||
/// window), Z (zen mode), D / Space (draw), and ticks down the new-game
|
||||
/// confirmation countdown each frame.
|
||||
/// Handles the core keyboard shortcuts: U (undo), N (new game), Z (zen mode),
|
||||
/// D / Space (draw).
|
||||
///
|
||||
/// `N` fires `NewGameRequestEvent` straight through; the existing
|
||||
/// `handle_new_game` flow shows the `ConfirmNewGameScreen` modal when
|
||||
/// the current game is in progress, so a single press surfaces a real
|
||||
/// Confirm / Cancel UI instead of a "press N again" toast. `Shift+N`
|
||||
/// keeps the keyboard power-user bypass by setting `confirmed: true`.
|
||||
///
|
||||
/// While the confirm modal or the restore prompt is already open, the
|
||||
/// system skips the N branch so those modals' own input handlers can
|
||||
/// process N (cancel / start-new-game) without us re-firing a request
|
||||
/// the same frame.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_keyboard_core(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
paused: Option<Res<PausedResource>>,
|
||||
progress: Option<Res<ProgressResource>>,
|
||||
game: Option<Res<GameStateResource>>,
|
||||
time: Res<Time>,
|
||||
mut confirm: ResMut<KeyboardConfirmState>,
|
||||
mut ev: CoreKeyboardMessages<'_>,
|
||||
mut time_attack: Option<ResMut<TimeAttackResource>>,
|
||||
selection: Option<Res<SelectionState>>,
|
||||
mut zen_requests: MessageReader<StartZenRequestEvent>,
|
||||
confirm_screens: Query<(), With<ConfirmNewGameScreen>>,
|
||||
restore_prompts: Query<(), With<RestorePromptScreen>>,
|
||||
) {
|
||||
if paused.is_some_and(|p| p.0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Tick down the new-game confirmation window each frame.
|
||||
if confirm.new_game_countdown > 0.0 {
|
||||
confirm.new_game_countdown -= time.delta_secs();
|
||||
if confirm.new_game_countdown <= 0.0 {
|
||||
confirm.new_game_countdown = 0.0;
|
||||
if confirm.new_game_pending {
|
||||
confirm.new_game_pending = false;
|
||||
ev.info_toast.write(InfoToastEvent("New game cancelled".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if keys.just_pressed(KeyCode::KeyU) {
|
||||
ev.undo.write(UndoRequestEvent);
|
||||
}
|
||||
@@ -194,27 +181,24 @@ fn handle_keyboard_core(
|
||||
mode: Some(solitaire_core::game_state::GameMode::Classic),
|
||||
confirmed: false,
|
||||
});
|
||||
confirm.new_game_countdown = 0.0;
|
||||
return;
|
||||
}
|
||||
|
||||
let active_game = game.as_ref().is_some_and(|g| g.0.move_count > 0 && !g.0.is_won);
|
||||
let shift_held = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight);
|
||||
if shift_held || !active_game {
|
||||
// Shift+N or no active game — start immediately, no confirmation.
|
||||
ev.new_game.write(NewGameRequestEvent::default());
|
||||
confirm.new_game_countdown = 0.0;
|
||||
confirm.new_game_pending = false;
|
||||
} else if confirm.new_game_countdown > 0.0 {
|
||||
// Second press within the window — confirmed.
|
||||
ev.new_game.write(NewGameRequestEvent::default());
|
||||
confirm.new_game_countdown = 0.0;
|
||||
confirm.new_game_pending = false;
|
||||
// The confirm modal and restore prompt own N while they're up —
|
||||
// they cancel / accept respectively. Skipping here prevents us
|
||||
// from firing a fresh request the same frame those modals close.
|
||||
if !confirm_screens.is_empty() || !restore_prompts.is_empty() {
|
||||
// intentional: defer to those modals' input handlers.
|
||||
} else {
|
||||
// First press on an active game — require confirmation.
|
||||
confirm.new_game_countdown = NEW_GAME_CONFIRM_WINDOW;
|
||||
confirm.new_game_pending = true;
|
||||
ev.confirm_event.write(NewGameConfirmEvent);
|
||||
let shift_held = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight);
|
||||
ev.new_game.write(NewGameRequestEvent {
|
||||
seed: None,
|
||||
mode: None,
|
||||
// Shift+N skips the confirm modal for keyboard power-users;
|
||||
// bare N falls through `handle_new_game`'s active-game check
|
||||
// and shows the modal when a game is in progress.
|
||||
confirmed: shift_held,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,36 +231,29 @@ fn handle_keyboard_core(
|
||||
// Esc is handled by `PausePlugin` (overlay toggle + paused flag).
|
||||
}
|
||||
|
||||
/// Handles the H key: surface the solver's provably-best first move when
|
||||
/// the position is winnable; otherwise fall back to cycling through the
|
||||
/// heuristic hints.
|
||||
/// Handles the H key: spawn an async solver task on
|
||||
/// `AsyncComputeTaskPool` whose result `pending_hint::poll_pending_hint_task`
|
||||
/// turns into hint visuals one frame later.
|
||||
///
|
||||
/// The solver (`solitaire_core::solver::try_solve_from_state`) is run
|
||||
/// synchronously on each H press — median ~2 ms on real positions, with a
|
||||
/// hard cap from `SolverConfig::default()`'s budgets. When the verdict is
|
||||
/// `Winnable`, the returned `first_move` is shown as a single, stable hint
|
||||
/// (no cycling — the optimal move doesn't change between identical
|
||||
/// presses). When the verdict is `Unwinnable` or `Inconclusive`, the
|
||||
/// handler falls back to the legacy heuristic in `all_hints`, which still
|
||||
/// cycles through every legal move.
|
||||
/// Median solve time is ~2 ms but pathological positions can hit the
|
||||
/// `SolverConfig::default()` cap at ~120 ms; running synchronously
|
||||
/// (the v0.17.0 behaviour) blocked the main thread on the same frame
|
||||
/// the player pressed H. Cancel-on-replace lives in
|
||||
/// `PendingHintTask::spawn` — a fresh H press while a previous task
|
||||
/// is in flight drops the previous task's handle.
|
||||
///
|
||||
/// When no moves are available a "No hints available" toast is shown
|
||||
/// instead. The H key always produces a hint when any legal move exists.
|
||||
///
|
||||
/// TODO: if profiling ever shows >100 ms solver calls in practice, move
|
||||
/// the solver call to `AsyncComputeTaskPool` to keep input latency low.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Special-cases: when the game is already won, surface a "Game won!"
|
||||
/// toast instead of asking the solver. The poll system handles the
|
||||
/// "no legal moves" toast on the heuristic fallback path so the
|
||||
/// handler here only needs to dispatch.
|
||||
fn handle_keyboard_hint(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
paused: Option<Res<PausedResource>>,
|
||||
game: Option<Res<GameStateResource>>,
|
||||
layout: Option<Res<LayoutResource>>,
|
||||
solver_config: Res<HintSolverConfig>,
|
||||
mut hint_cycle: ResMut<HintCycleIndex>,
|
||||
mut commands: Commands,
|
||||
card_entities: Query<(Entity, &CardEntity, &mut Sprite)>,
|
||||
mut pending_hint: ResMut<crate::pending_hint::PendingHintTask>,
|
||||
mut info_toast: MessageWriter<InfoToastEvent>,
|
||||
mut hint_visual: MessageWriter<HintVisualEvent>,
|
||||
) {
|
||||
if paused.is_some_and(|p| p.0) {
|
||||
return;
|
||||
@@ -294,43 +271,37 @@ fn handle_keyboard_hint(
|
||||
|
||||
let Some(_layout_res) = layout else { return };
|
||||
|
||||
// First pass: ask the solver for the provably-best move. The
|
||||
// solver is deterministic, so repeated H presses on the same
|
||||
// position keep showing the same hint (cycling is reserved for
|
||||
// the heuristic fallback path).
|
||||
use solitaire_core::solver::{try_solve_from_state, SolverResult};
|
||||
let outcome = try_solve_from_state(&g.0, &solver_config.0);
|
||||
if outcome.result == SolverResult::Winnable
|
||||
&& let Some(mv) = outcome.first_move
|
||||
{
|
||||
let from = mv.source.clone();
|
||||
let to = mv.dest.clone();
|
||||
emit_hint_visuals(&g.0, &from, &to, &mut commands, card_entities, &mut info_toast, &mut hint_visual);
|
||||
return;
|
||||
}
|
||||
pending_hint.spawn(g.0.clone(), solver_config.0);
|
||||
}
|
||||
|
||||
// Fallback: heuristic cycling hint. Used when the solver verdict
|
||||
// is `Unwinnable` (no legal winning path — but a legal *move* may
|
||||
// still exist, e.g. drawing from stock) or `Inconclusive` (budget
|
||||
// exhausted on a complex mid-game position).
|
||||
let hints = all_hints(&g.0);
|
||||
/// Heuristic hint helper used by `pending_hint::poll_pending_hint_task`
|
||||
/// when the solver returns `Inconclusive` or `Unwinnable`.
|
||||
///
|
||||
/// Picks the hint at `HintCycleIndex % hints.len()` (wrapping) and
|
||||
/// advances the index so successive H presses on a stuck position
|
||||
/// cycle through every legal move. Returns `None` when no legal move
|
||||
/// exists at all — the caller surfaces a "No hints available" toast.
|
||||
pub fn find_heuristic_hint(
|
||||
game: &GameState,
|
||||
hint_cycle: &mut HintCycleIndex,
|
||||
) -> Option<(PileType, PileType)> {
|
||||
let hints = all_hints(game);
|
||||
if hints.is_empty() {
|
||||
info_toast.write(InfoToastEvent("No hints available".to_string()));
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
|
||||
// Pick the hint at the current cycle index (wrapping) and advance.
|
||||
let idx = hint_cycle.0 % hints.len();
|
||||
hint_cycle.0 = hint_cycle.0.wrapping_add(1);
|
||||
let (from, to, _count) = hints[idx].clone();
|
||||
emit_hint_visuals(&g.0, &from, &to, &mut commands, card_entities, &mut info_toast, &mut hint_visual);
|
||||
Some((from, to))
|
||||
}
|
||||
|
||||
/// Apply the visual + toast effects for a single chosen hint move.
|
||||
///
|
||||
/// Shared between the solver-driven and heuristic-driven hint paths so
|
||||
/// both produce identical player-facing feedback.
|
||||
fn emit_hint_visuals(
|
||||
/// both produce identical player-facing feedback. Called from
|
||||
/// `pending_hint::poll_pending_hint_task` once the async solver task
|
||||
/// resolves.
|
||||
pub fn emit_hint_visuals(
|
||||
game: &GameState,
|
||||
from: &PileType,
|
||||
to: &PileType,
|
||||
@@ -673,10 +644,23 @@ fn end_drag(
|
||||
}
|
||||
|
||||
// If the drag was never committed (user tapped without moving far enough),
|
||||
// treat it as a click: just cancel the pending drag and resync card positions.
|
||||
// treat it as a click: cancel the pending drag and exit. We deliberately
|
||||
// do NOT fire `StateChangedEvent` here — `start_drag` only mutates the
|
||||
// `DragState` resource on press, never card transforms, so an uncommitted
|
||||
// drag has no visual side effect to undo.
|
||||
//
|
||||
// Firing one would race a CardAnim that's already in flight on the same
|
||||
// card. Specifically: on a successful double-click, `handle_double_click`
|
||||
// fires `MoveRequestEvent`, `start_drag` picks the card up the same
|
||||
// frame (uncommitted), and `handle_move` queues a `StateChangedEvent` →
|
||||
// `sync_cards_on_change` starts a slide animation. When the player
|
||||
// releases the button mid-slide, `end_drag` would fire a second
|
||||
// `StateChangedEvent`, `sync_cards_on_change` would see the card mid-
|
||||
// animation (`cur != target`), and replace the in-flight CardAnim with
|
||||
// a fresh one — restarting the slide and reading on screen as the move
|
||||
// animation playing twice.
|
||||
if !drag.committed {
|
||||
drag.clear();
|
||||
changed.write(StateChangedEvent);
|
||||
return;
|
||||
}
|
||||
let Some(layout) = layout else {
|
||||
@@ -1339,32 +1323,37 @@ fn handle_double_click(
|
||||
// Priority 2: if the player clicked the base of a multi-card face-up
|
||||
// stack (card_ids.len() > 1), try moving the whole stack to another
|
||||
// tableau column.
|
||||
if card_ids.len() > 1 {
|
||||
let Some(bottom_card) = game.0.piles.get(&pile)
|
||||
.and_then(|p| p.cards.get(stack_index)) else { return };
|
||||
if let Some((dest, count)) = best_tableau_destination_for_stack(
|
||||
if card_ids.len() > 1
|
||||
&& let Some(bottom_card) = game.0.piles.get(&pile)
|
||||
.and_then(|p| p.cards.get(stack_index))
|
||||
&& let Some((dest, count)) = best_tableau_destination_for_stack(
|
||||
bottom_card,
|
||||
&pile,
|
||||
&game.0,
|
||||
card_ids.len(),
|
||||
) {
|
||||
)
|
||||
{
|
||||
moves.write(MoveRequestEvent {
|
||||
from: pile,
|
||||
to: dest,
|
||||
count,
|
||||
});
|
||||
} else {
|
||||
// No legal destination for the stack — play the invalid-move
|
||||
// sound and shake the source pile cards as feedback.
|
||||
// `MoveRejectedEvent` with `from == to` routes the shake to
|
||||
// the source pile (which `start_shake_anim` reads from `ev.to`).
|
||||
return;
|
||||
}
|
||||
|
||||
// Both priorities failed — play the invalid-move sound and shake
|
||||
// the source pile as feedback. `MoveRejectedEvent` with
|
||||
// `from == to` routes the shake to the source pile (which
|
||||
// `start_shake_anim` reads from `ev.to`). Pre-fix, this branch
|
||||
// only fired for multi-card stacks, so a double-click on a
|
||||
// single card with no legal destination did nothing — no
|
||||
// sound, no shake. Now both single-card and stack misses get
|
||||
// the same feedback.
|
||||
rejected.write(MoveRejectedEvent {
|
||||
from: pile.clone(),
|
||||
to: pile,
|
||||
count: card_ids.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single click — record the time.
|
||||
last_click.insert(top_card_id, now);
|
||||
@@ -2019,15 +2008,6 @@ mod tests {
|
||||
assert!(hints.is_empty(), "no hint should exist when the game is truly stuck");
|
||||
}
|
||||
|
||||
/// Const-assert that `NEW_GAME_CONFIRM_WINDOW` is positive so the
|
||||
/// confirmation countdown actually opens on the first N press.
|
||||
///
|
||||
/// Mirrors the existing `forfeit_confirm_window_is_positive` test.
|
||||
#[test]
|
||||
fn new_game_confirm_window_is_positive() {
|
||||
const { assert!(NEW_GAME_CONFIRM_WINDOW > 0.0, "NEW_GAME_CONFIRM_WINDOW must be > 0"); }
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Drag-rejection return tween — `CardAnimation` replaces the legacy
|
||||
// `ShakeAnim` on the dragged cards. The audio cue
|
||||
@@ -2186,191 +2166,50 @@ mod tests {
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Hint system — solver promotion (v0.16.0+)
|
||||
// Hint system — async port (v0.18.0+)
|
||||
//
|
||||
// The H-key hint is now backed by `solitaire_core::solver::try_solve_from_state`.
|
||||
// When the solver proves the position winnable, the hint is the
|
||||
// first move on the solver's solution path. When the solver returns
|
||||
// Inconclusive (budget exhausted) or Unwinnable, the legacy
|
||||
// heuristic in `all_hints` supplies the hint instead so the H key
|
||||
// always produces feedback while any legal move exists.
|
||||
// `handle_keyboard_hint` no longer runs the solver inline; it
|
||||
// spawns an `AsyncComputeTaskPool` task whose result the polling
|
||||
// system in `pending_hint` turns into hint visuals one frame
|
||||
// later. The behaviour contract this section pins is "pressing H
|
||||
// populates `PendingHintTask`" — the spawn-to-emit pipeline is
|
||||
// covered end-to-end in `pending_hint::tests`.
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/// Build a minimal Bevy app that registers only the resources and
|
||||
/// messages needed to drive `handle_keyboard_hint` end-to-end.
|
||||
/// Skips every other input system — the test only exercises the hint
|
||||
/// path and we want the assertions to be unaffected by other handlers.
|
||||
fn hint_test_app() -> App {
|
||||
/// Pressing H on a non-paused, non-won game with a live
|
||||
/// `GameStateResource` + `LayoutResource` must populate
|
||||
/// `PendingHintTask`. The polling system, exercised in
|
||||
/// `pending_hint::tests`, drives the result to a visual event.
|
||||
#[test]
|
||||
fn pressing_h_spawns_pending_hint_task() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins);
|
||||
app.add_message::<InfoToastEvent>();
|
||||
app.add_message::<HintVisualEvent>();
|
||||
app.init_resource::<HintCycleIndex>();
|
||||
app.init_resource::<HintSolverConfig>();
|
||||
app.init_resource::<crate::pending_hint::PendingHintTask>();
|
||||
app.init_resource::<ButtonInput<KeyCode>>();
|
||||
// Layout: a fixed 1280x800 layout — `handle_keyboard_hint` only
|
||||
// checks the resource is present, never reads coordinates.
|
||||
app.insert_resource(crate::layout::LayoutResource(
|
||||
crate::layout::compute_layout(Vec2::new(1280.0, 800.0)),
|
||||
));
|
||||
app.insert_resource(GameStateResource(GameState::new(42, DrawMode::DrawOne)));
|
||||
app.add_systems(Update, handle_keyboard_hint);
|
||||
app
|
||||
}
|
||||
|
||||
/// Helper: simulate "the player just pressed H this frame".
|
||||
fn press_h(app: &mut App) {
|
||||
// Simulate the H key being pressed this frame.
|
||||
{
|
||||
let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
|
||||
input.release(KeyCode::KeyH);
|
||||
input.clear();
|
||||
input.press(KeyCode::KeyH);
|
||||
}
|
||||
|
||||
/// Build a near-finished `GameState`: foundations hold A..Q for each
|
||||
/// suit, four Kings sit on tableau columns 0..3, stock and waste
|
||||
/// empty. Solver-side equivalent of the `near_finished_game_state`
|
||||
/// helper in `solitaire_core::solver::tests`.
|
||||
fn near_finished_game_state() -> GameState {
|
||||
use solitaire_core::card::{Card, Rank, Suit};
|
||||
let mut game = GameState::new(1, DrawMode::DrawOne);
|
||||
for slot in 0..4_u8 {
|
||||
game.piles
|
||||
.get_mut(&PileType::Foundation(slot))
|
||||
.unwrap()
|
||||
.cards
|
||||
.clear();
|
||||
}
|
||||
for i in 0..7_usize {
|
||||
game.piles
|
||||
.get_mut(&PileType::Tableau(i))
|
||||
.unwrap()
|
||||
.cards
|
||||
.clear();
|
||||
}
|
||||
game.piles.get_mut(&PileType::Stock).unwrap().cards.clear();
|
||||
game.piles.get_mut(&PileType::Waste).unwrap().cards.clear();
|
||||
let suit_for_slot = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
let ranks_below_king = [
|
||||
Rank::Ace, Rank::Two, Rank::Three, Rank::Four, Rank::Five,
|
||||
Rank::Six, Rank::Seven, Rank::Eight, Rank::Nine, Rank::Ten,
|
||||
Rank::Jack, Rank::Queen,
|
||||
];
|
||||
for (slot, suit) in suit_for_slot.iter().enumerate() {
|
||||
let pile = game
|
||||
.piles
|
||||
.get_mut(&PileType::Foundation(slot as u8))
|
||||
.unwrap();
|
||||
for (i, rank) in ranks_below_king.iter().enumerate() {
|
||||
pile.cards.push(Card {
|
||||
id: (slot as u32) * 13 + i as u32,
|
||||
suit: *suit,
|
||||
rank: *rank,
|
||||
face_up: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (col, suit) in suit_for_slot.iter().enumerate() {
|
||||
game.piles
|
||||
.get_mut(&PileType::Tableau(col))
|
||||
.unwrap()
|
||||
.cards
|
||||
.push(Card {
|
||||
id: 100 + col as u32,
|
||||
suit: *suit,
|
||||
rank: Rank::King,
|
||||
face_up: true,
|
||||
});
|
||||
}
|
||||
game
|
||||
}
|
||||
|
||||
/// When the solver verdict is Winnable, the hint must come from the
|
||||
/// solver: in our near-finished fixture, four Tableau→Foundation
|
||||
/// moves are legal and the solver returns one of them. The
|
||||
/// `HintVisualEvent` source card must be one of the four Kings and
|
||||
/// the destination must be a foundation slot.
|
||||
#[test]
|
||||
fn hint_uses_solver_when_winnable() {
|
||||
use solitaire_core::card::Rank;
|
||||
let mut app = hint_test_app();
|
||||
let game = near_finished_game_state();
|
||||
// Track the 4 King ids so we can assert the hint source matches.
|
||||
let king_ids: Vec<u32> = (0..4_u8)
|
||||
.map(|c| {
|
||||
game.piles
|
||||
.get(&PileType::Tableau(c as usize))
|
||||
.unwrap()
|
||||
.cards
|
||||
.last()
|
||||
.filter(|c| c.rank == Rank::King)
|
||||
.map(|c| c.id)
|
||||
.expect("each tableau col 0..3 has a King on top")
|
||||
})
|
||||
.collect();
|
||||
|
||||
app.insert_resource(GameStateResource(game));
|
||||
press_h(&mut app);
|
||||
app.update();
|
||||
|
||||
// Read out the messages via the standard cursor API.
|
||||
let messages = app.world().resource::<Messages<HintVisualEvent>>();
|
||||
let mut cursor = messages.get_cursor();
|
||||
let collected: Vec<HintVisualEvent> = cursor.read(messages).cloned().collect();
|
||||
assert_eq!(
|
||||
collected.len(), 1,
|
||||
"exactly one HintVisualEvent must fire on a winnable solver verdict"
|
||||
);
|
||||
let event = &collected[0];
|
||||
assert!(
|
||||
king_ids.contains(&event.source_card_id),
|
||||
"solver hint must point at one of the four Kings; got id {}",
|
||||
event.source_card_id
|
||||
);
|
||||
assert!(
|
||||
matches!(event.dest_pile, PileType::Foundation(_)),
|
||||
"solver hint destination must be a foundation slot; got {:?}",
|
||||
event.dest_pile
|
||||
);
|
||||
}
|
||||
|
||||
/// When the solver returns Inconclusive (e.g. tight budgets force an
|
||||
/// early bail), the heuristic fallback must still produce a hint
|
||||
/// event so the H key never feels broken.
|
||||
///
|
||||
/// We force the solver inconclusive by setting both budgets to 0 —
|
||||
/// the search bails on the very first iteration, returning
|
||||
/// `SolverResult::Inconclusive`. The heuristic fallback then runs on
|
||||
/// the fresh deal and finds at least one legal move.
|
||||
#[test]
|
||||
fn hint_falls_back_to_heuristic_when_solver_inconclusive() {
|
||||
use solitaire_core::solver::SolverConfig;
|
||||
let mut app = hint_test_app();
|
||||
// Force solver to bail before exploring anything.
|
||||
app.insert_resource(HintSolverConfig(SolverConfig {
|
||||
move_budget: 0,
|
||||
state_budget: 0,
|
||||
}));
|
||||
// A fresh seeded deal — guaranteed to have at least one legal
|
||||
// move (the standard Klondike opening always has draws available
|
||||
// even if no immediate tableau move exists).
|
||||
let game = GameState::new(42, DrawMode::DrawOne);
|
||||
app.insert_resource(GameStateResource(game));
|
||||
press_h(&mut app);
|
||||
app.update();
|
||||
|
||||
let world = app.world();
|
||||
let visuals = world.resource::<Messages<HintVisualEvent>>();
|
||||
let mut visual_cursor = visuals.get_cursor();
|
||||
let collected: Vec<HintVisualEvent> = visual_cursor.read(visuals).cloned().collect();
|
||||
// Either a card-move hint (most fresh deals) or a draw suggestion.
|
||||
// A draw suggestion fires no `HintVisualEvent` (only an
|
||||
// `InfoToastEvent`), so we accept zero-or-one HintVisualEvent so
|
||||
// long as at least one feedback signal was emitted overall.
|
||||
let toasts = world.resource::<Messages<InfoToastEvent>>();
|
||||
let mut toast_cursor = toasts.get_cursor();
|
||||
let toast_count = toast_cursor.read(toasts).count();
|
||||
assert!(
|
||||
!collected.is_empty() || toast_count > 0,
|
||||
"heuristic fallback must produce a hint signal (visual or toast)"
|
||||
app.world()
|
||||
.resource::<crate::pending_hint::PendingHintTask>()
|
||||
.is_pending(),
|
||||
"pressing H must spawn an async hint task",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,7 +501,12 @@ fn spawn_leaderboard_screen(
|
||||
}
|
||||
LeaderboardResource::Loaded(rows) if rows.is_empty() => {
|
||||
body.spawn((
|
||||
Text::new("No entries yet \u{2014} sync and opt in to appear here."),
|
||||
Text::new("Be the first on the leaderboard."),
|
||||
font_status.clone(),
|
||||
TextColor(TEXT_PRIMARY),
|
||||
));
|
||||
body.spawn((
|
||||
Text::new("Win a game and opt in to appear here."),
|
||||
font_row.clone(),
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
|
||||
@@ -22,6 +22,7 @@ pub mod input_plugin;
|
||||
pub mod layout;
|
||||
pub mod onboarding_plugin;
|
||||
pub mod pause_plugin;
|
||||
pub mod pending_hint;
|
||||
pub mod profile_plugin;
|
||||
pub mod radial_menu;
|
||||
pub mod replay_overlay;
|
||||
@@ -88,7 +89,7 @@ pub use events::{
|
||||
AchievementUnlockedEvent, CardFaceRevealedEvent, CardFlippedEvent, DrawRequestEvent,
|
||||
ForfeitEvent, ForfeitRequestEvent, FoundationCompletedEvent, GameWonEvent, HelpRequestEvent,
|
||||
HintVisualEvent, InfoToastEvent, ManualSyncRequestEvent, MoveRejectedEvent, MoveRequestEvent,
|
||||
NewGameConfirmEvent, NewGameRequestEvent, PauseRequestEvent, StartChallengeRequestEvent,
|
||||
NewGameRequestEvent, PauseRequestEvent, StartChallengeRequestEvent,
|
||||
StartDailyChallengeRequestEvent, StartTimeAttackRequestEvent, StartZenRequestEvent,
|
||||
StateChangedEvent, SyncCompleteEvent, ToggleAchievementsRequestEvent,
|
||||
ToggleLeaderboardRequestEvent, ToggleProfileRequestEvent, ToggleSettingsRequestEvent,
|
||||
|
||||
@@ -36,8 +36,9 @@ use crate::settings_plugin::{SettingsChangedEvent, SettingsResource, SettingsSto
|
||||
use crate::stats_plugin::StatsResource;
|
||||
use crate::ui_modal::{
|
||||
spawn_modal, spawn_modal_actions, spawn_modal_body_text, spawn_modal_button,
|
||||
spawn_modal_header, ButtonVariant,
|
||||
spawn_modal_header, ButtonVariant, ModalScrim,
|
||||
};
|
||||
use bevy::ecs::system::SystemParam;
|
||||
use crate::ui_theme::{
|
||||
self, TEXT_PRIMARY, TEXT_SECONDARY, TYPE_BODY_LG, TYPE_CAPTION, VAL_SPACE_3,
|
||||
};
|
||||
@@ -126,15 +127,24 @@ impl Plugin for PausePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bundles the modal-related queries `toggle_pause` reads each tick.
|
||||
/// Pulled into a [`SystemParam`] so the system stays under Bevy's 16-
|
||||
/// parameter cap after the cross-modal Esc guard query was added.
|
||||
#[derive(SystemParam)]
|
||||
struct PauseModalQueries<'w, 's> {
|
||||
pause_screens: Query<'w, 's, Entity, With<PauseScreen>>,
|
||||
forfeit_screens: Query<'w, 's, Entity, With<ForfeitConfirmScreen>>,
|
||||
game_over_screens: Query<'w, 's, Entity, With<GameOverScreen>>,
|
||||
other_modal_scrims: Query<'w, 's, Entity, (With<ModalScrim>, Without<PauseScreen>)>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn toggle_pause(
|
||||
mut commands: Commands,
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
mut requests: MessageReader<PauseRequestEvent>,
|
||||
mut paused: ResMut<PausedResource>,
|
||||
screens: Query<Entity, With<PauseScreen>>,
|
||||
forfeit_screens: Query<Entity, With<ForfeitConfirmScreen>>,
|
||||
game_over_screens: Query<Entity, With<GameOverScreen>>,
|
||||
modal_queries: PauseModalQueries<'_, '_>,
|
||||
game: Option<Res<GameStateResource>>,
|
||||
path: Option<Res<GameStatePath>>,
|
||||
progress: Option<Res<ProgressResource>>,
|
||||
@@ -145,6 +155,13 @@ fn toggle_pause(
|
||||
mut changed: MessageWriter<StateChangedEvent>,
|
||||
selection: Option<Res<SelectionState>>,
|
||||
) {
|
||||
let PauseModalQueries {
|
||||
pause_screens: screens,
|
||||
forfeit_screens,
|
||||
game_over_screens,
|
||||
other_modal_scrims,
|
||||
} = modal_queries;
|
||||
|
||||
// Either Esc or a click on the HUD "Pause" button (which fires
|
||||
// PauseRequestEvent) opens or closes the overlay. Drain the queue so a
|
||||
// burst of clicks doesn't queue future toggles.
|
||||
@@ -157,6 +174,16 @@ fn toggle_pause(
|
||||
if !forfeit_screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Any other modal (Confirm New Game, Restore, Home, Onboarding,
|
||||
// Settings, etc.) owns its own dismissal — pause must not stack
|
||||
// on top of it. Without this guard a single Esc both closes the
|
||||
// open modal AND spawns the pause overlay underneath, leaving the
|
||||
// player on a screen they didn't ask for. The HUD-button path
|
||||
// (`button_clicked`) is gated too; clicking Pause while another
|
||||
// modal is up is almost always an accident.
|
||||
if !other_modal_scrims.is_empty() {
|
||||
return;
|
||||
}
|
||||
// If a card is currently selected, let SelectionPlugin handle this Escape
|
||||
// (it will clear the selection). Pause must not also open in the same frame.
|
||||
if selection.is_some_and(|s| s.selected_pile.is_some()) {
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Async H-key hint solver, modelled on `PendingNewGameSeed` in
|
||||
//! `game_plugin`.
|
||||
//!
|
||||
//! The synchronous version (v0.17.0) called
|
||||
//! `solitaire_core::solver::try_solve_from_state` on the main thread on
|
||||
//! every H press. Median latency was ~2 ms but pathological positions
|
||||
//! can hit the `SolverConfig::default()` cap at ~120 ms, which is a
|
||||
//! noticeable input-stall on the same frame the player sees the hint
|
||||
//! request.
|
||||
//!
|
||||
//! This module hosts the resource and polling system that move the
|
||||
//! solver call onto `AsyncComputeTaskPool`. `handle_keyboard_hint`
|
||||
//! (input_plugin) becomes a thin spawn point: snapshot the state,
|
||||
//! spawn the task, store the handle. The polling system takes the
|
||||
//! result one frame later and surfaces the hint visuals via the
|
||||
//! shared `emit_hint_visuals` helper.
|
||||
//!
|
||||
//! Cancel-on-replace: a fresh H press while a previous task is in
|
||||
//! flight drops the previous task. Bevy's `Task` `Drop` cancels
|
||||
//! cooperatively at the next await point.
|
||||
//!
|
||||
//! Stale-state drop: any `StateChangedEvent` (move applied, undo,
|
||||
//! new game) drops the in-flight task — the position the solver was
|
||||
//! reasoning about no longer exists, and surfacing a hint for the
|
||||
//! old state would be confusing.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::tasks::{futures_lite::future, AsyncComputeTaskPool, Task};
|
||||
use solitaire_core::game_state::GameState;
|
||||
use solitaire_core::pile::PileType;
|
||||
use solitaire_core::solver::{try_solve_from_state, SolverConfig, SolverResult};
|
||||
|
||||
use crate::card_plugin::CardEntity;
|
||||
use crate::events::{HintVisualEvent, InfoToastEvent, StateChangedEvent};
|
||||
use crate::input_plugin::{emit_hint_visuals, find_heuristic_hint};
|
||||
use crate::resources::{GameStateResource, HintCycleIndex};
|
||||
|
||||
/// In-flight async work for the H-key hint.
|
||||
///
|
||||
/// `handle_keyboard_hint` writes here when the player presses H;
|
||||
/// `poll_pending_hint_task` reads from here, polls the task, and
|
||||
/// emits the hint visuals once the task completes. At most one task
|
||||
/// is ever in flight: a fresh H press while a previous task is
|
||||
/// running drops the previous task and queues the new one.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct PendingHintTask {
|
||||
/// `Some` while the solver is still working on a verdict.
|
||||
inner: Option<HintTask>,
|
||||
}
|
||||
|
||||
impl PendingHintTask {
|
||||
/// Whether a hint task is currently in flight.
|
||||
pub fn is_pending(&self) -> bool {
|
||||
self.inner.is_some()
|
||||
}
|
||||
|
||||
/// Drop any in-flight task. Bevy's `Task` `Drop` cancels the
|
||||
/// underlying future cooperatively at the next await point.
|
||||
pub fn cancel(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
/// Spawn a new solver task for `state` with `config`. Drops any
|
||||
/// previously in-flight task first (cancel-on-replace).
|
||||
pub fn spawn(&mut self, state: GameState, config: SolverConfig) {
|
||||
let move_count_at_spawn = state.move_count;
|
||||
let handle = AsyncComputeTaskPool::get().spawn(async move {
|
||||
let outcome = try_solve_from_state(&state, &config);
|
||||
match outcome.result {
|
||||
SolverResult::Winnable => outcome
|
||||
.first_move
|
||||
.map(|mv| HintTaskOutput::SolverMove {
|
||||
from: mv.source,
|
||||
to: mv.dest,
|
||||
})
|
||||
.unwrap_or(HintTaskOutput::NeedsHeuristic),
|
||||
SolverResult::Unwinnable | SolverResult::Inconclusive => {
|
||||
HintTaskOutput::NeedsHeuristic
|
||||
}
|
||||
}
|
||||
});
|
||||
self.inner = Some(HintTask {
|
||||
handle,
|
||||
move_count_at_spawn,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One in-flight hint search plus the snapshot data needed to detect
|
||||
/// a stale result if the live state moved while the solver ran.
|
||||
struct HintTask {
|
||||
handle: Task<HintTaskOutput>,
|
||||
/// `GameState.move_count` at spawn time. The poll system discards
|
||||
/// the result if the live move_count has advanced — the player
|
||||
/// applied a move while the solver ran, so the hint would be
|
||||
/// stale even if the StateChangedEvent drop didn't fire first.
|
||||
move_count_at_spawn: u32,
|
||||
}
|
||||
|
||||
/// What the solver task carries back to the main thread.
|
||||
enum HintTaskOutput {
|
||||
/// Solver verdict was `Winnable`; here is the first move on the
|
||||
/// solution path.
|
||||
SolverMove {
|
||||
from: PileType,
|
||||
to: PileType,
|
||||
},
|
||||
/// Solver was `Unwinnable` or `Inconclusive`. The poll system
|
||||
/// runs the legacy heuristic against the live `GameState` so the
|
||||
/// H key always produces feedback while any legal move exists.
|
||||
NeedsHeuristic,
|
||||
}
|
||||
|
||||
/// Drop the in-flight hint task whenever the live `GameState` shifts.
|
||||
///
|
||||
/// The position the solver was reasoning about no longer matches the
|
||||
/// live state, so its result would be stale. Mirrors the semantics
|
||||
/// of `reset_hint_cycle_on_state_change` for `HintCycleIndex`.
|
||||
pub fn drop_pending_hint_on_state_change(
|
||||
mut state_events: MessageReader<StateChangedEvent>,
|
||||
mut pending: ResMut<PendingHintTask>,
|
||||
) {
|
||||
if state_events.read().next().is_some() {
|
||||
pending.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll the in-flight hint solver task. When the task resolves, run
|
||||
/// `emit_hint_visuals` on the result — either the solver's
|
||||
/// provably-best first move (Winnable verdict) or a heuristic hint
|
||||
/// over the live state (Unwinnable / Inconclusive).
|
||||
///
|
||||
/// Discards the result when `GameState.move_count` has moved past the
|
||||
/// snapshot taken at spawn time — the player applied a move during
|
||||
/// the solve and `drop_pending_hint_on_state_change` should have
|
||||
/// already cleared the resource, but we double-check here for the
|
||||
/// rare case where the solver task completed in the same frame the
|
||||
/// move was applied.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn poll_pending_hint_task(
|
||||
mut pending: ResMut<PendingHintTask>,
|
||||
game: Option<Res<GameStateResource>>,
|
||||
mut hint_cycle: ResMut<HintCycleIndex>,
|
||||
mut commands: Commands,
|
||||
card_entities: Query<(Entity, &CardEntity, &mut Sprite)>,
|
||||
mut info_toast: MessageWriter<InfoToastEvent>,
|
||||
mut hint_visual: MessageWriter<HintVisualEvent>,
|
||||
) {
|
||||
let Some(p) = pending.inner.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(output) = future::block_on(future::poll_once(&mut p.handle)) else {
|
||||
return;
|
||||
};
|
||||
let move_count_at_spawn = p.move_count_at_spawn;
|
||||
pending.inner = None;
|
||||
|
||||
let Some(g) = game else { return };
|
||||
if g.0.move_count != move_count_at_spawn {
|
||||
return;
|
||||
}
|
||||
|
||||
let (from, to) = match output {
|
||||
HintTaskOutput::SolverMove { from, to } => (from, to),
|
||||
HintTaskOutput::NeedsHeuristic => {
|
||||
match find_heuristic_hint(&g.0, &mut hint_cycle) {
|
||||
Some(pair) => pair,
|
||||
None => {
|
||||
info_toast.write(InfoToastEvent("No hints available".to_string()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
emit_hint_visuals(
|
||||
&g.0,
|
||||
&from,
|
||||
&to,
|
||||
&mut commands,
|
||||
card_entities,
|
||||
&mut info_toast,
|
||||
&mut hint_visual,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::events::HintVisualEvent;
|
||||
use crate::input_plugin::HintSolverConfig;
|
||||
use solitaire_core::card::{Card, Rank, Suit};
|
||||
use solitaire_core::game_state::{DrawMode, GameState};
|
||||
|
||||
/// Build a minimal Bevy app exercising only the polling system
|
||||
/// and the resources/messages it touches.
|
||||
fn pending_hint_app() -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(MinimalPlugins);
|
||||
app.add_message::<InfoToastEvent>();
|
||||
app.add_message::<HintVisualEvent>();
|
||||
app.add_message::<StateChangedEvent>();
|
||||
app.init_resource::<HintCycleIndex>();
|
||||
app.init_resource::<HintSolverConfig>();
|
||||
app.init_resource::<PendingHintTask>();
|
||||
// Chain the drop-on-state-change system before the poll
|
||||
// system, mirroring how `InputPlugin::build` wires them.
|
||||
// Without this, system order is unspecified and the
|
||||
// state_change_drops_in_flight_task test sometimes sees the
|
||||
// poll fire before the drop.
|
||||
app.add_systems(
|
||||
Update,
|
||||
(
|
||||
drop_pending_hint_on_state_change,
|
||||
poll_pending_hint_task,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
app
|
||||
}
|
||||
|
||||
/// Same near-finished fixture used by the v0.17 hint tests:
|
||||
/// foundations hold A..Q for each suit, four Kings sit on
|
||||
/// tableau columns 0..3, stock and waste empty.
|
||||
fn near_finished_state() -> GameState {
|
||||
let mut game = GameState::new(1, DrawMode::DrawOne);
|
||||
for slot in 0..4_u8 {
|
||||
game.piles
|
||||
.get_mut(&PileType::Foundation(slot))
|
||||
.unwrap()
|
||||
.cards
|
||||
.clear();
|
||||
}
|
||||
for i in 0..7_usize {
|
||||
game.piles
|
||||
.get_mut(&PileType::Tableau(i))
|
||||
.unwrap()
|
||||
.cards
|
||||
.clear();
|
||||
}
|
||||
game.piles.get_mut(&PileType::Stock).unwrap().cards.clear();
|
||||
game.piles.get_mut(&PileType::Waste).unwrap().cards.clear();
|
||||
let suits = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades];
|
||||
let ranks_below_king = [
|
||||
Rank::Ace, Rank::Two, Rank::Three, Rank::Four, Rank::Five,
|
||||
Rank::Six, Rank::Seven, Rank::Eight, Rank::Nine, Rank::Ten,
|
||||
Rank::Jack, Rank::Queen,
|
||||
];
|
||||
for (slot, suit) in suits.iter().enumerate() {
|
||||
let pile = game
|
||||
.piles
|
||||
.get_mut(&PileType::Foundation(slot as u8))
|
||||
.unwrap();
|
||||
for (i, rank) in ranks_below_king.iter().enumerate() {
|
||||
pile.cards.push(Card {
|
||||
id: (slot as u32) * 13 + i as u32,
|
||||
suit: *suit,
|
||||
rank: *rank,
|
||||
face_up: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (col, suit) in suits.iter().enumerate() {
|
||||
game.piles
|
||||
.get_mut(&PileType::Tableau(col))
|
||||
.unwrap()
|
||||
.cards
|
||||
.push(Card {
|
||||
id: 100 + col as u32,
|
||||
suit: *suit,
|
||||
rank: Rank::King,
|
||||
face_up: true,
|
||||
});
|
||||
}
|
||||
game
|
||||
}
|
||||
|
||||
/// Spawning a task and pumping update() until it completes must
|
||||
/// emit a HintVisualEvent. Mirrors the `winnable_seed_search_*`
|
||||
/// pattern in game_plugin tests — drives a wall-clock-bounded
|
||||
/// loop so the shared AsyncComputeTaskPool can schedule the
|
||||
/// future under cargo-test parallelism.
|
||||
#[test]
|
||||
fn winnable_solver_emits_hint_after_async_completes() {
|
||||
let mut app = pending_hint_app();
|
||||
app.insert_resource(GameStateResource(near_finished_state()));
|
||||
let cfg = app.world().resource::<HintSolverConfig>().0;
|
||||
app.world_mut()
|
||||
.resource_mut::<PendingHintTask>()
|
||||
.spawn(near_finished_state(), cfg);
|
||||
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while app.world().resource::<PendingHintTask>().is_pending() {
|
||||
app.update();
|
||||
std::thread::yield_now();
|
||||
if std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!app.world().resource::<PendingHintTask>().is_pending(),
|
||||
"hint task should have completed within 15 s wall-clock",
|
||||
);
|
||||
let messages = app.world().resource::<Messages<HintVisualEvent>>();
|
||||
let mut cursor = messages.get_cursor();
|
||||
let collected: Vec<HintVisualEvent> = cursor.read(messages).cloned().collect();
|
||||
assert_eq!(
|
||||
collected.len(), 1,
|
||||
"exactly one HintVisualEvent must fire when the solver returns Winnable",
|
||||
);
|
||||
assert!(
|
||||
matches!(collected[0].dest_pile, PileType::Foundation(_)),
|
||||
"solver hint destination must be a foundation slot; got {:?}",
|
||||
collected[0].dest_pile,
|
||||
);
|
||||
}
|
||||
|
||||
/// A StateChangedEvent fired while the task is in flight must
|
||||
/// drop the task; the polling system must not emit any visuals
|
||||
/// once the result eventually arrives.
|
||||
#[test]
|
||||
fn state_change_drops_in_flight_task() {
|
||||
let mut app = pending_hint_app();
|
||||
app.insert_resource(GameStateResource(near_finished_state()));
|
||||
let cfg = app.world().resource::<HintSolverConfig>().0;
|
||||
app.world_mut()
|
||||
.resource_mut::<PendingHintTask>()
|
||||
.spawn(near_finished_state(), cfg);
|
||||
assert!(
|
||||
app.world().resource::<PendingHintTask>().is_pending(),
|
||||
"task is in flight after spawn",
|
||||
);
|
||||
|
||||
// Fire a StateChangedEvent before draining the task. The
|
||||
// drop-on-state-change system runs in the same Update tick
|
||||
// and clears the resource.
|
||||
app.world_mut().write_message(StateChangedEvent);
|
||||
app.update();
|
||||
|
||||
assert!(
|
||||
!app.world().resource::<PendingHintTask>().is_pending(),
|
||||
"StateChangedEvent must drop the in-flight hint task",
|
||||
);
|
||||
// No HintVisualEvent should ever have fired.
|
||||
let messages = app.world().resource::<Messages<HintVisualEvent>>();
|
||||
let mut cursor = messages.get_cursor();
|
||||
assert_eq!(
|
||||
cursor.read(messages).count(),
|
||||
0,
|
||||
"dropped hint task must not emit any visuals",
|
||||
);
|
||||
}
|
||||
|
||||
/// Cancel-on-replace: spawning a fresh task while a previous one
|
||||
/// is in flight must drop the previous task. Only the second
|
||||
/// spawn's result is allowed to surface.
|
||||
#[test]
|
||||
fn second_spawn_drops_first_in_flight_task() {
|
||||
let mut app = pending_hint_app();
|
||||
app.insert_resource(GameStateResource(near_finished_state()));
|
||||
let cfg = app.world().resource::<HintSolverConfig>().0;
|
||||
|
||||
// First spawn.
|
||||
app.world_mut()
|
||||
.resource_mut::<PendingHintTask>()
|
||||
.spawn(near_finished_state(), cfg);
|
||||
let first_handle_present = app.world().resource::<PendingHintTask>().is_pending();
|
||||
assert!(first_handle_present);
|
||||
|
||||
// Second spawn. The `spawn` helper drops the prior task
|
||||
// before assigning the new one — at no point are two tasks
|
||||
// in flight.
|
||||
app.world_mut()
|
||||
.resource_mut::<PendingHintTask>()
|
||||
.spawn(near_finished_state(), cfg);
|
||||
// Resource still pending (the second task), but the first
|
||||
// is gone. We can't directly observe the first handle once
|
||||
// it's been overwritten — what we *can* assert is that the
|
||||
// resource still holds a single task, and that task
|
||||
// eventually completes producing exactly one hint visual.
|
||||
assert!(app.world().resource::<PendingHintTask>().is_pending());
|
||||
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while app.world().resource::<PendingHintTask>().is_pending() {
|
||||
app.update();
|
||||
std::thread::yield_now();
|
||||
if std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!app.world().resource::<PendingHintTask>().is_pending(),
|
||||
"second hint task should have completed within 15 s wall-clock",
|
||||
);
|
||||
let messages = app.world().resource::<Messages<HintVisualEvent>>();
|
||||
let mut cursor = messages.get_cursor();
|
||||
let collected: Vec<HintVisualEvent> = cursor.read(messages).cloned().collect();
|
||||
assert_eq!(
|
||||
collected.len(), 1,
|
||||
"cancel-on-replace: only the surviving task's result emits a visual",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,17 @@ fn toggle_profile_screen(
|
||||
screens: Query<Entity, With<ProfileScreen>>,
|
||||
) {
|
||||
let button_clicked = requests.read().count() > 0;
|
||||
if !keys.just_pressed(KeyCode::KeyP) && !button_clicked {
|
||||
let p_pressed = keys.just_pressed(KeyCode::KeyP);
|
||||
let esc_pressed = keys.just_pressed(KeyCode::Escape);
|
||||
let already_open = !screens.is_empty();
|
||||
// P / button toggles open-or-close. Esc only ever closes — when
|
||||
// Profile is layered over Home (clicking the new Home stats chip
|
||||
// opens this on top), Esc must dismiss the *topmost* modal.
|
||||
// Without this branch, Esc fell through to Home's cancel handler
|
||||
// and closed the wrong modal.
|
||||
let want_open = !already_open && (p_pressed || button_clicked);
|
||||
let want_close = already_open && (p_pressed || button_clicked || esc_pressed);
|
||||
if !want_open && !want_close {
|
||||
return;
|
||||
}
|
||||
if let Ok(entity) = screens.single() {
|
||||
|
||||
@@ -22,7 +22,7 @@ use solitaire_data::{
|
||||
TOOLTIP_DELAY_STEP_SECS,
|
||||
};
|
||||
|
||||
use crate::events::{ManualSyncRequestEvent, ToggleSettingsRequestEvent};
|
||||
use crate::events::{InfoToastEvent, ManualSyncRequestEvent, ToggleSettingsRequestEvent};
|
||||
use crate::font_plugin::FontResource;
|
||||
use crate::progress_plugin::ProgressResource;
|
||||
use crate::resources::{SettingsScrollPos, SyncStatus, SyncStatusResource};
|
||||
@@ -296,6 +296,7 @@ impl Plugin for SettingsPlugin {
|
||||
.add_message::<SettingsChangedEvent>()
|
||||
.add_message::<ManualSyncRequestEvent>()
|
||||
.add_message::<ToggleSettingsRequestEvent>()
|
||||
.add_message::<InfoToastEvent>()
|
||||
.add_message::<bevy::input::mouse::MouseWheel>()
|
||||
// `WindowResized` / `WindowMoved` are real Bevy window events
|
||||
// and emitted by the windowing backend under `DefaultPlugins`,
|
||||
@@ -383,6 +384,7 @@ fn handle_volume_keys(
|
||||
mut settings: ResMut<SettingsResource>,
|
||||
path: Res<SettingsStoragePath>,
|
||||
mut changed: MessageWriter<SettingsChangedEvent>,
|
||||
mut toast: MessageWriter<InfoToastEvent>,
|
||||
) {
|
||||
let mut delta = 0.0_f32;
|
||||
if keys.just_pressed(KeyCode::BracketLeft) {
|
||||
@@ -401,6 +403,10 @@ fn handle_volume_keys(
|
||||
}
|
||||
persist(&path, &settings.0);
|
||||
changed.write(SettingsChangedEvent(settings.0.clone()));
|
||||
toast.write(InfoToastEvent(format!(
|
||||
"SFX volume: {}%",
|
||||
(after * 100.0).round() as i32
|
||||
)));
|
||||
}
|
||||
|
||||
/// Opens or closes the Settings panel — `O` keyboard accelerator or
|
||||
@@ -1410,11 +1416,18 @@ fn volume_row<Marker: Component>(
|
||||
) {
|
||||
let label_font = label_text_font(font_res);
|
||||
let value_font = value_text_font(font_res);
|
||||
// Row spans the full body width with a flex-grow spacer between
|
||||
// the left-aligned label and the right-aligned controls cluster.
|
||||
// Without `width: 100%` + the spacer, the label / value / buttons
|
||||
// bunch against the left edge and a varying-length value (e.g.
|
||||
// "0.80" → "1.00") shifts the +/− buttons sideways frame to
|
||||
// frame, visually overlapping with adjacent UI on small windows.
|
||||
parent
|
||||
.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -1423,14 +1436,31 @@ fn volume_row<Marker: Component>(
|
||||
label_font,
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
row.spawn((
|
||||
// Spacer: takes up all remaining horizontal space so the
|
||||
// controls cluster sits flush against the right edge.
|
||||
row.spawn(Node {
|
||||
flex_grow: 1.0,
|
||||
..default()
|
||||
});
|
||||
// Controls cluster — value + decrement + increment held
|
||||
// together so the buttons stay in fixed positions even
|
||||
// as the value text width varies.
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
..default()
|
||||
})
|
||||
.with_children(|cluster| {
|
||||
cluster.spawn((
|
||||
marker,
|
||||
Text::new(format!("{value:.2}")),
|
||||
value_font,
|
||||
TextColor(TEXT_PRIMARY),
|
||||
));
|
||||
icon_button(row, "−", btn_down, tooltip_down, font_res);
|
||||
icon_button(row, "+", btn_up, tooltip_up, font_res);
|
||||
icon_button(cluster, "−", btn_down, tooltip_down, font_res);
|
||||
icon_button(cluster, "+", btn_up, tooltip_up, font_res);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1450,6 +1480,7 @@ fn tooltip_delay_row(
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -1458,27 +1489,39 @@ fn tooltip_delay_row(
|
||||
label_font,
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
row.spawn((
|
||||
row.spawn(Node {
|
||||
flex_grow: 1.0,
|
||||
..default()
|
||||
});
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
..default()
|
||||
})
|
||||
.with_children(|cluster| {
|
||||
cluster.spawn((
|
||||
TooltipDelayText,
|
||||
Text::new(tooltip_delay_label(value_secs)),
|
||||
value_font,
|
||||
TextColor(TEXT_PRIMARY),
|
||||
));
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"−",
|
||||
SettingsButton::TooltipDelayDown,
|
||||
"Shorten the hover delay before tooltips appear.",
|
||||
font_res,
|
||||
);
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"+",
|
||||
SettingsButton::TooltipDelayUp,
|
||||
"Lengthen the hover delay before tooltips appear.",
|
||||
font_res,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// `Time bonus 1.0× [−] [+]` — slider row for the cosmetic
|
||||
@@ -1500,6 +1543,7 @@ fn time_bonus_multiplier_row(
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -1508,27 +1552,39 @@ fn time_bonus_multiplier_row(
|
||||
label_font,
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
row.spawn((
|
||||
row.spawn(Node {
|
||||
flex_grow: 1.0,
|
||||
..default()
|
||||
});
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
..default()
|
||||
})
|
||||
.with_children(|cluster| {
|
||||
cluster.spawn((
|
||||
TimeBonusMultiplierText,
|
||||
Text::new(time_bonus_label(value)),
|
||||
value_font,
|
||||
TextColor(TEXT_PRIMARY),
|
||||
));
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"−",
|
||||
SettingsButton::TimeBonusDown,
|
||||
"Shrink the time-bonus shown in the win modal. Cosmetic only.",
|
||||
font_res,
|
||||
);
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"+",
|
||||
SettingsButton::TimeBonusUp,
|
||||
"Boost the time-bonus shown in the win modal. Cosmetic only.",
|
||||
font_res,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// `Replay speed 0.45 s/move [−] [+]` — slider row for the
|
||||
@@ -1550,6 +1606,7 @@ fn replay_move_interval_row(
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -1558,27 +1615,39 @@ fn replay_move_interval_row(
|
||||
label_font,
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
row.spawn((
|
||||
row.spawn(Node {
|
||||
flex_grow: 1.0,
|
||||
..default()
|
||||
});
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
..default()
|
||||
})
|
||||
.with_children(|cluster| {
|
||||
cluster.spawn((
|
||||
ReplayMoveIntervalText,
|
||||
Text::new(replay_move_interval_label(value_secs)),
|
||||
value_font,
|
||||
TextColor(TEXT_PRIMARY),
|
||||
));
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"−",
|
||||
SettingsButton::ReplayMoveIntervalDown,
|
||||
"Speed up replay playback (shorter per-move interval).",
|
||||
font_res,
|
||||
);
|
||||
icon_button(
|
||||
row,
|
||||
cluster,
|
||||
"+",
|
||||
SettingsButton::ReplayMoveIntervalUp,
|
||||
"Slow down replay playback (longer per-move interval).",
|
||||
font_res,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// `Label Value [⇄]` — used for cycle/toggle rows (draw mode, theme,
|
||||
@@ -1603,6 +1672,7 @@ fn toggle_row<Marker: Component>(
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
width: Val::Percent(100.0),
|
||||
..default()
|
||||
})
|
||||
.with_children(|row| {
|
||||
@@ -1611,8 +1681,20 @@ fn toggle_row<Marker: Component>(
|
||||
label_font,
|
||||
TextColor(TEXT_SECONDARY),
|
||||
));
|
||||
row.spawn((marker, Text::new(value), value_font, TextColor(TEXT_PRIMARY)));
|
||||
icon_button(row, "⇄", action, tooltip, font_res);
|
||||
row.spawn(Node {
|
||||
flex_grow: 1.0,
|
||||
..default()
|
||||
});
|
||||
row.spawn(Node {
|
||||
flex_direction: FlexDirection::Row,
|
||||
align_items: AlignItems::Center,
|
||||
column_gap: VAL_SPACE_2,
|
||||
..default()
|
||||
})
|
||||
.with_children(|cluster| {
|
||||
cluster.spawn((marker, Text::new(value), value_font, TextColor(TEXT_PRIMARY)));
|
||||
icon_button(cluster, "⇄", action, tooltip, font_res);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,16 @@ pub struct StatsCell;
|
||||
#[derive(Resource, Debug, Default, Clone)]
|
||||
pub struct ReplayHistoryResource(pub ReplayHistory);
|
||||
|
||||
/// Marker on the "Copy share link" button inside the Stats modal.
|
||||
/// Click reads the share URL from the currently-selected replay
|
||||
/// (`history.0.replays[selected.0].share_url`) and writes it to the
|
||||
/// OS clipboard via `arboard`, surfacing a confirmation toast. The
|
||||
/// share URL is populated by `sync_plugin::poll_replay_upload_result`
|
||||
/// when the corresponding win's upload completes and is persisted to
|
||||
/// `replays.json` so it survives a restart.
|
||||
#[derive(Component, Debug)]
|
||||
pub struct CopyShareLinkButton;
|
||||
|
||||
/// Currently-selected index into [`ReplayHistoryResource::0`].`replays`.
|
||||
///
|
||||
/// `0` is the most recent win and is the default on every modal open.
|
||||
@@ -210,6 +220,7 @@ impl Plugin for StatsPlugin {
|
||||
refresh_replay_history_on_win.after(GameMutation),
|
||||
)
|
||||
.add_systems(Update, handle_watch_replay_button)
|
||||
.add_systems(Update, handle_copy_share_link_button)
|
||||
.add_systems(
|
||||
Update,
|
||||
(handle_replay_selector_buttons, repaint_replay_selector_caption).chain(),
|
||||
@@ -277,6 +288,56 @@ fn refresh_replay_history_on_win(
|
||||
/// resets the live game to the recorded deal and ticks through the
|
||||
/// move list via [`crate::replay_playback`]; the
|
||||
/// [`crate::replay_overlay`] banner surfaces while playback runs.
|
||||
/// Copies the currently-selected replay's `share_url` to the OS
|
||||
/// clipboard via `arboard` and surfaces a confirmation toast. When no
|
||||
/// URL is in hand on the selected entry (replay never uploaded — the
|
||||
/// player won on a local-only backend, the upload failed, or the
|
||||
/// replay pre-dates v0.19.0 share-link persistence) the button still
|
||||
/// acknowledges the click but explains why the clipboard wasn't
|
||||
/// written. `arboard::Clipboard::new()` failures are logged + surfaced
|
||||
/// as a generic "couldn't reach the clipboard" toast rather than
|
||||
/// swallowed — they're rare but worth diagnosing.
|
||||
fn handle_copy_share_link_button(
|
||||
buttons: Query<&Interaction, (With<CopyShareLinkButton>, Changed<Interaction>)>,
|
||||
history: Res<ReplayHistoryResource>,
|
||||
selected: Res<SelectedReplayIndex>,
|
||||
mut toast: MessageWriter<InfoToastEvent>,
|
||||
) {
|
||||
if !buttons.iter().any(|i| *i == Interaction::Pressed) {
|
||||
return;
|
||||
}
|
||||
let Some(url) = history
|
||||
.0
|
||||
.replays
|
||||
.get(selected.0)
|
||||
.and_then(|r| r.share_url.as_ref())
|
||||
else {
|
||||
toast.write(InfoToastEvent(
|
||||
"No share link for this replay \u{2014} win a game on a server-backed sync to upload one.".to_string(),
|
||||
));
|
||||
return;
|
||||
};
|
||||
match arboard::Clipboard::new() {
|
||||
Ok(mut cb) => match cb.set_text(url.clone()) {
|
||||
Ok(()) => {
|
||||
toast.write(InfoToastEvent(format!("Copied: {url}")));
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("clipboard write failed: {e}");
|
||||
toast.write(InfoToastEvent(
|
||||
"Couldn't write to clipboard \u{2014} share link wasn't copied.".to_string(),
|
||||
));
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!("clipboard init failed: {e}");
|
||||
toast.write(InfoToastEvent(
|
||||
"Couldn't reach the clipboard \u{2014} share link wasn't copied.".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_watch_replay_button(
|
||||
mut commands: Commands,
|
||||
buttons: Query<&Interaction, (With<WatchReplayButton>, Changed<Interaction>)>,
|
||||
@@ -811,6 +872,19 @@ fn spawn_stats_screen(
|
||||
ButtonVariant::Secondary,
|
||||
font_res,
|
||||
);
|
||||
// Copy share link only renders when a sharable URL is in
|
||||
// hand. The button is intentionally absent (rather than
|
||||
// disabled) when no upload has happened yet — keeps the
|
||||
// action bar free of dead controls in the local-only and
|
||||
// first-launch cases.
|
||||
spawn_modal_button(
|
||||
actions,
|
||||
CopyShareLinkButton,
|
||||
"Copy share link",
|
||||
None,
|
||||
ButtonVariant::Secondary,
|
||||
font_res,
|
||||
);
|
||||
spawn_modal_button(
|
||||
actions,
|
||||
StatsCloseButton,
|
||||
|
||||
@@ -19,8 +19,8 @@ use chrono::Utc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use solitaire_data::{
|
||||
save_achievements_to, save_progress_to, save_stats_to, AchievementRecord, PlayerProgress,
|
||||
Replay, StatsSnapshot, SyncError, SyncProvider,
|
||||
save_achievements_to, save_progress_to, save_replay_history_to, save_stats_to,
|
||||
AchievementRecord, PlayerProgress, Replay, StatsSnapshot, SyncError, SyncProvider,
|
||||
};
|
||||
use solitaire_sync::{merge, SyncPayload, SyncResponse};
|
||||
|
||||
@@ -29,7 +29,7 @@ use crate::events::{GameWonEvent, ManualSyncRequestEvent, SyncCompleteEvent};
|
||||
use crate::game_plugin::RecordingReplay;
|
||||
use crate::progress_plugin::{ProgressResource, ProgressStoragePath};
|
||||
use crate::resources::{GameStateResource, SyncStatus, SyncStatusResource};
|
||||
use crate::stats_plugin::{StatsResource, StatsStoragePath};
|
||||
use crate::stats_plugin::{LatestReplayPath, ReplayHistoryResource, StatsResource, StatsStoragePath};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public resources
|
||||
@@ -57,6 +57,13 @@ pub struct PullTaskResult(pub Option<Result<SyncPayload, SyncError>>);
|
||||
#[derive(Resource, Default)]
|
||||
struct PullTask(Option<Task<Result<SyncPayload, SyncError>>>);
|
||||
|
||||
/// Holds the in-flight winning-replay upload task so the polling
|
||||
/// system can harvest the resulting share URL on the main thread
|
||||
/// without blocking. `None` outside an active upload; `Some(task)`
|
||||
/// from `GameWonEvent` until the response lands.
|
||||
#[derive(Resource, Default)]
|
||||
struct PendingReplayUpload(Option<Task<Result<String, SyncError>>>);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plugin struct
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -94,12 +101,18 @@ impl Plugin for SyncPlugin {
|
||||
.init_resource::<SyncStatusResource>()
|
||||
.init_resource::<PullTaskResult>()
|
||||
.init_resource::<PullTask>()
|
||||
.init_resource::<PendingReplayUpload>()
|
||||
.add_message::<ManualSyncRequestEvent>()
|
||||
.add_message::<SyncCompleteEvent>()
|
||||
.add_systems(Startup, start_pull)
|
||||
.add_systems(
|
||||
Update,
|
||||
(poll_pull_result, handle_manual_sync_request, push_replay_on_win),
|
||||
(
|
||||
poll_pull_result,
|
||||
handle_manual_sync_request,
|
||||
push_replay_on_win,
|
||||
poll_replay_upload_result,
|
||||
),
|
||||
)
|
||||
.add_systems(Last, push_on_exit);
|
||||
}
|
||||
@@ -282,6 +295,7 @@ fn push_replay_on_win(
|
||||
provider: Res<SyncProviderResource>,
|
||||
game: Res<GameStateResource>,
|
||||
recording: Res<RecordingReplay>,
|
||||
mut pending: ResMut<PendingReplayUpload>,
|
||||
) {
|
||||
for ev in wins.read() {
|
||||
// Empty-recording guard mirrors `record_replay_on_win` —
|
||||
@@ -300,15 +314,55 @@ fn push_replay_on_win(
|
||||
recording.moves.clone(),
|
||||
);
|
||||
let provider = provider.0.clone();
|
||||
AsyncComputeTaskPool::get()
|
||||
.spawn(async move {
|
||||
match provider.push_replay(&replay).await {
|
||||
Ok(()) => {}
|
||||
Err(SyncError::UnsupportedPlatform) => {}
|
||||
Err(e) => warn!("replay upload failed: {e}"),
|
||||
let task = AsyncComputeTaskPool::get()
|
||||
.spawn(async move { provider.push_replay(&replay).await });
|
||||
// If a previous upload is still in flight, drop it — the most
|
||||
// recent win is the one whose share link the player will care
|
||||
// about. Bevy's `Task` Drop cancels cooperatively.
|
||||
pending.0 = Some(task);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Update-schedule system: harvests the upload task's result on the
|
||||
/// main thread once it resolves. On success writes the share URL into
|
||||
/// the most-recent entry of [`ReplayHistoryResource`] (`replays[0]`,
|
||||
/// guaranteed by `record_replay_on_win` to be the win this upload
|
||||
/// covers, since `cancel-on-replace` in `push_replay_on_win` drops any
|
||||
/// older in-flight task) and persists the updated history to disk so
|
||||
/// the URL survives a restart. `UnsupportedPlatform` (the
|
||||
/// `LocalOnlyProvider` no-op path) is silently absorbed; real network
|
||||
/// / auth errors log a warn but never clobber an existing URL.
|
||||
fn poll_replay_upload_result(
|
||||
mut pending: ResMut<PendingReplayUpload>,
|
||||
mut history: ResMut<ReplayHistoryResource>,
|
||||
replay_path: Res<LatestReplayPath>,
|
||||
) {
|
||||
let Some(task) = pending.0.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(result) = future::block_on(future::poll_once(task)) else {
|
||||
return;
|
||||
};
|
||||
pending.0 = None;
|
||||
let url = match result {
|
||||
Ok(url) => url,
|
||||
Err(SyncError::UnsupportedPlatform) => return,
|
||||
Err(e) => {
|
||||
warn!("replay upload failed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(entry) = history.0.replays.first_mut() else {
|
||||
// Defensive: `push_replay_on_win` only fires after a win, so a
|
||||
// missing replays[0] means another system cleared the history
|
||||
// mid-upload. Drop the URL silently rather than panicking.
|
||||
return;
|
||||
};
|
||||
entry.share_url = Some(url);
|
||||
if let Some(path) = replay_path.0.as_deref()
|
||||
&& let Err(e) = save_replay_history_to(path, &history.0)
|
||||
{
|
||||
warn!("failed to persist share URL into replay history: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,4 +530,87 @@ mod tests {
|
||||
let payload = build_payload(&stats, &[], &PlayerProgress::default());
|
||||
assert_eq!(payload.stats.games_played, 42);
|
||||
}
|
||||
|
||||
/// `poll_replay_upload_result` must write the resolved share URL
|
||||
/// into `replays[0].share_url` AND persist the updated history to
|
||||
/// disk so the URL survives a restart. Pins v0.19.0's persistent
|
||||
/// share-link contract — the v0.18.0 ephemeral
|
||||
/// `LastSharedReplayUrl` resource is gone, so a regression here
|
||||
/// would silently drop the link.
|
||||
#[test]
|
||||
fn upload_result_writes_share_url_into_replay_and_persists() {
|
||||
use solitaire_core::game_state::{DrawMode, GameMode};
|
||||
use solitaire_data::{
|
||||
load_replay_history_from, save_replay_history_to, Replay, ReplayHistory,
|
||||
};
|
||||
|
||||
let mut app = headless_app_with(NoOpProvider);
|
||||
let path = std::env::temp_dir()
|
||||
.join("solitaire_test_replay_share_url_persist.json");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
// Seed the in-memory history with a single replay carrying no
|
||||
// share_url — the upload-poll path must populate it.
|
||||
let initial = Replay::new(
|
||||
42,
|
||||
DrawMode::DrawOne,
|
||||
GameMode::Classic,
|
||||
60,
|
||||
500,
|
||||
chrono::NaiveDate::from_ymd_opt(2026, 5, 6).expect("valid date"),
|
||||
vec![],
|
||||
);
|
||||
let history = ReplayHistory {
|
||||
schema_version: solitaire_data::REPLAY_HISTORY_SCHEMA_VERSION,
|
||||
replays: vec![initial],
|
||||
};
|
||||
save_replay_history_to(&path, &history).expect("seed history on disk");
|
||||
app.insert_resource(crate::stats_plugin::ReplayHistoryResource(history));
|
||||
app.insert_resource(crate::stats_plugin::LatestReplayPath(Some(path.clone())));
|
||||
|
||||
// Pre-resolved task carrying the URL the production path would
|
||||
// get back from the server.
|
||||
let url = "https://example.test/replays/abc123".to_string();
|
||||
let task = AsyncComputeTaskPool::get().spawn({
|
||||
let url = url.clone();
|
||||
async move { Ok::<String, SyncError>(url) }
|
||||
});
|
||||
app.world_mut()
|
||||
.resource_mut::<PendingReplayUpload>()
|
||||
.0 = Some(task);
|
||||
|
||||
// Pump frames until the polling system observes the task as
|
||||
// ready and clears `PendingReplayUpload`.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while app.world().resource::<PendingReplayUpload>().0.is_some() {
|
||||
app.update();
|
||||
std::thread::yield_now();
|
||||
if std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
app.world().resource::<PendingReplayUpload>().0.is_none(),
|
||||
"upload task should have been consumed within 15 s wall-clock",
|
||||
);
|
||||
|
||||
// In-memory contract: replays[0].share_url is now Some(url).
|
||||
let live = app
|
||||
.world()
|
||||
.resource::<crate::stats_plugin::ReplayHistoryResource>();
|
||||
assert_eq!(
|
||||
live.0.replays.first().and_then(|r| r.share_url.clone()),
|
||||
Some(url.clone()),
|
||||
"share URL must be written into replays[0].share_url",
|
||||
);
|
||||
// Persistence contract: a fresh load picks up the same URL.
|
||||
let on_disk = load_replay_history_from(&path).expect("history must reload");
|
||||
assert_eq!(
|
||||
on_disk.replays.first().and_then(|r| r.share_url.clone()),
|
||||
Some(url),
|
||||
"share URL must survive a save/load round-trip",
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,11 +171,15 @@ fn advance_time_attack(
|
||||
mut ended: MessageWriter<TimeAttackEndedEvent>,
|
||||
paused: Option<Res<crate::pause_plugin::PausedResource>>,
|
||||
path: Option<Res<TimeAttackSessionPath>>,
|
||||
home_screens: Query<(), With<crate::home_plugin::HomeScreen>>,
|
||||
) {
|
||||
if !session.active {
|
||||
return;
|
||||
}
|
||||
if paused.is_some_and(|p| p.0) {
|
||||
// Mirrors `tick_elapsed_time`: pause while the launch / mode-picker
|
||||
// Home modal is up so the countdown doesn't burn while the player
|
||||
// is choosing what to play next.
|
||||
if paused.is_some_and(|p| p.0) || !home_screens.is_empty() {
|
||||
return;
|
||||
}
|
||||
session.remaining_secs -= time.delta_secs();
|
||||
|
||||
@@ -235,6 +235,7 @@ impl Plugin for WinSummaryPlugin {
|
||||
collect_session_achievements,
|
||||
spawn_win_summary_after_delay,
|
||||
handle_win_summary_buttons,
|
||||
handle_win_summary_keyboard,
|
||||
apply_screen_shake,
|
||||
reveal_score_breakdown,
|
||||
)
|
||||
@@ -624,6 +625,31 @@ fn handle_win_summary_buttons(
|
||||
}
|
||||
}
|
||||
|
||||
/// Keyboard accelerator for the win summary's "Play Again" button.
|
||||
/// Enter / Return collapses the win modal and starts a fresh deal —
|
||||
/// the same path the click handler takes — so a keyboard-only player
|
||||
/// can dismiss the post-win celebration without reaching for the mouse.
|
||||
fn handle_win_summary_keyboard(
|
||||
keys: Option<Res<ButtonInput<KeyCode>>>,
|
||||
overlays: Query<Entity, With<WinSummaryOverlay>>,
|
||||
mut commands: Commands,
|
||||
mut new_game: MessageWriter<NewGameRequestEvent>,
|
||||
) {
|
||||
if overlays.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(keys) = keys else {
|
||||
return;
|
||||
};
|
||||
if !keys.just_pressed(KeyCode::Enter) {
|
||||
return;
|
||||
}
|
||||
for entity in &overlays {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
new_game.write(NewGameRequestEvent::default());
|
||||
}
|
||||
|
||||
/// Applies a decaying sinusoidal offset to the main `Camera2d` each frame
|
||||
/// while `ScreenShakeResource::remaining > 0`.
|
||||
///
|
||||
@@ -798,8 +824,11 @@ fn spawn_overlay(
|
||||
BackgroundColor(ACCENT_PRIMARY),
|
||||
))
|
||||
.with_children(|b| {
|
||||
// Append the Enter / Return glyph so keyboard players see
|
||||
// the accelerator on the button itself — mirrors the
|
||||
// chip-style hints on every modal button helper.
|
||||
b.spawn((
|
||||
Text::new("Play Again"),
|
||||
Text::new("Play Again \u{21B5}"),
|
||||
TextFont { font_size: TYPE_BODY_LG, ..default() },
|
||||
TextColor(BG_BASE),
|
||||
));
|
||||
|
||||
Reference in New Issue
Block a user