diff --git a/README.md b/README.md index fe4034f..4794ea1 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,10 @@ npm install && npm run build --prefix web npm run test --prefix web # frontend tests ``` +**Versus:** open the VERSUS tab, create a room and send the invite link — +two humans, server-authoritative, with a turn clock, concede and +reconnect-on-refresh ([docs/multiplayer.md](docs/multiplayer.md)). + Right now matches pit the two starter decks (`neon_frequency` vs `cinderworks`) against each other; the AI is a greedy heuristic opponent — no search, no LLM. Going second gets a **Signal Spike** (a free Track that grants +1 Bandwidth this turn) as second-player compensation — the coin analog. ## CLI @@ -80,7 +84,8 @@ FastAPI app (`sunder/server/app.py`), docs at `/api/docs`: - `POST /api/registry` — propose a tag - `POST /api/registry/{kind}/{id}/approve` — approve a proposal - `POST /api/generate` — run `generate_pack` (async thread) -- `WS /ws` — the match protocol: `start` / `restart` / `play {hand, target?}` / `attack {board, target}` / `end_turn`, all answers as full `state` snapshots +- `GET /api/rooms/{code}` — versus room status (never exposes tokens) +- `WS /ws` — the match protocol: `start` / `restart` / `play {hand, target?}` / `attack {board, target}` / `end_turn` / `concede`, plus the versus lobby `create_room` / `join_room` / `resume` / `leave_room`; every mutation answers each seat with its own `state` snapshot Snapshots (`state.py`) are viewer-aware: opponent hand is a count, hidden B-SIDEs are masked AND precomputed server-side (`is_playable`, `attack_targets`, `legal_targets`) — the client stays dumb. @@ -137,6 +142,7 @@ Full documentation lives in [docs/](docs/index.md): - [Architecture](docs/architecture.md) — module map, closed vocabulary, engine design - [Card format](docs/cards.md) — JSON schema, budget model, registry governance - [Card generation](docs/generation.md) — the LLM pipeline + review gate +- [Multiplayer](docs/multiplayer.md) — versus rooms, clocks, resume, server authority, roadmap - [Server API](docs/api.md) — REST + WebSocket protocol, snapshot shape - [Developing](docs/developing.md) — setup, tests, lint, CI, Docker/homelab deploy @@ -150,9 +156,11 @@ pytest tests -x - **Match** — AI vs AI across seeds: every match terminates, every seed is deterministic - **Generation** — every module in isolation (client/SSE, profile, sampler, ledger, humanizer, legality, end-to-end with a `FakeLLM` double), including graceful-degradation paths - **Web** — API routes, tag registry, WS loop +- **Versus** — seat-aware rooms, clocks, grace/resume, lobby protocol, full PvP match over two sockets ## Status / notes +- v0.4.0 — **Versus.** Invite-code PvP rooms with server-side turn clocks, concede, and resume-on-refresh; every match runs in a seat-aware `MatchRoom` (the bot is just another seat). Fixes a Station-1-win bug (`winner == 0` read as "no winner") and hidden B-SIDE names leaking through the log. - v0.3.7.5 — card faces redrawn at the standard 5:7 ratio, with an edition/rarity badge, a station watermark, clamped rules, and a playability signal on the hand cost bars; flavor moves to the inspector. Profile icons are a separate pick from sleeves: the station avatar opens an emblem grid, and the glyph takes your sleeve's ink. - v0.3.6.1 — changelog inside the game UI (Changelog tab) with a short roadmap. - Card backs are hand-editable SVG art (`web/src/art/sleeves/*.svg`), one file per sleeve, themed via palette channels from `sunder/cards/sleeves.json`. Browse + pick in the codex (SLEEVES tab), carried server-side per station so opponents see your back too. Adding a sleeve = one JSON entry + one SVG. diff --git a/docs/api.md b/docs/api.md index e4250bb..038fbbe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,38 +20,52 @@ by the test suite). The module also exposes a ready `app = create_app()` for | GET | `/api/health` | `{"ok": true}` | | GET | `/api/sleeves` | card-back manifest from `sunder/cards/sleeves.json` | | GET | `/api/avatars` | profile-icon manifest from `sunder/cards/avatars.json` | +| GET | `/api/rooms/{code}` | versus room status: `{code, status: "waiting" \| "live" \| "over"}`, `404` if unknown — never exposes seat tokens ([multiplayer](multiplayer.md)) | The built SPA is served at `/` **iff `web/dist` exists** (StaticFiles, html mode). Rails: dev frontend via `npm run dev` in `web/` proxies `/api` + `/ws`. ## WebSocket `/ws` -One match per connection; client-driven request/response; every mutation -answers with a full `state` snapshot. Protocol: +Every connection is routed through a `MatchRoom` (`sunder/server/match.py`). +A practice match is Human(seat 0) vs `BotSeat`; a versus match is two +`HumanSeat`s created by the lobby (see [multiplayer.md](multiplayer.md)). +Actions are validated against **the sender's seat**, and every mutation is +answered with a `state` to **each** seat, built for that seat's viewpoint. | Client → | Payload | Effect | |---|---|---| -| `start` / `restart` | `{seed?}` | new GameState + deal; answers a fresh state | -| `play` | `{hand: , target?: }` | play hand card (indexes into *your* hand); `target` auto-looked up on the enemy board | +| `start` / `restart` | `{seed?}` | new practice match vs the bot (refused while a live PvP match is running) | +| `play` | `{hand: , target?: }` | play a card from *your* hand; `target` must be one of the card's `legal_targets` (friendly or enemy), else `bad target`. A target sent for an untargeted card is ignored | | `attack` | `{board: , target: \| "face"}` | attack (indexes into your board) | -| `end_turn` | `{turn: }` | guarded — a stale turn number is ignored; then the AI's turn is **staged**: before it speaks (director pause), then one snapshot per AI action, paced by the jitter windows | +| `end_turn` | `{turn: }` | guarded — a stale turn number or out-of-turn request is ignored (answered with a fresh state). Against the bot, its turn then runs as a background task: a think pause, then one `state` per AI action, paced by the jitter windows | +| `concede` | — | forfeit the current match (`end_reason: "concede"`) | +| `create_room` / `join_room {code}` / `resume {code, token}` / `leave_room` | | versus lobby — see [multiplayer.md](multiplayer.md#protocol) | | `set_sleeve` | `{sleeve: ""}` | set your station's card back; id validated against the sleeve manifest (invalid → error, no state change); the opponent sees the new sleeve in `players.{}.sleeve` | | `set_avatar` | `{avatar: ""}` | set your station's profile icon; id validated against `avatars.json` (invalid → error, no state change); glyph + sleeve ink ride the snapshot | | `ping` | — | answers `{"type": "pong"}` | Server →: -* `{"type": "state", "snapshot": {...}}` +* `{"type": "state", "snapshot": {...}, "match": {...}}` — `match` is + per-seat: `mode` (`"bot"`/`"pvp"`), `code`, `seat`, + `opponent_connected`, `turn_seconds`, `turn_remaining` +* `{"type": "room", ...}` / `{"type": "room_closed", "reason": ...}` — versus lobby * `{"type": "error", "message": "…"}` — never closes the socket +While the bot is playing, the socket stays responsive: a `play` sent during +its turn gets `not your turn` immediately, and `restart` cancels the bot's +turn cleanly. + ## Snapshot shape (`state.py`) -Viewer-aware (`viewer = 0` for the human station): +Viewer-aware — each seat gets `snapshot(gs, viewer=)`: ```jsonc { "turn": 1, "current": 0, "phase": "MAIN", - "winner": null, "status": "Turn 1 | …", + "winner": null, "end_reason": null, // "signal" | "concede" | "timeout" | "disconnect" + "status": "Turn 1 | …", "viewer": 0, "can_act": true, // winner is None AND it is your turn "players": {"0": {...}, "1": {...}}, diff --git a/docs/architecture.md b/docs/architecture.md index 1b781b1..5aed601 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -17,6 +17,8 @@ sunder/ codex.py CLI card browser cards/ JSON sets + registry.json server/ FastAPI app (REST + WS) + uvicorn launcher + match.py MatchRoom + seats (HumanSeat / BotSeat), clocks + lobby.py versus rooms: invite codes, seat tokens, resume gen/ LLM card-generation pipeline web/ React + TypeScript + Vite SPA (served from web/dist) tests/ ~20 Python modules + vitest suite in web/ @@ -73,6 +75,21 @@ Card JSON ──parse_card()──▶ Card ──▶ CardInstance (zone-aware ru counter effects can CUT a track mid-cast; `resolving` guards re-entrancy (`COPY_LAST_TRACK` can't copy itself). +## Match rooms + +`game.py` has no notion of sockets or players-as-people; the server wraps +each `GameState` in a `MatchRoom` with one **seat** per station. Seats are +pluggable — `HumanSeat` (a WebSocket) or `BotSeat` (the heuristic AI run +as a background task) — so practice and versus share one code path. The +room validates every action against the sender's station, serializes +mutations behind one lock, and broadcasts a per-viewer snapshot to each +seat. Versus rooms add a turn clock, AFK strikes and a disconnect grace; +the in-memory `Lobby` pairs connections via invite codes. Details: +[multiplayer.md](multiplayer.md). + +Game end is always `winner` (0/1) + `end_reason`; use `gs.game_over`, +never truthiness of `winner` (station 0 winning is `winner == 0`). + ## Snapshot masks * Viewer's own board: full — `atk`/`def` are *effective* values, `damage`, @@ -80,6 +97,8 @@ Card JSON ──parse_card()──▶ Card ──▶ CardInstance (zone-aware ru * Hidden B-SIDE (opponent view): name `???`, type `None`, only the B-SIDE keyword. The owner additionally sees its resolved rules text. * Rival hand: a count only. +* Log/history text: a hidden B-SIDE is named "Hidden B-SIDE" until revealed + (`CardInstance.label()`), so damage/death lines can't leak it. ## Resource model diff --git a/docs/developing.md b/docs/developing.md index bc2a4b8..fbcc1e3 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -75,10 +75,22 @@ installed in the image layer above the source layer, so code-only changes rebuild fast. `.dockerignore` keeps node_modules, local dist, caches, and development docs out of the build context. +### Runtime settings + +| Env var | Default | | +|---|---|---| +| `SUNDER_TURN_SECONDS` | `75` | versus turn clock (`0`/`off` = untimed) | +| `SUNDER_GRACE_SECONDS` | `60` | versus reconnect window before a disconnect forfeits | +| `SUNDER_LLM_*` | see README | card-generation gateway | + +Versus rooms are held **in memory in one process**: keep uvicorn at a single +worker (the image's default) and expect a restart/redeploy to end live +matches until Phase 2 persistence lands — see +[multiplayer.md](multiplayer.md#configuration). + ### Homelab (efx-lab) flow -The lab host consumes a tar-over-ssh stream (no rsync, no clone needed — the -repo is private): +The lab host consumes a tar-over-ssh stream (no rsync, no clone needed): ```bash tar -czf - --exclude='.git' --exclude='web/node_modules' \ diff --git a/docs/index.md b/docs/index.md index 77cee96..414f42c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,6 +9,7 @@ the airwaves, and an LLM generates new card packs that never break the rules. | [Architecture](architecture.md) | Module map, the closed vocabulary, why the engine never special-cases cards | | [Card format](cards.md) | JSON schema for sets, the cost budget, tag + keyword governance | | [Card generation](generation.md) | The LLM pipeline end-to-end: profile → sampler → ledger → budget → humanizer | +| [Multiplayer](multiplayer.md) | Versus rooms, clocks, resume + seat tokens, server authority, roadmap to accounts/ratings | | [Server API](api.md) | REST endpoints, the WebSocket match protocol, snapshot shape | | [Developing](developing.md) | Setup, tests, lint, CI, and deploying the web server (Docker, efx-lab) | diff --git a/docs/multiplayer.md b/docs/multiplayer.md new file mode 100644 index 0000000..e674627 --- /dev/null +++ b/docs/multiplayer.md @@ -0,0 +1,173 @@ +# Multiplayer (versus) + +Two humans, one server-authoritative match. This page covers how live PvP +works today (Phase 1: invite rooms, in-memory) and what's planned next. + +> **Status:** Phase 1. Rooms live in server memory: a server restart ends +> every live match, and there are no accounts, ratings or saved history yet. +> Those land in Phase 2 (Postgres + username/password accounts) and +> Phase 3 (ratings, leaderboards, stats). See [Roadmap](#roadmap). + +## Playing + +1. Open the **VERSUS** tab and press **CREATE ROOM**. You get a six-character + code (e.g. `K7QM2X`) and a **COPY INVITE LINK** button + (`https:///?room=K7QM2X`). +2. Your rival opens the link, or types the code under **JOIN**. +3. The match starts right away. Seats are random, so the host doesn't always + go first. Station 2 still gets the Signal Spike. + +During the match, the bar above the board shows the room code, whether your +rival is connected, and the turn clock. **CONCEDE** asks for confirmation. + +| Rule | Default | What happens | +|---|---|---| +| Turn timer | 75 s | When it runs out, your turn ends for you. | +| AFK limit | 3 strikes | Three timeouts in a row with no action forfeit the match (`timeout`). Any play, attack or end-turn resets your strikes. | +| Reconnect grace | 60 s | If you disconnect, your seat waits for you. Stay away longer than the grace period and you forfeit (`disconnect`). | +| Concede / leave | — | Ends the match at once (`concede`). Leaving the room during a live match counts as a concede. | + +Practice matches against the bot have no clocks. + +**Refreshing the page** brings you back to your seat (see +[Resume](#resume-and-seat-tokens)). Opening the same match in a second tab +moves your seat there, and the first tab drops back to practice. + +## Architecture + +``` +browser ──WS /ws──▶ Connection ──▶ Lobby ──▶ MatchRoom ──▶ GameState + │ ├─ HumanSeat(0, ws) + │ └─ HumanSeat(1, ws) (or BotSeat) + └─ pending rooms (code → host) +``` + +| Module | Owns | +|---|---| +| `sunder/game.py` | Rules. `forfeit(station, reason)` and `end_reason` cover endings that aren't Signal. No I/O. | +| `sunder/server/match.py` | `MatchRoom`: one `GameState` plus two seats. It checks every action against the seat that sent it, sends each seat its own snapshot, and runs the turn clock, AFK strikes and grace clocks. All mutations happen under `room.lock`. | +| `sunder/server/lobby.py` | `Lobby`: invite codes, seat tokens, join, resume, leave, and cleanup of finished rooms. | +| `sunder/server/app.py` | `/ws` routing. A practice `start` builds a Human-vs-Bot `MatchRoom`; the lobby messages build Human-vs-Human ones. | + +The bot is just another seat (`BotSeat`). It runs as a background task, so +sockets stay responsive during its turn, and the same `MatchRoom` code paths +serve practice and versus. + +### Server authority + +* Clients send intents (`play`, `attack`, `end_turn`), and the room checks + them against the **sender's** station. A seat can't act out of turn or + aim at an illegal target: chosen targets must be in + `legal_track_targets()`. +* Each seat gets `snapshot(gs, viewer=seat)`. The rival's hand is a count, + and hidden B-SIDEs are masked. +* Log and history text never name a hidden B-SIDE. `CardInstance.label()` + returns "Hidden B-SIDE" while the card is hidden, so area damage or a death + can't leak it. This is covered by `tests/test_pvp.py`. +* The server picks the match seed (`secrets.randbits`) and never sends it to + clients. Knowing the seed would reveal both shuffled playlists. + +### Resume and seat tokens + +When a match goes live, each seat receives a **seat token** +(`secrets.token_urlsafe(16)`) in its `room` message. The token is a bearer +secret: whoever holds it can play that seat. + +* The client keeps `{code, token}` in `sessionStorage` under `sunder-pvp`. + That's per tab and cleared when the tab closes. The token is never shown in + the UI and never appears in URLs. +* After a reconnect the client sends `resume {code, token}`. The server + compares tokens in constant time (`hmac.compare_digest`), reattaches the + socket and cancels the grace clock. +* Room codes are shareable but are **not** credentials. `GET /api/rooms/{code}` + only returns `waiting` / `live` / `over`. + +### Lifecycle + +``` +create_room ─▶ waiting ──join_room──▶ live ──signal | concede | timeout | disconnect──▶ over + │ ▲ │ + └─ leave_room / socket closes └──── resume (within grace) ◀── socket drops └─ reaped after 5 min + → room deleted (or when both leave) +``` + +A server holds at most `max_rooms` rooms (200 by default, pending and live +combined). Past that, `create_room` fails with "server is full". + +## Protocol + +These messages extend the existing [WebSocket protocol](api.md#websocket-ws). + +| Client → | Payload | Effect | +|---|---|---| +| `create_room` | — | Host a room. Answers `room {status: "waiting", code}`. Ends any practice match. | +| `join_room` | `{code}` | Join a waiting room (case-insensitive). Both seats get `room {status: "live", seat, token}` and then a `state`. | +| `resume` | `{code, token}` | Reattach to your seat. Answers `room` + `state`, and the rival sees `opponent_connected: true`. | +| `leave_room` | — | Cancel a waiting room, or concede and leave a live one. Answers `room_closed {reason: "left"}`. | +| `concede` | — | Forfeit the current match (versus or practice). | + +| Server → | Payload | +|---|---| +| `room` | `{mode: "pvp", code, seat, token, status}`. `seat` and `token` are `null` while waiting. | +| `room_closed` | `{reason}`: `"left"` or `"resumed elsewhere"`. | +| `state` | `{snapshot, match}` (see below). | +| `error` | `{message}`, e.g. `no such room`, `room is full`, `not your turn`, `that match is no longer running`, `you're in a PvP match — concede or leave first`. | + +Every `state` now carries `match`: + +```jsonc +{ + "mode": "pvp", // or "bot" + "code": "K7QM2X", // null for practice + "seat": 1, // your station + "opponent_connected": true, + "turn_seconds": 75, // null when untimed (practice, or clock disabled) + "turn_remaining": 41.37 // seconds left on the current turn, or null +} +``` + +The snapshot also gains `end_reason`: `null` while the match is live, then +one of `"signal" | "concede" | "timeout" | "disconnect"`. + +`start` / `restart` are refused during a live PvP match. You have to concede +or leave first, so a stray key press can't throw away a ranked game later on. + +## Configuration + +| Env var | Default | Meaning | +|---|---|---| +| `SUNDER_TURN_SECONDS` | `75` | Turn length in versus. Set to `0` or `off` for untimed versus. | +| `SUNDER_GRACE_SECONDS` | `60` | Reconnect window before a disconnect forfeits. `0` / `off` disables it (a dropped seat then waits forever). | + +`create_app()` takes the same settings as keyword arguments (`turn_seconds`, +`grace_seconds`, `afk_limit`, `finished_ttl`). Tests pass `0` to switch the +clocks off, or tiny values to exercise them. + +**Single process only.** Rooms live in one Python process, so run uvicorn +with **one worker** (the Docker image already does). Running several workers +would need shared room state, for example Redis, which is out of scope until +it's actually needed. + +## Testing + +* `tests/test_pvp.py`: forfeits and end reasons; the hidden-B-SIDE log + regression; turn timer, AFK strikes, grace and reconnect; and, over + WebSockets: create/join, alternating turns, a full PvP match to completion, + join errors, full rooms, resume (including bad tokens and "resumed + elsewhere"), concede, leave, disconnect forfeit. +* `tests/test_seats.py`: seat-aware rooms, per-seat views, out-of-turn + rejection, the station-0 `winner` regression. +* `web/src/pvp.test.ts`, `components/MatchBar.test.tsx`, + `components/LobbyView.test.tsx`, and the "App — versus" suite in + `App.test.tsx`: session storage, invite links, resume/join on connect, + the stale-resume fallback, hosting, concede confirmation, end-of-match text. + +## Roadmap + +| Phase | Scope | +|---|---| +| 0 ✅ | Fix for the `winner == 0` bug; seat-aware `MatchRoom`; bot as a seat. | +| 1 ✅ | Invite rooms, server-side clocks, concede, resume, the VERSUS UI. | +| 2 | Postgres (async SQLAlchemy 2 + Alembic), username/password accounts (argon2, httpOnly session cookie), profiles (avatar/sleeve stored server-side), match + action log (seed + actions = replay). Seat tokens become "the logged-in user owns this seat". | +| 3 | Glicko-2 ratings, ranked matchmaking queue, leaderboard, per-deck stats, match history. | +| 4 | Deck choice/building, replays, spectating, admin roles for `/api/registry` approve + `/api/generate`, rate limits. | diff --git a/pyproject.toml b/pyproject.toml index e978124..95ca670 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "sunder" -version = "0.3.7.5" +version = "0.4.0" description = "Procedural duel card game — the Sundered spectrum" requires-python = ">=3.11" dependencies = [ diff --git a/sunder/game.py b/sunder/game.py index 6d42e5b..a40bd91 100644 --- a/sunder/game.py +++ b/sunder/game.py @@ -56,7 +56,8 @@ def has(self, key: str) -> bool: return key in self.card.keywords or key in self.granted_keywords def label(self) -> str: - return self.card.name + # Log text is shown to both stations — never name a hidden B-SIDE. + return "Hidden B-SIDE" if self.hidden else self.card.name class Player: @@ -109,6 +110,8 @@ def __init__(self, deck1: list[Card], deck2: list[Card], self.resolving: set[int] = set() self.last_track_stack: list[CardInstance] = [] self.winner: int | None = None + # "signal" | "concede" | "timeout" | "disconnect" once the game ends. + self.end_reason: str | None = None self.sleeves = sleeves if sleeves is not None else load_manifest() self.avatars = avatars if avatars is not None else load_avatars() self.players = [Player(0, deck1, self), Player(1, deck2, self)] @@ -439,12 +442,28 @@ def check_win(self) -> None: elif self.players[0].signal <= 0: self.winner = 1 if self.winner is not None: + self.end_reason = "signal" self.log_line( f"Station {self.winner + 1} cuts the rival off the air.", kind="win", station=self.winner, ) + def forfeit(self, station: int, reason: str) -> None: + """End the game with `station` losing for a non-Signal `reason` + (concede / timeout / disconnect). No-op once the game is over.""" + if self.game_over: + return + if station not in (0, 1): + raise ValueError("no such station") + self.winner = 1 - station + self.end_reason = reason + self.log_line( + f"Station {station + 1} goes off the air ({reason}).", + kind="win", + station=self.winner, + ) + def status(self) -> str: return (f"Turn {self.turn} | Station {self.cur.index + 1} | " f"Signal {self.players[0].signal}/{MAX_SIGNAL} vs {self.players[1].signal}/{MAX_SIGNAL} | " diff --git a/sunder/server/app.py b/sunder/server/app.py index 91dab22..5bcf513 100644 --- a/sunder/server/app.py +++ b/sunder/server/app.py @@ -8,6 +8,9 @@ from __future__ import annotations import json +import math +import os +from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect @@ -19,6 +22,7 @@ from ..lore import rules_text from ..schema import load_card_file from ..sleeves import load_manifest +from .lobby import Connection, Lobby, LobbyError from .match import BotSeat, HumanSeat, MatchRoom SERVER_DIR = Path(__file__).parent @@ -45,14 +49,51 @@ def _card_json(c) -> dict: } -def create_app(decks=None, ai_think: float = 1.4, ai_delay: float = 1.4) -> FastAPI: +def _env_seconds(name: str, default: float | None) -> float | None: + """Read a duration from the environment; `0`/`off` disables the clock.""" + raw = os.environ.get(name) + if raw is None or raw.strip() == "": + return default + if raw.strip().lower() in ("0", "off", "none"): + return None + try: + seconds = float(raw) + except ValueError: + return default + if not math.isfinite(seconds) or seconds < 0: + return default + return seconds if seconds else None + + +def create_app(decks=None, ai_think: float = 1.4, ai_delay: float = 1.4, *, + turn_seconds: float | None = None, grace_seconds: float | None = None, + afk_limit: int = 3, finished_ttl: float = 300) -> FastAPI: """Build the app. `ai_think`/`ai_delay` are the base seconds for the rival's thinking pause and per-action delay (randomized around them); - pass 0 to make AI turns instant (tests).""" + pass 0 to make AI turns instant (tests). + + PvP clocks (docs/multiplayer.md): `turn_seconds` (default 75, env + `SUNDER_TURN_SECONDS`) and `grace_seconds` (default 60, env + `SUNDER_GRACE_SECONDS`). Pass/set `0` to disable a clock.""" decks = tuple(decks) if decks else default_decks() sleeves = load_manifest() avatars = load_avatars() - app = FastAPI(title="SUNDER", docs_url="/api/docs") + if turn_seconds is None: + turn_seconds = _env_seconds("SUNDER_TURN_SECONDS", 75) + if grace_seconds is None: + grace_seconds = _env_seconds("SUNDER_GRACE_SECONDS", 60) + lobby = Lobby(decks, sleeves=sleeves, avatars=avatars, + turn_seconds=turn_seconds or None, + grace_seconds=grace_seconds if grace_seconds else None, + afk_limit=afk_limit, finished_ttl=finished_ttl) + + @asynccontextmanager + async def lifespan(_app: FastAPI): + yield + await lobby.shutdown() + + app = FastAPI(title="SUNDER", docs_url="/api/docs", lifespan=lifespan) + app.state.lobby = lobby @app.get("/api/cards") def api_cards(): @@ -150,24 +191,32 @@ async def api_generate(payload: dict): def api_health(): return {"ok": True} + @app.get("/api/rooms/{code}") + def api_room(code: str): + """Public room lookup for invite links — never exposes tokens.""" + code = lobby.normalize(code) + if code in lobby.pending: + return {"code": code, "status": "waiting"} + if code in lobby.live: + over = lobby.live[code].room.gs.game_over + return {"code": code, "status": "over" if over else "live"} + return JSONResponse({"error": "no such room"}, status_code=404) + @app.websocket("/ws") async def ws_endpoint(ws: WebSocket): - """Serve a station-0 human against a bot, replacing the room on restart. - - Reply to invalid JSON, non-object messages, and pre-game actions with - errors; answer pings only after a game starts. Mark the seat disconnected - and cancel its room's bot task when the receive loop exits. Catch - WebSocketDisconnect; other receive-loop errors propagate after cleanup. - """ await ws.accept() - # Single-human server for now: this socket is seat 0 vs a bot seat. - # A PvP lobby will build the same MatchRoom with two HumanSeats. - seat = HumanSeat(0, ws) - room: MatchRoom | None = None + conn = Connection(ws) + + async def send(payload: dict) -> None: + await ws.send_text(json.dumps(payload)) async def send_error(message: str) -> None: - """Send an error response to this socket's human seat.""" - await seat.send({"type": "error", "message": message}) + await send({"type": "error", "message": message}) + + async def end_bot_room() -> None: + if conn.room is not None and conn.entry is None: + await conn.room.close() + conn.clear() try: while True: @@ -182,32 +231,71 @@ async def send_error(message: str) -> None: continue mtype = msg.get("type") - if mtype == "start" or mtype == "restart": - if room is not None: - await room.close() - gs = GameState(*decks, seed=msg.get("seed"), - sleeves=sleeves, avatars=avatars) - gs.start_game() - room = MatchRoom(gs, [seat, BotSeat(1, think=ai_think, delay=ai_delay)]) - await room.send_state(seat) - room.kick() - - elif room is None: - await send_error("send {type:start} first") - - elif mtype == "ping": - await seat.send({"type": "pong"}) - - else: - err = await room.handle(seat, msg, sleeves=sleeves, avatars=avatars) - if err: - await send_error(err) + try: + if mtype == "ping": + await send({"type": "pong"}) + + elif mtype in ("start", "restart"): + # Practice match vs the bot. Never silently abandons a + # live PvP match — that needs an explicit concede/leave. + if conn.in_live_pvp: + await send_error("you're in a PvP match — concede or leave first") + continue + await lobby.leave(conn) + await end_bot_room() + gs = GameState(*decks, seed=msg.get("seed"), + sleeves=sleeves, avatars=avatars) + gs.start_game() + human = HumanSeat(0, ws) + conn.room, conn.seat = MatchRoom( + gs, [human, BotSeat(1, think=ai_think, delay=ai_delay)]), 0 + await conn.room.send_state(human) + conn.room.start() + + elif mtype == "create_room": + if conn.in_live_pvp: + await send_error("you're in a PvP match — concede or leave first") + continue + await lobby.leave(conn) + await end_bot_room() + pr = lobby.create(conn) + await send(lobby.room_msg(pr.code, None, None, "waiting")) + + elif mtype == "join_room": + if conn.in_live_pvp: + await send_error("you're in a PvP match — concede or leave first") + continue + code = lobby.check_joinable(conn, msg.get("code")) + await lobby.leave(conn) + await end_bot_room() + await lobby.join(conn, code) + + elif mtype == "resume": + await end_bot_room() + if conn.pending is not None: + lobby.cancel_pending(conn) + await lobby.resume(conn, msg.get("code"), msg.get("token")) + + elif mtype == "leave_room": + await lobby.leave(conn) + await end_bot_room() + await send({"type": "room_closed", "reason": "left"}) + + elif conn.room is None: + await send_error("send {type:start} first") + + else: + err = await conn.room.handle(conn.room.seats[conn.seat], msg, + sleeves=sleeves, avatars=avatars) + if err: + await send_error(err) + except LobbyError as exc: + await send_error(str(exc)) except WebSocketDisconnect: return finally: - seat.connected = False - if room is not None: - await room.close() + await lobby.disconnect(conn) + await end_bot_room() if DIST_DIR.exists(): app.mount("/", StaticFiles(directory=str(DIST_DIR), html=True), name="spa") diff --git a/sunder/server/lobby.py b/sunder/server/lobby.py new file mode 100644 index 0000000..f38c632 --- /dev/null +++ b/sunder/server/lobby.py @@ -0,0 +1,246 @@ +"""SUNDER — PvP lobby: invite-code rooms, seat tokens, resume. + +In-memory and single-process by design (Phase 1). Each WebSocket gets a +`Connection`; the lobby moves connections between three places: + + nothing ──create──▶ PendingRoom (host waiting, has an invite code) + PendingRoom ──join──▶ LiveEntry (MatchRoom with two HumanSeats) + LiveEntry ──resume(code, token)──▶ re-attach a dropped seat + +Seat tokens are bearer secrets (`secrets.token_urlsafe`) handed only to the +seat's owner; anyone holding one can play that seat, so the client keeps it +in `sessionStorage` (per tab) and never shows it. Codes are short and +shareable, tokens are not. See docs/multiplayer.md. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import hmac +import json +import secrets +from dataclasses import dataclass, field + +from ..game import GameState +from .match import HumanSeat, MatchRoom + +# No 0/O/1/I/L — codes get read aloud and typed on phones. +CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" +CODE_LENGTH = 6 + + +class LobbyError(Exception): + """A user-facing lobby failure (message is safe to send to the client).""" + + +@dataclass(eq=False) +class Connection: + """Per-socket routing state. Exactly one of `room`/`pending` (or neither).""" + + ws: object + room: MatchRoom | None = None + seat: int | None = None + pending: "PendingRoom | None" = None + entry: "LiveEntry | None" = None + + @property + def in_live_pvp(self) -> bool: + return (self.entry is not None and self.room is not None + and not self.room.gs.game_over) + + def clear(self) -> None: + self.room = self.seat = self.pending = self.entry = None + + +@dataclass(eq=False) +class PendingRoom: + code: str + host: Connection + host_token: str + + +@dataclass(eq=False) +class LiveEntry: + code: str + room: MatchRoom + tokens: dict[int, str] + conns: dict[int, Connection | None] = field(default_factory=dict) + reaper: asyncio.Task | None = None + + +class Lobby: + def __init__(self, decks, *, sleeves: dict, avatars: dict, + turn_seconds: float | None = 75, grace_seconds: float | None = 60, + afk_limit: int = 3, finished_ttl: float = 300, max_rooms: int = 200): + self.decks = decks + self.sleeves = sleeves + self.avatars = avatars + self.turn_seconds = turn_seconds + self.grace_seconds = grace_seconds + self.afk_limit = afk_limit + self.finished_ttl = finished_ttl + self.max_rooms = max_rooms + self.pending: dict[str, PendingRoom] = {} + self.live: dict[str, LiveEntry] = {} + + # ------------------------------------------------------------ helpers + + def _new_code(self) -> str: + for _ in range(100): + code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LENGTH)) + if code not in self.pending and code not in self.live: + return code + raise LobbyError("could not allocate a room code") # pragma: no cover + + @staticmethod + def normalize(code) -> str: + return str(code or "").strip().upper() + + @staticmethod + def room_msg(code: str, seat: int | None, token: str | None, status: str) -> dict: + return {"type": "room", "mode": "pvp", "code": code, "seat": seat, + "token": token, "status": status} + + # ------------------------------------------------------------ create / join + + def create(self, conn: Connection) -> PendingRoom: + if len(self.pending) + len(self.live) >= self.max_rooms: + raise LobbyError("server is full — try again in a bit") + self.cancel_pending(conn) + pr = PendingRoom(self._new_code(), conn, secrets.token_urlsafe(16)) + self.pending[pr.code] = pr + conn.pending = pr + return pr + + def cancel_pending(self, conn: Connection) -> None: + pr = conn.pending + if pr is not None and self.pending.get(pr.code) is pr: + del self.pending[pr.code] + conn.pending = None + + def check_joinable(self, conn: Connection, code) -> str: + """Validate a join without side effects; returns the normalized code.""" + code = self.normalize(code) + pr = self.pending.get(code) + if pr is None: + raise LobbyError("no such room" if code not in self.live else "room is full") + if pr.host is conn: + raise LobbyError("that's your own room — share the code with a rival") + return code + + async def join(self, conn: Connection, code) -> LiveEntry: + code = self.check_joinable(conn, code) + pr = self.pending[code] + del self.pending[code] + pr.host.pending = None + + # Seat order is random so the host doesn't always move first. The + # seed is server-only: a client-chosen seed would leak the shuffle. + host_seat = secrets.randbelow(2) + guest_seat = 1 - host_seat + gs = GameState(*self.decks, seed=secrets.randbits(64), + sleeves=self.sleeves, avatars=self.avatars) + gs.start_game() + tokens = {host_seat: pr.host_token, guest_seat: secrets.token_urlsafe(16)} + entry = LiveEntry(code, None, tokens) # type: ignore[arg-type] + room = MatchRoom( + gs, + [HumanSeat(host_seat, pr.host.ws), HumanSeat(guest_seat, conn.ws)], + code=code, turn_seconds=self.turn_seconds, grace_seconds=self.grace_seconds, + afk_limit=self.afk_limit, on_end=lambda _room: self._schedule_reap(entry), + ) + entry.room = room + entry.conns = {host_seat: pr.host, guest_seat: conn} + self.live[code] = entry + for seat, c in entry.conns.items(): + c.clear() + c.room, c.seat, c.entry = room, seat, entry + await room.seats[seat].send(self.room_msg(code, seat, tokens[seat], "live")) + await room.broadcast() + room.start() + return entry + + # ------------------------------------------------------------ resume / leave + + async def resume(self, conn: Connection, code, token) -> LiveEntry: + code = self.normalize(code) + entry = self.live.get(code) + if entry is None or not isinstance(token, str): + raise LobbyError("that match is no longer running") + seat = next((s for s, t in entry.tokens.items() + if hmac.compare_digest(t, token)), None) + if seat is None: + raise LobbyError("that match is no longer running") + old = entry.conns.get(seat) + if old is not None and old is not conn: + # Same seat opened in another tab/device: last one wins. + old_ws = old.ws + old.clear() + with contextlib.suppress(Exception): + await old_ws.send_text(json.dumps( + {"type": "room_closed", "reason": "resumed elsewhere"})) + conn.clear() + conn.room, conn.seat, conn.entry = entry.room, seat, entry + entry.conns[seat] = conn + status = "over" if entry.room.gs.game_over else "live" + seat_obj = entry.room.seats[seat] + seat_obj.ws = conn.ws + await seat_obj.send(self.room_msg(code, seat, entry.tokens[seat], status)) + await entry.room.attach(seat, conn.ws) + return entry + + async def leave(self, conn: Connection) -> None: + """Leave whatever PvP state `conn` is in. A live match is conceded.""" + if conn.pending is not None: + self.cancel_pending(conn) + entry, seat = conn.entry, conn.seat + if entry is not None and seat is not None: + room = entry.room + if not room.gs.game_over: + await room.concede(room.seats[seat]) + await self._drop(entry, seat, conn) + conn.clear() + + async def disconnect(self, conn: Connection) -> None: + """Socket closed. Pending rooms vanish; live seats start their grace.""" + if conn.pending is not None: + self.cancel_pending(conn) + entry, seat = conn.entry, conn.seat + if entry is not None and seat is not None: + await self._drop(entry, seat, conn) + conn.clear() + + async def _drop(self, entry: LiveEntry, seat: int, conn: Connection) -> None: + if entry.conns.get(seat) is not conn: + return + entry.conns[seat] = None + await entry.room.detach(seat, conn.ws) + if entry.room.gs.game_over and not any(entry.conns.values()): + await self._reap(entry) + + # ------------------------------------------------------------ cleanup + + def _schedule_reap(self, entry: LiveEntry) -> None: + if entry.reaper is None: + entry.reaper = asyncio.create_task(self._reap_later(entry)) + + async def _reap_later(self, entry: LiveEntry) -> None: + await asyncio.sleep(self.finished_ttl) + await self._reap(entry) + + async def _reap(self, entry: LiveEntry) -> None: + if self.live.get(entry.code) is entry: + del self.live[entry.code] + for c in entry.conns.values(): + if c is not None and c.entry is entry: + c.clear() + task, entry.reaper = entry.reaper, None + if task and task is not asyncio.current_task() and not task.done(): + task.cancel() + await entry.room.close() + + async def shutdown(self) -> None: + for entry in list(self.live.values()): + await self._reap(entry) + self.pending.clear() diff --git a/sunder/server/match.py b/sunder/server/match.py index 122d248..db3dd74 100644 --- a/sunder/server/match.py +++ b/sunder/server/match.py @@ -1,15 +1,22 @@ -"""SUNDER — match rooms: one GameState, N seats, server-authoritative actions. +"""SUNDER — match rooms: one GameState, two seats, server-authoritative actions. A `MatchRoom` owns a `GameState` and the seats that play it. Every action names the seat that sent it, and the room checks it against that seat's station, never against a hard-coded `0`. Seats are pluggable: -* `HumanSeat` — a WebSocket. Receives viewer-aware snapshots for its station. +* `HumanSeat` — a WebSocket (detachable: a dropped socket leaves the seat + empty until the player resumes). Receives viewer-aware snapshots. * `BotSeat` — the heuristic AI (`ai.iter_turn`), run as a background task so the room (and any human socket) stays responsive during its turn. -Today the server builds a room as Human(0) vs Bot(1). A PvP room is the same -class with two `HumanSeat`s; no engine or snapshot changes needed. +PvP rooms (two `HumanSeat`s) also run clocks — see docs/multiplayer.md: + +* turn timer: `turn_seconds` per turn; on expiry the turn is ended for the + player, and `afk_limit` consecutive expiries forfeit (`"timeout"`). +* disconnect grace: a seat that stays detached for `grace_seconds` while + the game is live forfeits (`"disconnect"`). + +All `GameState` mutation happens under `room.lock`. """ from __future__ import annotations @@ -19,6 +26,8 @@ class with two `HumanSeat`s; no engine or snapshot changes needed. import json import logging import random +import time +from typing import Awaitable, Callable from .. import ai as ai_mod from ..game import GameState @@ -29,7 +38,6 @@ class with two `HumanSeat`s; no engine or snapshot changes needed. def _needs_target(inst) -> bool: - """Return whether any card ability uses CHOSEN or ENEMY_BROADCAST targeting.""" # Mirrors state.hand_view's `needs_target`. return any(ab.target in (Target.CHOSEN, Target.ENEMY_BROADCAST) for ab in inst.card.abilities) @@ -41,39 +49,41 @@ class Seat: is_bot = False def __init__(self, index: int): - """Assign a station, raising ValueError unless `index` is 0 or 1.""" if index not in (0, 1): raise ValueError("seat index must be 0 or 1") self.index = index + @property + def connected(self) -> bool: + return True + async def send(self, payload: dict) -> None: # pragma: no cover - interface - """Deliver a server message; the base implementation raises NotImplementedError.""" raise NotImplementedError class HumanSeat(Seat): - """A seat backed by a WebSocket. Sends are serialized per socket, so the - bot task and the receive loop never interleave a frame.""" + """A seat backed by a WebSocket. Sends are serialized per seat, so the + bot task, clocks and the receive loop never interleave a frame.""" - def __init__(self, index: int, ws): - """Bind a WebSocket to a station, raising ValueError for an invalid index.""" + def __init__(self, index: int, ws=None): super().__init__(index) self.ws = ws - self.connected = True self._send_lock = asyncio.Lock() - async def send(self, payload: dict) -> None: - """Send JSON with serialized socket access, skipping disconnected seats. + @property + def connected(self) -> bool: + return self.ws is not None - Catch serialization or send exceptions and mark the seat disconnected. - """ - if not self.connected: + async def send(self, payload: dict) -> None: + ws = self.ws + if ws is None: return async with self._send_lock: try: - await self.ws.send_text(json.dumps(payload)) - except Exception: # socket gone mid-send; the receive loop will notice - self.connected = False + await ws.send_text(json.dumps(payload)) + except Exception: # socket gone mid-send; its receive loop will detach + if self.ws is ws: + self.ws = None class BotSeat(Seat): @@ -82,88 +92,109 @@ class BotSeat(Seat): is_bot = True def __init__(self, index: int, think: float = 1.4, delay: float = 1.4): - """Set base thinking and action delays in seconds; zero skips the pauses. - - Raise ValueError unless `index` is 0 or 1. - """ super().__init__(index) self.think = think self.delay = delay async def send(self, payload: dict) -> None: - """Ignore server messages; the bot reads the game state directly.""" return None # the bot reads the GameState directly async def play_turn(self, room: "MatchRoom") -> None: - """Play a paced AI turn, broadcasting after each action and turn completion. - - Stop if the room's game changes, the game ends, or this station loses - the turn. Cancellation and errors from AI actions or broadcasts propagate. - """ gs = room.gs await asyncio.sleep(self.think * random.uniform(0.8, 1.2)) steps = ai_mod.iter_turn(gs) while True: async with room.lock: - if room.gs is not gs or gs.game_over or gs.current != self.index: + if gs.game_over or gs.current != self.index: return try: next(steps) done = False except StopIteration: # iter_turn ended the turn (or the game) done = True + room._after_change() await room.broadcast() if done: return await asyncio.sleep(self.delay * random.uniform(0.6, 1.3)) -class MatchRoom: - def __init__(self, gs: GameState, seats: list[Seat]): - """Manage `gs` with one seat per station, without starting the game or bot. +OnEnd = Callable[["MatchRoom"], Awaitable[None] | None] - Raise ValueError unless the seats' indices are exactly 0 and 1. - """ + +class MatchRoom: + def __init__(self, gs: GameState, seats: list[Seat], *, code: str | None = None, + turn_seconds: float | None = None, grace_seconds: float | None = None, + afk_limit: int = 3, on_end: OnEnd | None = None): if sorted(s.index for s in seats) != [0, 1]: raise ValueError("a room needs exactly one seat per station") self.gs = gs self.seats: dict[int, Seat] = {s.index: s for s in seats} + self.code = code + self.turn_seconds = turn_seconds + self.grace_seconds = grace_seconds + self.afk_limit = max(1, afk_limit) + self.on_end = on_end self.lock = asyncio.Lock() self._bot_task: asyncio.Task | None = None + self._clock_task: asyncio.Task | None = None + self._clock_key: tuple[int, int] | None = None + self._deadline: float | None = None # time.monotonic() + self._grace: dict[int, asyncio.Task] = {} + self._timeouts = {0: 0, 1: 0} + self._ended = False + self.closed = False + + @property + def mode(self) -> str: + return "bot" if any(s.is_bot for s in self.seats.values()) else "pvp" # ------------------------------------------------------------ output - async def send_state(self, seat: Seat) -> None: - """Send a snapshot from the seat's perspective, hiding the opponent's hand. + def meta(self, seat: Seat) -> dict: + """Per-seat match info that rides next to each snapshot.""" + foe = self.seats[1 - seat.index] + remaining = None + if self._deadline is not None and not self.gs.game_over: + remaining = round(max(0.0, self._deadline - time.monotonic()), 2) + return { + "mode": self.mode, + "code": self.code, + "seat": seat.index, + "opponent_connected": foe.connected, + "turn_seconds": self.turn_seconds if self.mode == "pvp" else None, + "turn_remaining": remaining, + } - Snapshot and seat-send errors propagate unless the seat handles them. - """ - await seat.send({"type": "state", "snapshot": snapshot(self.gs, viewer=seat.index)}) + async def send_state(self, seat: Seat) -> None: + await seat.send({"type": "state", + "snapshot": snapshot(self.gs, viewer=seat.index), + "match": self.meta(seat)}) async def broadcast(self) -> None: - """Send each seat its own state view; stop and propagate any send_state error.""" for seat in self.seats.values(): await self.send_state(seat) # ------------------------------------------------------------ lifecycle + def start(self) -> None: + """Arm clocks and start the bot if it moves first. Call once, after + the initial state has been sent.""" + self._after_change() + self.kick() + def kick(self) -> None: """Start the bot if it is a bot's turn and it isn't already running.""" - if self.gs.game_over: + if self.gs.game_over or self.closed: return seat = self.seats[self.gs.current] if seat.is_bot and (self._bot_task is None or self._bot_task.done()): - self._bot_task = asyncio.create_task(self._run_bot(seat)) - - async def _run_bot(self, seat: BotSeat) -> None: - """Run consecutive bot turns until game over, a human turn, or no progress. + self._bot_task = asyncio.create_task(self._run_bot()) - Stop if the room's game changes. Bot-turn exceptions end the loop; - cancellation propagates. - """ + async def _run_bot(self) -> None: # Loop so bot-vs-bot rooms (tests, future spectating) keep going. gs = self.gs - while not gs.game_over and self.gs is gs: + while not gs.game_over and not self.closed: seat = self.seats[gs.current] if not seat.is_bot: return @@ -178,41 +209,129 @@ async def _run_bot(self, seat: BotSeat) -> None: if (gs.turn, gs.current) == before: # no progress — never spin return - async def close(self) -> None: - """Cancel and await an active bot task, clearing the room's task reference. + def _after_change(self) -> None: + """Call under the lock after any mutation: re-arms the turn clock on + a new turn, and fires `on_end` exactly once when the game ends.""" + gs = self.gs + if gs.game_over: + self._stop_clock() + for st in list(self._grace): + self._cancel_grace(st) + if not self._ended: + self._ended = True + if self.on_end is not None: + res = self.on_end(self) + if asyncio.iscoroutine(res): + asyncio.create_task(res) + return + # Clocks are a PvP courtesy to the rival; practice vs the bot is untimed. + if not self.turn_seconds or self.mode != "pvp": + self._stop_clock() + return + key = (gs.turn, gs.current) + if key != self._clock_key: + self._stop_clock() + self._clock_key = key + self._deadline = time.monotonic() + self.turn_seconds + self._clock_task = asyncio.create_task(self._turn_clock(key)) + + def _stop_clock(self) -> None: + task, self._clock_task = self._clock_task, None + self._clock_key = None + self._deadline = None + if task and task is not asyncio.current_task() and not task.done(): + task.cancel() - Suppress cancellation; other errors from the awaited task propagate. - """ - task, self._bot_task = self._bot_task, None - if task and not task.done(): + async def _turn_clock(self, key: tuple[int, int]) -> None: + await asyncio.sleep(self.turn_seconds) + async with self.lock: + gs = self.gs + if gs.game_over or (gs.turn, gs.current) != key: + return + st = gs.current + self._timeouts[st] += 1 + if self._timeouts[st] >= self.afk_limit: + gs.forfeit(st, "timeout") + else: + gs.log_line(f"Station {st + 1} ran out of time.", kind="system", station=st) + gs.end_turn() + self._after_change() + await self.broadcast() + self.kick() + + # ------------------------------------------------------------ connections + + async def attach(self, index: int, ws) -> None: + seat = self.seats[index] + if not isinstance(seat, HumanSeat): + raise ValueError("not a human seat") + seat.ws = ws + self._cancel_grace(index) + await self.broadcast() + + async def detach(self, index: int, ws=None) -> None: + """Drop seat `index`'s socket unless a different socket is attached. + In a live PvP game this starts the disconnect grace clock.""" + seat = self.seats[index] + if not isinstance(seat, HumanSeat): + return + if ws is not None and seat.ws is not None and seat.ws is not ws: + return + seat.ws = None + if self.mode == "pvp" and not self.gs.game_over and self.grace_seconds is not None: + self._cancel_grace(index) + self._grace[index] = asyncio.create_task(self._grace_clock(index)) + await self.broadcast() + + def _cancel_grace(self, index: int) -> None: + task = self._grace.pop(index, None) + if task and task is not asyncio.current_task() and not task.done(): task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await task + + async def _grace_clock(self, index: int) -> None: + await asyncio.sleep(self.grace_seconds) + async with self.lock: + self._grace.pop(index, None) + if self.gs.game_over or self.seats[index].connected: + return + self.gs.forfeit(index, "disconnect") + self._after_change() + await self.broadcast() + + async def close(self) -> None: + """Cancel every background task (bot, clocks). Idempotent.""" + self.closed = True + tasks = [self._bot_task, self._clock_task, *self._grace.values()] + self._bot_task = self._clock_task = None + self._grace.clear() + self._deadline = None + me = asyncio.current_task() + for task in tasks: + if task and task is not me and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task # ------------------------------------------------------------ input def _my_turn(self, seat: Seat) -> bool: - """Return whether this seat controls the current station in an unfinished game.""" return not self.gs.game_over and self.gs.current == seat.index + async def concede(self, seat: Seat) -> str | None: + async with self.lock: + if self.gs.game_over: + return "game over" + self.gs.forfeit(seat.index, "concede") + self._after_change() + await self.broadcast() + return None + async def handle(self, seat: Seat, msg: dict, *, sleeves: dict, avatars: dict) -> str | None: - """Apply a seat's play, attack, end-turn, or cosmetic message. - - `hand` and `board` select list positions; card targets use serials, - with 'face' selecting the rival station for attacks. Ignore targets - on untargeted cards. `sleeves` and `avatars` supply allowed cosmetic IDs. - Cosmetics may change out of turn, including after game over. - - Return an error string for the caller to send to this seat. KeyError, - TypeError, ValueError, and IndexError during plays or attacks are - converted to error strings; other errors, including unhandled snapshot - or seat-send errors, propagate. Returned errors do not trigger a broadcast. - - Otherwise broadcast state, start any pending bot turn, and return None. - Stale or out-of-turn end-turn messages also take this path without - advancing the turn; valid end-turn messages must match `gs.turn`. - """ + """Apply one client message for `seat`. Returns an error message for + that seat only, or None on success (state is then broadcast).""" mtype = msg.get("type") + if mtype == "concede": + return await self.concede(seat) async with self.lock: gs = self.gs me = gs.players[seat.index] @@ -237,6 +356,7 @@ async def handle(self, seat: Seat, msg: dict, *, sleeves: dict, avatars: dict) - gs.play_card(idx, chosen) except (KeyError, TypeError, ValueError, IndexError) as exc: return str(exc) or "bad play" + self._timeouts[seat.index] = 0 elif mtype == "attack": if not self._my_turn(seat): @@ -254,12 +374,14 @@ async def handle(self, seat: Seat, msg: dict, *, sleeves: dict, avatars: dict) - gs.attack(attacker, t) except (KeyError, TypeError, ValueError, IndexError) as exc: return str(exc) or "bad attack" + self._timeouts[seat.index] = 0 elif mtype == "end_turn": # Stale/duplicate end_turns are ignored but still answered with # a fresh state, so the client can resync. if self._my_turn(seat) and msg.get("turn") == gs.turn: gs.end_turn() + self._timeouts[seat.index] = 0 elif mtype == "set_sleeve": sid = msg.get("sleeve") @@ -276,6 +398,7 @@ async def handle(self, seat: Seat, msg: dict, *, sleeves: dict, avatars: dict) - else: return f"unknown type {mtype!r}" + self._after_change() await self.broadcast() self.kick() return None diff --git a/sunder/state.py b/sunder/state.py index fde35c2..9d80d34 100644 --- a/sunder/state.py +++ b/sunder/state.py @@ -116,6 +116,7 @@ def snapshot(gs: GameState, viewer: int = 0) -> dict: "current": gs.current, "phase": gs.phase, "winner": gs.winner, + "end_reason": gs.end_reason, "status": gs.status(), "viewer": viewer, "can_act": gs.winner is None and gs.current == viewer, diff --git a/tests/test_pvp.py b/tests/test_pvp.py new file mode 100644 index 0000000..2a09824 --- /dev/null +++ b/tests/test_pvp.py @@ -0,0 +1,499 @@ +"""Phase 1 — live PvP: forfeits, clocks, hidden-info, lobby + WS protocol.""" + +import asyncio +import contextlib +import json +import time +from unittest.mock import AsyncMock + +import pytest +from fastapi.testclient import TestClient + +from sunder.game import GameState +from sunder.server.app import _env_seconds, create_app, default_decks +from sunder.server.lobby import CODE_ALPHABET, CODE_LENGTH +from sunder.server.match import HumanSeat, MatchRoom, Seat +from sunder.state import snapshot +from tests.conftest import card, make_gs, put_board, put_hand + + +@pytest.mark.parametrize("raw", [None, "", " ", "bad", "-1", "nan", "NaN", + "inf", "-inf", "Infinity", "1e309"]) +@pytest.mark.parametrize("default", [75, None]) +def test_env_seconds_falls_back(monkeypatch, raw, default): + if raw is None: + monkeypatch.delenv("SUNDER_TURN_SECONDS", raising=False) + else: + monkeypatch.setenv("SUNDER_TURN_SECONDS", raw) + assert _env_seconds("SUNDER_TURN_SECONDS", default) == default + + +@pytest.mark.parametrize("raw, expected", [ + ("0", None), ("0.0", None), ("-0.0", None), (" OFF ", None), ("none", None), + ("0.25", 0.25), (" 75 ", 75), ("1e2", 100), +]) +def test_env_seconds_accepts_disabled_and_positive_values(monkeypatch, raw, expected): + monkeypatch.setenv("SUNDER_TURN_SECONDS", raw) + assert _env_seconds("SUNDER_TURN_SECONDS", 60) == expected + +# ---------------------------------------------------------------- engine + + +def _gs(seed=1): + gs = GameState(*default_decks(), seed=seed) + gs.start_game() + return gs + + +def test_forfeit_sets_winner_and_reason(): + gs = _gs() + gs.forfeit(0, "concede") + assert gs.winner == 1 and gs.end_reason == "concede" and gs.game_over + gs.forfeit(1, "timeout") # no-op once over + assert gs.winner == 1 and gs.end_reason == "concede" + assert snapshot(gs, 0)["end_reason"] == "concede" + + +def test_signal_win_reason(): + gs = _gs() + gs.players[1].signal = 0 + gs.check_win() + assert gs.end_reason == "signal" + + +def test_forfeit_rejects_bad_station(): + with pytest.raises(ValueError): + _gs().forfeit(2, "concede") + + +def test_hidden_bside_name_never_logged(): + """Regression: AoE damage/death lines used to print a hidden B-SIDE's name.""" + gs = make_gs() + put_board(gs, 1, card(name="Deep Secret", stats={"atk": 1, "def": 1}, keywords=["B_SIDE"])) + gs.players[1].board[0].hidden = True + put_hand(gs, 0, card(name="Wipe", type="TRACK", stats=None, abilities=[ + {"trigger": "ON_PLAY", "effect": "DEAL_DAMAGE", "target": "ALL_ENEMY_BROADCASTS", + "value": 2}])) + gs.cur.bandwidth = 5 + gs.play_card(0) + s = snapshot(gs, viewer=0) + text = " ".join(s["log"]) + " ".join(e["text"] for e in s["history"]) + assert "Deep Secret" not in text + assert "Hidden B-SIDE goes silent." in s["log"] + + +def test_revealed_bside_is_named_again(): + gs = make_gs() + put_board(gs, 1, card(name="Deep Secret", keywords=["B_SIDE"])) + inst = gs.players[1].board[0] + inst.hidden = True + assert inst.label() == "Hidden B-SIDE" + inst.hidden = False + assert inst.label() == "Deep Secret" + + +# ---------------------------------------------------------------- room clocks + + +class FakeSocket: + def __init__(self, inbox): + self.inbox = inbox + + async def send_text(self, text): + self.inbox.append(json.loads(text)) + + +class FakeSeat(HumanSeat): + """A HumanSeat with an in-memory socket, using the real send path.""" + + def __init__(self, index): + self.inbox = [] + super().__init__(index, ws=FakeSocket(self.inbox)) + + @property + def last(self): + return [m for m in self.inbox if m["type"] == "state"][-1] + + +def _room(**kw): + gs = _gs() + a, b = FakeSeat(0), FakeSeat(1) + return gs, MatchRoom(gs, [a, b], **kw), a, b + + +def test_meta_rides_with_each_state(): + gs, room, a, b = _room(code="ABCDEF", turn_seconds=30) + + async def go(): + room.start() + await room.broadcast() + await room.close() + asyncio.run(go()) + m = a.last["match"] + assert m["mode"] == "pvp" and m["code"] == "ABCDEF" and m["seat"] == 0 + assert m["opponent_connected"] is True and m["turn_seconds"] == 30 + assert 0 < m["turn_remaining"] <= 30 + assert b.last["match"]["seat"] == 1 + + +def test_turn_timer_ends_turn_then_forfeits_afk(): + gs, room, a, b = _room(turn_seconds=0.1, afk_limit=2) + + async def go(): + room.start() + await asyncio.sleep(0.15) # t=0.10 seat 0 times out once → turn passes + assert gs.current == 1 and not gs.game_over + await asyncio.sleep(0.10) # t=0.20 seat 1 times out once + assert gs.current == 0 and not gs.game_over + await asyncio.sleep(0.10) # t=0.30 seat 0's second strike → forfeit + await room.close() + asyncio.run(go()) + assert gs.winner == 1 and gs.end_reason == "timeout" + + +def test_acting_resets_afk_strikes(): + gs, room, a, b = _room(turn_seconds=0.1, afk_limit=2) + + async def go(): + room.start() + await asyncio.sleep(0.25) # seat 0 strike 1 (t=.1), seat 1 strike 1 (t=.2) + assert gs.current == 0 and room._timeouts == {0: 1, 1: 1} + await room.handle(a, {"type": "end_turn", "turn": gs.turn}, sleeves={}, avatars={}) + assert room._timeouts[0] == 0 + await room.handle(b, {"type": "end_turn", "turn": gs.turn}, sleeves={}, avatars={}) + await asyncio.sleep(0.15) # seat 0 times out — strike 1 again, not 2 + assert room._timeouts[0] == 1 + await room.close() + asyncio.run(go()) + assert not gs.game_over + + +def test_turn_clock_restarts_each_turn(): + gs, room, a, b = _room(turn_seconds=10) + + async def go(): + room.start() + first = room._deadline + await asyncio.sleep(0.02) + await room.handle(a, {"type": "end_turn", "turn": 1}, sleeves={}, avatars={}) + assert room._deadline > first + await room.close() + asyncio.run(go()) + + +def test_disconnect_grace_forfeits(): + gs, room, a, b = _room(grace_seconds=0.05) + + async def go(): + await room.detach(1) + assert a.last["match"]["opponent_connected"] is False + await asyncio.sleep(0.12) + await room.close() + asyncio.run(go()) + assert gs.winner == 0 and gs.end_reason == "disconnect" + + +def test_send_failure_still_starts_disconnect_grace(monkeypatch): + gs, room, a, b = _room(grace_seconds=0.01) + ws = b.ws + failed_send = AsyncMock(side_effect=RuntimeError("socket closed")) + monkeypatch.setattr(ws, "send_text", failed_send) + + async def go(): + try: + await room.broadcast() + failed_send.assert_awaited_once() + assert b.ws is None + a.inbox.clear() + await room.detach(1, ws) + assert a.last["match"]["opponent_connected"] is False + await asyncio.wait_for(room._grace[1], timeout=1) + assert a.last["snapshot"]["winner"] == 0 + assert a.last["snapshot"]["end_reason"] == "disconnect" + finally: + await room.close() + asyncio.run(go()) + assert gs.winner == 0 and gs.end_reason == "disconnect" + + +def test_detach_old_socket_keeps_current_connection(): + gs, room, a, b = _room(grace_seconds=0.01) + old_ws = b.ws + new_ws = FakeSocket(b.inbox) + + async def go(): + try: + await room.attach(1, new_ws) + a.inbox.clear() + await room.detach(1, old_ws) + assert b.ws is new_ws + assert not room._grace and not a.inbox + assert not gs.game_over + finally: + await room.close() + asyncio.run(go()) + + +def test_reconnect_within_grace_keeps_game(): + gs, room, a, b = _room(grace_seconds=0.1) + + async def go(): + await room.detach(1) + await asyncio.sleep(0.03) + await room.attach(1, FakeSocket(b.inbox)) + await asyncio.sleep(0.15) + await room.close() + asyncio.run(go()) + assert not gs.game_over + assert a.last["match"]["opponent_connected"] is True + + +def test_concede_any_time_and_on_end_once(): + ended = [] + gs, room, a, b = _room(on_end=lambda r: ended.append(r.gs.winner)) + + async def go(): + assert await room.handle(b, {"type": "concede"}, sleeves={}, avatars={}) is None + assert await room.handle(a, {"type": "concede"}, sleeves={}, avatars={}) == "game over" + asyncio.run(go()) + assert gs.winner == 0 and gs.end_reason == "concede" and ended == [0] + + +def test_no_clocks_in_bot_rooms(): + from sunder.server.match import BotSeat + gs = _gs() + human = FakeSeat(0) + room = MatchRoom(gs, [human, BotSeat(1, 0, 0)], turn_seconds=0.01, grace_seconds=0.01) + + async def go(): + room.start() + await room.detach(0) + await asyncio.sleep(0.05) + await room.close() + asyncio.run(go()) + assert not gs.game_over and gs.current == 0 and room._deadline is None + + +def test_plain_seat_is_always_connected(): + assert Seat(0).connected is True + + +# ---------------------------------------------------------------- WS protocol + + +def _client(**kw): + kw.setdefault("ai_think", 0) + kw.setdefault("ai_delay", 0) + kw.setdefault("turn_seconds", 0) + kw.setdefault("grace_seconds", 0) + return TestClient(create_app(**kw)) + + +def _close(ws): + """Simulate a dropped connection for one side of a `_pair`.""" + ws.close() + + +def _recv(ws, mtype): + """Read until a message of `mtype` arrives (skips interleaved states).""" + for _ in range(50): + m = ws.receive_json() + if m["type"] == mtype: + return m + raise AssertionError(f"no {mtype}") + + +@contextlib.contextmanager +def _pair(tc): + """Open two sockets, host creates, guest joins. + + Yields ({seat: (ws, room_msg, first_state)}, code). Sockets are always + closed on exit, so a failing assertion can't hang the TestClient.""" + with tc.websocket_connect("/ws") as h, tc.websocket_connect("/ws") as g: + h.send_json({"type": "create_room"}) + room = _recv(h, "room") + assert room["status"] == "waiting" and room["token"] is None + code = room["code"] + assert len(code) == CODE_LENGTH and set(code) <= set(CODE_ALPHABET) + g.send_json({"type": "join_room", "code": code.lower()}) # case-insensitive + rh, rg = _recv(h, "room"), _recv(g, "room") + assert rh["status"] == rg["status"] == "live" + assert {rh["seat"], rg["seat"]} == {0, 1} and rh["token"] != rg["token"] + sh, sg = _recv(h, "state"), _recv(g, "state") + yield {rh["seat"]: (h, rh, sh), rg["seat"]: (g, rg, sg)}, code + + +def test_ws_create_join_and_viewer_snapshots(): + with _client() as tc: + with _pair(tc) as (seats, code): + for seat, (_ws, _room, state) in seats.items(): + assert state["snapshot"]["viewer"] == seat + assert state["match"]["mode"] == "pvp" and state["match"]["code"] == code + assert state["snapshot"]["can_act"] is (seat == 0) + assert tc.get(f"/api/rooms/{code}").json() == {"code": code, "status": "live"} + + +def test_ws_turns_alternate_and_out_of_turn_rejected(): + with _client() as tc: + with _pair(tc) as (seats, _): + p0, p1 = seats[0][0], seats[1][0] + p1.send_json({"type": "end_turn", "turn": 1}) + s = _recv(p1, "state") # out-of-turn end_turn just resyncs (both seats) + assert s["snapshot"]["current"] == 0 + _recv(p0, "state") + p1.send_json({"type": "play", "hand": 0}) + assert _recv(p1, "error")["message"] == "not your turn" + p0.send_json({"type": "end_turn", "turn": 1}) + s0, s1 = _recv(p0, "state"), _recv(p1, "state") + assert s1["snapshot"]["can_act"] and not s0["snapshot"]["can_act"] + + +def test_ws_full_pvp_match_terminates(): + """Both seats play the same simple policy until someone wins.""" + with _client() as tc: + with _pair(tc) as (seats, code): + latest = {0: seats[0][2]["snapshot"], 1: seats[1][2]["snapshot"]} + socks = {0: seats[0][0], 1: seats[1][0]} + final = None + for _ in range(600): + cur = latest[0]["current"] + s = latest[cur] + if s["winner"] is not None: + final = s + break + ws = socks[cur] + idx = next((i for i, c in enumerate(s["hand"]) if c["is_playable"] + and (not c["needs_target"] or c["legal_targets"])), None) + if idx is not None: + c = s["hand"][idx] + ws.send_json({"type": "play", "hand": idx, + "target": c["legal_targets"][0] if c["needs_target"] else None}) + else: + att = next((b for b in s["me"]["board"] + if b.get("can_attack") and b.get("attack_targets")), None) + if att: + t = att["attack_targets"][0] + ws.send_json({"type": "attack", "board": s["me"]["board"].index(att), + "target": "face" if t["kind"] == "face" else t["serial"]}) + else: + ws.send_json({"type": "end_turn", "turn": s["turn"]}) + for seat in (0, 1): + msg = _recv(socks[seat], "state") + latest[seat] = msg["snapshot"] + assert final is not None and final["winner"] in (0, 1) + assert final["end_reason"] == "signal" + assert tc.get(f"/api/rooms/{code}").json()["status"] == "over" + + +def test_ws_join_errors(): + with _client() as tc: + with tc.websocket_connect("/ws") as h, tc.websocket_connect("/ws") as x: + x.send_json({"type": "join_room", "code": "ZZZZZZ"}) + assert _recv(x, "error")["message"] == "no such room" + h.send_json({"type": "create_room"}) + code = _recv(h, "room")["code"] + h.send_json({"type": "join_room", "code": code}) + assert "your own room" in _recv(h, "error")["message"] + assert tc.get("/api/rooms/ZZZZZZ").status_code == 404 + + +def test_ws_room_full(): + with _client() as tc: + with _pair(tc) as (seats, code): + with tc.websocket_connect("/ws") as third: + third.send_json({"type": "join_room", "code": code}) + assert _recv(third, "error")["message"] == "room is full" + + +def test_ws_pending_room_vanishes_on_disconnect_or_leave(): + with _client() as tc: + with tc.websocket_connect("/ws") as h: + h.send_json({"type": "create_room"}) + code = _recv(h, "room")["code"] + h.send_json({"type": "leave_room"}) + assert _recv(h, "room_closed")["reason"] == "left" + assert tc.get(f"/api/rooms/{code}").status_code == 404 + with tc.websocket_connect("/ws") as h: + h.send_json({"type": "create_room"}) + code = _recv(h, "room")["code"] + time.sleep(0.05) + assert tc.get(f"/api/rooms/{code}").status_code == 404 + + +def test_ws_resume_after_drop(): + with _client(grace_seconds=30) as tc: + with _pair(tc) as (seats, code): + p0, room0, _ = seats[0] + p1 = seats[1][0] + _close(p0) + assert _recv(p1, "state")["match"]["opponent_connected"] is False + with tc.websocket_connect("/ws") as back: + back.send_json({"type": "resume", "code": code, "token": "nope"}) + assert "no longer running" in _recv(back, "error")["message"] + back.send_json({"type": "resume", "code": code, "token": room0["token"]}) + r = _recv(back, "room") + assert r["seat"] == 0 and r["status"] == "live" + s = _recv(back, "state") + assert s["snapshot"]["viewer"] == 0 and s["snapshot"]["turn"] == 1 + assert _recv(p1, "state")["match"]["opponent_connected"] is True + back.send_json({"type": "end_turn", "turn": 1}) + assert _recv(p1, "state")["snapshot"]["can_act"] is True + + +def test_ws_resume_elsewhere_kicks_old_socket(): + with _client(grace_seconds=30) as tc: + with _pair(tc) as (seats, code): + p0, room0, _ = seats[0] + with tc.websocket_connect("/ws") as tab2: + tab2.send_json({"type": "resume", "code": code, "token": room0["token"]}) + assert _recv(tab2, "room")["seat"] == 0 + assert _recv(p0, "room_closed")["reason"] == "resumed elsewhere" + p0.send_json({"type": "end_turn", "turn": 1}) + assert _recv(p0, "error")["message"] == "send {type:start} first" + + +def test_ws_concede_and_start_guard(): + with _client() as tc: + with _pair(tc) as (seats, _): + p0, p1 = seats[0][0], seats[1][0] + p1.send_json({"type": "start"}) + assert "concede or leave" in _recv(p1, "error")["message"] + p1.send_json({"type": "concede"}) + s = _recv(p0, "state")["snapshot"] + assert s["winner"] == 0 and s["end_reason"] == "concede" + p1.send_json({"type": "start", "seed": 1}) # allowed once the match is over + s = _recv(p1, "state") + while s["match"]["mode"] == "pvp": # skip the concede broadcast + s = _recv(p1, "state") + assert s["match"]["mode"] == "bot" and s["snapshot"]["turn"] == 1 + + +def test_ws_leave_live_match_concedes(): + with _client() as tc: + with _pair(tc) as (seats, _): + p0, p1 = seats[0][0], seats[1][0] + p0.send_json({"type": "leave_room"}) + s = _recv(p1, "state")["snapshot"] + assert s["winner"] == 1 and s["end_reason"] == "concede" + + +def test_ws_disconnect_grace_forfeit_end_to_end(): + with _client(grace_seconds=0.1) as tc: + with _pair(tc) as (seats, _): + p0, p1 = seats[0][0], seats[1][0] + _close(p1) + time.sleep(0.3) + s = None + for _ in range(10): + s = _recv(p0, "state")["snapshot"] + if s["winner"] is not None: + break + assert s["winner"] == 0 and s["end_reason"] == "disconnect" + + +def test_ws_bot_mode_carries_match_meta(): + with _client() as tc, tc.websocket_connect("/ws") as ws: + ws.send_json({"type": "start", "seed": 1}) + s = _recv(ws, "state") + assert s["match"]["mode"] == "bot" and s["match"]["code"] is None + assert s["match"]["turn_seconds"] is None diff --git a/web/package-lock.json b/web/package-lock.json index 3756f91..a5495e1 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "sunder-web", - "version": "0.3.7.5", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sunder-web", - "version": "0.3.7.5", + "version": "0.4.0", "dependencies": { "lucide-react": "^1.58.0", "react": "^18.3.1", @@ -997,9 +997,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1108,9 +1105,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1125,9 +1119,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1142,9 +1133,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1159,9 +1147,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1176,9 +1161,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1193,9 +1175,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1210,9 +1189,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1227,9 +1203,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1244,9 +1217,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1261,9 +1231,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1278,9 +1245,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1295,9 +1259,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1312,9 +1273,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2562,9 +2520,9 @@ "license": "ISC" }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", "engines": { diff --git a/web/package.json b/web/package.json index a2da212..5cab74f 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "sunder-web", "private": true, - "version": "0.3.7.5", + "version": "0.4.0", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 34bcfdc..b330c1b 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -4,7 +4,9 @@ import App from "./App"; import type { BoardCard, HandCard, + MatchMeta, PlayerState, + RoomInfo, Snapshot, } from "./types"; @@ -12,9 +14,11 @@ const ws = vi.hoisted(() => { const sendMock = vi.fn(); class GameSocket { static last: GameSocket | null = null; - onState: (s: Snapshot) => void = () => {}; + onState: (s: Snapshot, m?: MatchMeta) => void = () => {}; onError: (m: string) => void = () => {}; onOpen: () => void = () => {}; + onRoom: (r: RoomInfo) => void = () => {}; + onRoomClosed: (reason: string) => void = () => {}; send = sendMock; connect() {} close() {} @@ -43,6 +47,17 @@ const storage = vi.hoisted(() => { vi.stubGlobal("localStorage", storage); +const session = vi.hoisted(() => { + const data = new Map(); + return { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value), + removeItem: (key: string) => void data.delete(key), + clear: () => data.clear(), + }; +}); +vi.stubGlobal("sessionStorage", session); + vi.stubGlobal( "fetch", vi.fn((url: string) => { @@ -132,6 +147,115 @@ function pump(snap: Snapshot): void { beforeEach(() => { ws.sendMock.mockClear(); storage.clear(); + session.clear(); + window.history.replaceState(null, "", "/"); +}); + +const pvpMeta = (o: Partial = {}): MatchMeta => ({ + mode: "pvp", + code: "ABC234", + seat: 0, + opponent_connected: true, + turn_seconds: 75, + turn_remaining: 60, + ...o, +}); + +function pumpPvp(snap: Snapshot, meta: MatchMeta = pvpMeta()): void { + const sock = ws.GameSocket.last; + act(() => sock?.onState(snap, meta)); +} + +function room(o: Partial = {}): RoomInfo { + return { mode: "pvp", code: "ABC234", seat: 0, token: "tok", status: "live", ...o }; +} + +describe("App — versus", () => { + it("starts a practice match on connect by default", () => { + render(); + act(() => ws.GameSocket.last?.onOpen()); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "start" }); + }); + + it("resumes a saved PvP seat instead of starting", () => { + session.setItem("sunder-pvp", JSON.stringify({ code: "ABC234", token: "tok" })); + render(); + act(() => ws.GameSocket.last?.onOpen()); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "resume", code: "ABC234", token: "tok" }); + expect(ws.sendMock).not.toHaveBeenCalledWith({ type: "start" }); + }); + + it("joins the room from an invite link", () => { + window.history.replaceState(null, "", "/?room=abc234"); + render(); + act(() => ws.GameSocket.last?.onOpen()); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "join_room", code: "ABC234" }); + }); + + it("falls back to practice when a stale resume fails during boot", () => { + session.setItem("sunder-pvp", JSON.stringify({ code: "ABC234", token: "old" })); + render(); + const sock = ws.GameSocket.last!; + act(() => sock.onOpen()); + act(() => sock.onError("that match is no longer running")); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "start" }); + expect(session.getItem("sunder-pvp")).toBeNull(); + }); + + it("hosts from the VERSUS tab and shows the code", () => { + render(); + pump(snapshot()); + fireEvent.click(screen.getByRole("button", { name: "VERSUS" })); + fireEvent.click(screen.getByRole("button", { name: "CREATE ROOM" })); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "create_room" }); + act(() => ws.GameSocket.last?.onRoom(room({ seat: null, token: null, status: "waiting" }))); + expect(screen.getByTestId("room-code")).toHaveTextContent("ABC234"); + }); + + it("cancelling a hosted room drops back to practice", () => { + render(); + pump(snapshot()); + const sock = ws.GameSocket.last!; + act(() => sock.onRoom(room({ seat: null, token: null, status: "waiting" }))); + ws.sendMock.mockClear(); + act(() => sock.onRoomClosed("left")); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "start" }); + }); + + it("saves the seat token and jumps to the duel when the match goes live", () => { + render(); + pump(snapshot()); + fireEvent.click(screen.getByRole("button", { name: "VERSUS" })); + act(() => ws.GameSocket.last?.onRoom(room())); + pumpPvp(snapshot()); + expect(JSON.parse(session.getItem("sunder-pvp")!)).toEqual({ code: "ABC234", token: "tok" }); + expect(screen.getByText("ROOM ABC234")).toBeInTheDocument(); + expect(screen.getByText("END BROADCAST")).toBeInTheDocument(); + }); + + it("concedes after confirmation", () => { + render(); + pumpPvp(snapshot()); + fireEvent.click(screen.getByRole("button", { name: "CONCEDE" })); + fireEvent.click(screen.getByRole("button", { name: "YES, CONCEDE" })); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "concede" }); + }); + + it("explains how a PvP match ended and offers practice", () => { + session.setItem("sunder-pvp", JSON.stringify({ code: "ABC234", token: "tok" })); + render(); + pumpPvp(snapshot({ winner: 0, can_act: false, end_reason: "concede" })); + expect(screen.getByText("The rival conceded.")).toBeInTheDocument(); + expect(session.getItem("sunder-pvp")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Practice vs the bot" })); + expect(ws.sendMock).toHaveBeenCalledWith({ type: "restart" }); + }); + + it("shows no match bar in practice games", () => { + render(); + pump(snapshot()); + expect(screen.queryByText(/ROOM /)).not.toBeInTheDocument(); + }); }); describe("App", () => { @@ -162,11 +286,15 @@ describe("App", () => { expect(localStorage.getItem("sunder-avatar")).toBe("cinder"); }); - it("restores the saved profile icon on connect", () => { + it("restores the saved profile icon once the first state arrives", () => { localStorage.setItem("sunder-avatar", "vhs"); render(); const sock = ws.GameSocket.last; act(() => sock?.onOpen()); + // cosmetics follow the first snapshot so they reach the right seat + // (practice, resumed PvP, or a freshly joined room) + expect(ws.sendMock).not.toHaveBeenCalledWith({ type: "set_avatar", avatar: "vhs" }); + pump(snapshot()); expect(ws.sendMock).toHaveBeenCalledWith({ type: "set_avatar", avatar: "vhs" }); }); diff --git a/web/src/App.tsx b/web/src/App.tsx index 833e38d..fa27dc0 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -4,7 +4,17 @@ import { BackgroundShader } from "./components/BackgroundShader"; import { ChangelogView } from "./components/ChangelogView"; import { CodexView } from "./components/CodexView"; import { GameView } from "./components/GameView"; -import type { BoardCard, ClientMsg, HandCard, Mode, Snapshot } from "./types"; +import { LobbyView } from "./components/LobbyView"; +import { MatchBar } from "./components/MatchBar"; +import { + clearPvp, + clearRoomFromUrl, + endReasonText, + loadPvp, + roomFromUrl, + savePvp, +} from "./pvp"; +import type { BoardCard, ClientMsg, HandCard, MatchMeta, Mode, RoomInfo, Snapshot } from "./types"; import { SLEEVE_KEY } from "./sleeves"; import { AVATAR_KEY } from "./avatars"; import { GameSocket } from "./ws"; @@ -13,11 +23,18 @@ export default function App() { const [snapshot, setSnapshot] = useState(null); const [mode, setMode] = useState({ kind: "none" }); const [notice, setNotice] = useState(""); - const [view, setView] = useState<"battle" | "codex" | "changelog">("battle"); + const [view, setView] = useState<"battle" | "versus" | "codex" | "changelog">("battle"); + const [match, setMatch] = useState(null); + const [room, setRoom] = useState(null); + const [deadline, setDeadline] = useState(null); const socketRef = useRef(null); + // True until the first snapshot after (re)connect: a failed resume/join + // during boot falls back to a practice match instead of a dead screen. + const bootingRef = useRef(true); + const roomRef = useRef(null); useEffect(() => { - const hidden = view === "codex" || view === "changelog"; + const hidden = view === "codex" || view === "changelog" || view === "versus"; document.documentElement.classList.toggle("no-scrollbar", hidden); return () => { document.documentElement.classList.toggle("no-scrollbar", false); @@ -36,18 +53,73 @@ export default function App() { useEffect(() => { const sock = new GameSocket(); socketRef.current = sock; - sock.onState = (s) => { + const sendCosmetics = () => { + const saved = localStorage.getItem(SLEEVE_KEY); + if (saved) sock.send({ type: "set_sleeve", sleeve: saved }); + const savedAvatar = localStorage.getItem(AVATAR_KEY); + if (savedAvatar) sock.send({ type: "set_avatar", avatar: savedAvatar }); + }; + sock.onState = (s, m) => { + const first = bootingRef.current; + bootingRef.current = false; setSnapshot(s); + setMatch(m ?? null); + setDeadline( + m?.turn_remaining != null ? Date.now() + m.turn_remaining * 1000 : null, + ); + if (m?.mode !== "pvp") { + roomRef.current = null; + setRoom(null); + } + if (m?.mode === "pvp" && s.winner !== null) clearPvp(); // nothing left to resume setMode({ kind: "none" }); setNotice(""); + if (first) sendCosmetics(); + }; + sock.onError = (m) => { + if (bootingRef.current) { + // resume/join from a stale link or token: fall back to practice + clearPvp(); + clearRoomFromUrl(); + sock.send({ type: "start" }); + } + setNotice(m); + }; + sock.onRoom = (r) => { + roomRef.current = r; + setRoom(r); + if (r.token) savePvp({ code: r.code, token: r.token }); + if (r.status === "waiting") { + // The server closed our practice match; don't leave a dead board up. + bootingRef.current = false; + setSnapshot(null); + setMatch(null); + } + if (r.status === "live") { + clearRoomFromUrl(); + setView("battle"); + } + }; + sock.onRoomClosed = (reason) => { + const wasWaiting = roomRef.current?.status === "waiting"; + roomRef.current = null; + setRoom(null); + clearPvp(); + if (wasWaiting) sock.send({ type: "start" }); // cancelled hosting → practice + if (reason === "resumed elsewhere") { + setMatch(null); + setSnapshot(null); + setNotice("This match was opened in another tab."); + sock.send({ type: "start" }); + } }; - sock.onError = (m) => setNotice(m); sock.onOpen = () => { - sock.send({ type: "start" }); - const saved = localStorage.getItem(SLEEVE_KEY); - if (saved) sock.send({ type: "set_sleeve", sleeve: saved }); - const savedAvatar = localStorage.getItem(AVATAR_KEY); - if (savedAvatar) sock.send({ type: "set_avatar", avatar: savedAvatar }); + bootingRef.current = true; + const saved = loadPvp(); + const invite = roomFromUrl(); + if (saved) sock.send({ type: "resume", code: saved.code, token: saved.token }); + else if (invite) sock.send({ type: "join_room", code: invite }); + else sock.send({ type: "start" }); }; sock.connect(); return () => sock.close(); @@ -158,7 +230,9 @@ export default function App() { savedSleeve = localStorage.getItem(SLEEVE_KEY); } catch { /* storage unavailable */ } - const mySleeve = snapshot?.players?.[0]?.sleeve ?? savedSleeve ?? "ember"; + const mySleeve = snapshot?.me?.sleeve ?? savedSleeve ?? "ember"; + const inPvp = match?.mode === "pvp"; + const won = snapshot !== null && snapshot.winner === snapshot.viewer; return ( <> @@ -187,6 +261,13 @@ export default function App() { > DUEL + + + ); + } + + return ( +
+

VERSUS

+ {waiting && room ? ( +
+
ROOM CODE
+
+ {room.code} +
+

Waiting for a rival station to tune in…

+
+ + +
+
+ ) : ( +
+
+
HOST
+

Open a frequency and send the code to a friend.

+ +
+
{ + e.preventDefault(); + const c = normalizeCode(code); + if (c) onJoin(c); + }} + > + + setCode(normalizeCode(e.target.value))} + placeholder="ABC234" + maxLength={12} + autoComplete="off" + spellCheck={false} + /> + +
+
+ )} +

+ Turns are timed in versus. Leaving or closing the tab for too long forfeits. +

+
+ ); +} diff --git a/web/src/components/MatchBar.test.tsx b/web/src/components/MatchBar.test.tsx new file mode 100644 index 0000000..dfec093 --- /dev/null +++ b/web/src/components/MatchBar.test.tsx @@ -0,0 +1,57 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import type { MatchMeta } from "../types"; +import { MatchBar } from "./MatchBar"; + +const meta = (o: Partial = {}): MatchMeta => ({ + mode: "pvp", + code: "ABC234", + seat: 0, + opponent_connected: true, + turn_seconds: 75, + turn_remaining: 40, + ...o, +}); + +describe("MatchBar", () => { + it("shows the room, rival status and the turn clock", () => { + render( + {}} />, + ); + expect(screen.getByText("ROOM ABC234")).toBeInTheDocument(); + expect(screen.getByText("RIVAL ON AIR")).toBeInTheDocument(); + expect(screen.getByText(/YOUR TURN 40s/)).toBeInTheDocument(); + }); + + it("flags a dropped rival", () => { + render( + {}} />, + ); + expect(screen.getByText(/RIVAL SIGNAL LOST/)).toBeInTheDocument(); + expect(screen.queryByText(/\ds$/)).not.toBeInTheDocument(); + }); + + it("asks for confirmation before conceding", () => { + const onConcede = vi.fn(); + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: "CONCEDE" })); + expect(onConcede).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "KEEP PLAYING" })); + fireEvent.click(screen.getByRole("button", { name: "CONCEDE" })); + fireEvent.click(screen.getByRole("button", { name: "YES, CONCEDE" })); + expect(onConcede).toHaveBeenCalledTimes(1); + }); + + it("hides concede and clock once the game is over", () => { + render( + {}} />, + ); + expect(screen.queryByRole("button", { name: "CONCEDE" })).not.toBeInTheDocument(); + expect(screen.queryByText(/YOUR TURN/)).not.toBeInTheDocument(); + }); +}); diff --git a/web/src/components/MatchBar.tsx b/web/src/components/MatchBar.tsx new file mode 100644 index 0000000..378deee --- /dev/null +++ b/web/src/components/MatchBar.tsx @@ -0,0 +1,58 @@ +import { useEffect, useState } from "react"; +import type { MatchMeta } from "../types"; + +interface MatchBarProps { + match: MatchMeta; + /** ms epoch when the current turn clock expires (client-side estimate). */ + deadline: number | null; + myTurn: boolean; + gameOver: boolean; + onConcede: () => void; +} + +/** PvP strip above the board: room code, rival link status, turn clock, concede. */ +export function MatchBar({ match, deadline, myTurn, gameOver, onConcede }: MatchBarProps) { + const [now, setNow] = useState(() => Date.now()); + const [confirm, setConfirm] = useState(false); + + useEffect(() => { + if (deadline === null || gameOver) return; + const id = window.setInterval(() => setNow(Date.now()), 250); + return () => window.clearInterval(id); + }, [deadline, gameOver]); + + const secs = deadline === null ? null : Math.max(0, Math.ceil((deadline - now) / 1000)); + const low = secs !== null && secs <= 10; + + return ( +
+ ROOM {match.code} + + {match.opponent_connected ? "RIVAL ON AIR" : "RIVAL SIGNAL LOST…"} + + {secs !== null && !gameOver && ( + + {myTurn ? "YOUR TURN" : "RIVAL"} {secs}s + + )} + {!gameOver && + (confirm ? ( + + + + + ) : ( + + ))} +
+ ); +} diff --git a/web/src/components/Overlays.tsx b/web/src/components/Overlays.tsx index a0d89b3..8fe8dc3 100644 --- a/web/src/components/Overlays.tsx +++ b/web/src/components/Overlays.tsx @@ -36,18 +36,23 @@ export function Inspector({ card }: { card: CardInfo | null }) { export function EndGameOverlay({ snapshot, onRestart, + note, + restartLabel = "Play again", }: { snapshot: Snapshot; onRestart: () => void; + note?: string; + restartLabel?: string; }) { const won = snapshot.winner === snapshot.viewer; return (

{won ? "You cut the rival off the air." : "You were cut off the air."}

+ {note &&

{note}

}

{snapshot.status}

diff --git a/web/src/pvp.test.ts b/web/src/pvp.test.ts new file mode 100644 index 0000000..2dd7595 --- /dev/null +++ b/web/src/pvp.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + clearPvp, + endReasonText, + inviteLink, + loadPvp, + normalizeCode, + PVP_KEY, + roomFromUrl, + savePvp, +} from "./pvp"; + +const store = new Map(); +vi.stubGlobal("sessionStorage", { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, v), + removeItem: (k: string) => void store.delete(k), +}); + +beforeEach(() => store.clear()); + +describe("pvp session", () => { + it("round-trips code + token through sessionStorage", () => { + expect(loadPvp()).toBeNull(); + savePvp({ code: "ABC234", token: "secret" }); + expect(loadPvp()).toEqual({ code: "ABC234", token: "secret" }); + clearPvp(); + expect(loadPvp()).toBeNull(); + }); + + it("ignores malformed storage", () => { + store.set(PVP_KEY, "{not json"); + expect(loadPvp()).toBeNull(); + store.set(PVP_KEY, JSON.stringify({ code: 5 })); + expect(loadPvp()).toBeNull(); + }); +}); + +describe("room codes and links", () => { + it("normalizes user input", () => { + expect(normalizeCode(" abc-234 ")).toBe("ABC234"); + }); + + it("reads ?room= from the URL and rejects junk", () => { + expect(roomFromUrl("?room=abc234")).toBe("ABC234"); + expect(roomFromUrl("?room=