diff --git a/.gitignore b/.gitignore index 915a5c1..455fe64 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ target/ # Tests data/ test-output/ -# TODO: Why is xunit writing stuff to the build root instead of its test output directory? xunit/ # Gradle diff --git a/build-logic/src/main/kotlin/webapp-conventions.gradle.kts b/build-logic/src/main/kotlin/webapp-conventions.gradle.kts index 1b64b11..0622c88 100644 --- a/build-logic/src/main/kotlin/webapp-conventions.gradle.kts +++ b/build-logic/src/main/kotlin/webapp-conventions.gradle.kts @@ -1,11 +1,15 @@ /** * Convention plugin for XTC modules with webapp content. * - * Adds the project's webapp/ directory as a resource source, so that - * static content can be served at runtime. + * Adds the project's webapp content as a resource source, so that static + * content can be served at runtime via @StaticContent. * * If webapp/package.json exists, the Node/npm plugin builds the webapp - * (e.g. React) automatically before resource processing. + * (e.g. React/Vite) automatically before resource processing, and only the + * build *output* (webapp/build) is exposed as a resource — not the npm + * project itself (node_modules, raw src, config files). Projects with only + * static HTML in webapp/public/ (banking, counter) expose the whole webapp/ + * directory as-is, since there's no build step to separate out. */ import com.github.gradle.node.npm.task.NpmTask @@ -29,9 +33,14 @@ repositories { mavenCentral() } +val hasNpmWebapp = file("webapp/package.json").exists() + sourceSets.named("main") { resources { - srcDir("webapp") + // npm-based webapps (welcome, chess-game) only need their built + // output; the npm project itself (node_modules, src, configs) would + // otherwise get copied into the module's resources unnecessarily. + srcDir(if (hasNpmWebapp) "webapp/build" else "webapp") } } @@ -42,11 +51,8 @@ sourceSets.named("main") { // 2. Register a buildWebapp task that runs `npm run build` with proper caching // 3. Make processResources and processXtcResources depend on buildWebapp so the // compiled webapp output is available as XTC module resources (used by -// @StaticContent annotations). Both tasks copy the webapp/ resource srcDir. -// -// Projects with only static HTML in webapp/public/ (banking, counter, chess-game) -// skip this block entirely — their content is picked up directly by the srcDir above. -if (file("webapp/package.json").exists()) { +// @StaticContent annotations). Both tasks copy the webapp/build resource srcDir. +if (hasNpmWebapp) { node { download.set(providers.gradleProperty("node.download") .map { it.toBoolean() } diff --git a/build.gradle.kts b/build.gradle.kts index 98dc39a..ab55881 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -20,7 +20,6 @@ dependencies { xtcModule(projects.welcome) xtcModule(projects.banking) xtcModule(projects.counter) - xtcModule(projects.cardGame) // Chess-game is an included composite build. Gradle's composite-build // dependency substitution routes these coordinate-based deps to the diff --git a/chess-game/README.md b/chess-game/README.md index 7444a3d..3c665f2 100644 --- a/chess-game/README.md +++ b/chess-game/README.md @@ -1,121 +1,212 @@ -# Chess Game Example - -A full-stack web-based chess game built with the Ecstasy language, featuring both single-player mode with an intelligent AI opponent and online multiplayer with real-time chat. +# Chess Playground + +A full-stack chess game written in XTC (Ecstasy) with a React client. Play Stockfish, play a +friend over a shared room link, solve the chess.com daily puzzle, or review a chess.com game — +then see how you played and how you think: live engine evaluations, accuracy, mistakes, and a +fitted model of your decision-making, all drawn as interactive charts. + +## Contents + +- [Overview](#overview) +- [Prerequisites](#prerequisites) +- [Project Structure](#project-structure) +- [Quick Start](#quick-start) +- [Game Modes](#game-modes) + - [Single Player (vs AI)](#single-player-vs-ai) + - [Play a Friend (Rooms)](#play-a-friend-rooms) + - [Daily Puzzle](#daily-puzzle) + - [Review](#review) +- [How to Play](#how-to-play) +- [API](#api) + - [Single-Player Endpoints](#single-player-endpoints) + - [Room Endpoints](#room-endpoints) + - [Engine and chess.com Endpoints](#engine-and-chesscom-endpoints) +- [Technical Details](#technical-details) +- [Development](#development) +- [Database](#database) +- [Troubleshooting](#troubleshooting) +- [Learn More](#learn-more) ## Overview -This project demonstrates a complete web application using the Ecstasy platform: -- **Server**: RESTful API built with the Ecstasy web framework and OODB (Object-Oriented Database) -- **Client**: Single-page application with vanilla JavaScript and modern CSS -- **Game Logic**: Complete chess rule implementation including castling and en passant -- **AI Opponent**: Diverse, randomized AI with opening book and heuristic evaluation -- **Online Multiplayer**: Play against others with game codes and real-time chat - -### Key Features - -- ♟️ **Two Game Modes**: Single-player vs AI or online multiplayer -- 🎮 **Complete Chess Rules**: Full implementation including castling, en passant, and pawn promotion -- 🤖 **Intelligent & Diverse AI**: Randomized move selection with opening book for varied gameplay -- 🌐 **Online Multiplayer**: Create or join games with unique game codes -- 💬 **Real-time Chat**: Modern chat interface for online games -- 💾 **Session Isolation**: Each browser tab has its own independent game -- 🎨 **Modern UI**: Responsive design with smooth animations and gradients -- ⚡ **Real-time Updates**: Auto-refresh during opponent's turn -- ⏱️ **Time Controls**: Optional chess clocks for competitive play +- **Server** — an XTC `@WebApp` module hosted by the [XQIZ.IT platform](https://github.com/xtclang/platform): + REST services, a jsondb database, and proxies for the Stockfish Online engine and chess.com. +- **Client** — React with TanStack Query (live data), TanStack Charts (charts) and TanStack Table + (the sortable move list), built with Vite and compiled into the server module. +- **Computer opponent** — every move comes from Stockfish Online; nothing picks moves locally. +- **Rooms** — play a friend over a shared link, with an optional clock. See + [Play a Friend (Rooms)](#play-a-friend-rooms). +- **Daily puzzle** — the chess.com puzzle of the day, playable move by move with right/wrong + feedback, not just a static diagram. See [Daily Puzzle](#daily-puzzle). +- **Insights** — engine evaluation, win chance, accuracy, centipawn loss, mistake counts, and a + softmax model of your choices fitted to the moves you play. The in-app **Guide** explains each. ## Prerequisites -- **JDK 21+** on your PATH to bootstrap `./gradlew`. The Gradle daemon and - the XTC compile toolchain both run on JDK 25 (required by the XTC - plugin); Gradle auto-provisions those via Foojay — see - `gradle/gradle-daemon-jvm.properties` at the repo root. -- **XDK** is resolved automatically from Maven repositories. +| Tool | Why | +| --- | --- | +| **JDK** supported by your XDK (21+) | runs the XTC toolchain; set `JAVA_HOME` | +| **XDK** with `xtc` on your `PATH` | compiles, runs and tests the modules | +| **Node.js 18+** and npm | builds the React client | -This project is part of the outer `examples` composite build — see the -top-level [README](../README.md) for full prerequisites and setup. +Gradle (`./gradlew build`, `./gradlew run`) works too where the XTC Gradle plugin resolves; the +scripts below need only the three tools above. ## Project Structure `chess-game/` is itself a Gradle composite build that produces two XTC modules: `chess.xtc` (the `@WebApp` server) and `chessDB.xtc` (the OODB -schema). The `app` subproject depends on `db`. +schema). The `app` subproject depends on `db`. Being `@WebApp`, `chess.xtc` +needs the XQIZ.IT platform to host it — it has no standalone server of its own. ``` chess-game/ -├── build.gradle.kts # Composite root (lifecycle aggregator) -├── settings.gradle.kts -│ -├── app/ # :app subproject — produces chess.xtc -│ ├── build.gradle.kts -│ ├── src/main/x/ -│ │ ├── chess.x # @WebApp module entry point -│ │ └── chess/ -│ │ ├── ai/ # AIMoveSelector, AIOpeningBook, ChessAI, … -│ │ ├── api/ # ChessApi, OnlineChessApi, ChatApi -│ │ ├── config/ # CastlingManager, MoveContext, MoveStrategy -│ │ ├── core/ # ChessGame, ChessLogic, OnlineChessLogic -│ │ ├── services/ # TimeControlService -│ │ ├── utils/ # BoardOperations, BoardUtils, … -│ │ └── validation/ # CheckDetection, MoveValidator, PieceValidator, … -│ ├── src/test/x/ # 16 xunit test modules -│ ├── cli/ # @TerminalApp REST-API CLI (not yet on a source set) -│ └── webapp/public/ # Static client (HTML / JS / CSS) -│ -└── db/ # :db subproject — produces chessDB.xtc - ├── build.gradle.kts - └── src/main/x/ - ├── chessDB.x # @Database schema entry point - └── chessDB/ - ├── base/ # Piece base type - ├── factory/ # PieceFactory - ├── models/ # CastlingRights, GameRecord, OnlineGame, … - ├── pieces/ # Bishop, King, Knight, Pawn, Queen, Rook - └── types/ # PieceType +├── scripts/ +│ ├── build.sh # web client + chessDB + chess, into build/xtc/main/lib +│ └── test.sh # run every test suite, each in a fresh directory +├── db/src/main/x/ +│ └── chessDB.x # database schema (@oodb.Database) +└── app/ + ├── src/main/x/ + │ ├── chess.x # the @WebApp module: Database, static content + │ └── chess/ + │ ├── api/ # web services: ChessApi, OnlineChessApi, + │ │ # EngineApi (/api/engine), ChessComApi (/api/chesscom) + │ ├── ai/ # StockfishApi (engine client), ChessAPIClient (computer moves) + │ ├── core/ # game logic, single-player and online + │ ├── validation/ # move legality, check detection + │ └── services/ # time controls + ├── src/test/x/ # one xunit suite per service, plus the logic suites + └── webapp/ # React client (Vite) + └── src/ + ├── lib/ # engine scheduler, local model, insights, play state + └── components/ # board, charts, insights panel, guide, logo ``` ## Quick Start -Build and run from the `examples/` root (one level up): +### Build + +```bash +scripts/build.sh +``` + +This builds the web client and both modules into `build/xtc/main/lib`: `chessDB.xtc` and +`chess.xtc` (with the built web client bundled in as static content). + +### Host it + +`chess.examples.org` is `@WebApp` — it has no standalone server of its own and needs the +[XQIZ.IT platform](https://github.com/xtclang/platform) to host it (it supplies the `ChessSchema` +by injection and serves the HTTP/HTTPS endpoints). Deploy `chessDB.xtc` and `chess.xtc` to a +running platform instance per its own documentation. + +**Files the database writes**, relative to the working directory (both git-ignored): +`data/chessDB/` holds the database and `build/db/` the generated jsondb host module. These are +only used as a fallback when nothing injects a schema (e.g. tests calling a service directly) — +see `Database` in `chess.x`. + +### Run the tests ```bash -# Compile chess.xtc and chessDB.xtc, run all 16 chess test modules -./gradlew :chess-game:build +scripts/test.sh # all suites except the live network suite +scripts/test.sh ChessApiTest # one or more named suites +scripts/test.sh --live # also ChessLiveApiTest: real Stockfish and chess.com calls +scripts/test.sh --no-build # skip recompiling first +``` + +Each suite runs from its own fresh temporary directory, so its database never leaks into another +suite or into the repository. The script prints a table of passed, failed and skipped tests per +suite and exits non-zero on any failure. + +| Suite | Covers | +| --- | --- | +| `ChessApiTest` | `/api` — state, legal and illegal moves, valid moves, reset, clocks, session isolation | +| `OnlineChessApiTest` | `/api/online` — rooms, seating, turn order, moves, valid moves, reset, leaving | +| `EngineApiTest` | `/api/engine` — FEN validation before any upstream call, JSON encoding | +| `ChessComApiTest` | `/api/chesscom` — username and date validation before any upstream call | +| `ChessEngineApiTest` | `StockfishApi` — reading engine replies, UCI moves, URL encoding | +| `ChessLiveApiTest` | live: engine analysis, chess.com, and a real computer reply (opt-in) | +| the rest | game logic, validation, board utilities, time controls, the database models | -# Stage all examples (including chess.xtc + chessDB.xtc) into one lib dir -./gradlew installDist -ls build/install/examples/lib/ # → chess.xtc, chessDB.xtc, … +The live suite needs internet and respects the engine's rate limit (about one request per 1.5 +seconds); expect it to take around half a minute. `ChessAIMoveSelectionTest` in the default run +also reaches the engine once, through the computer-move path. + +A single suite can also be run by hand from any scratch directory: + +```bash +xtc test -L build/xtc/main/lib app/src/test/x/ChessApiTest.x ``` -`chess.examples.org` is an `@WebApp` and currently requires the XQIZ.IT -platform to be hosted (a standalone `xtc run` of an `@WebApp` is not -supported — `xenia.createServer(...)` from a `void run()` would be needed -to bootstrap one without the platform). Once hosted, the static client -served at `/` provides the UI in a browser. +### Work on the web client + +With the backend hosted on the XQIZ.IT platform, start Vite with hot reload in another terminal: + +```bash +cd app/webapp +npm install +npm run dev +``` + +Point Vite's dev proxy at wherever the platform is hosting `chess.examples.org`, so the client +talks to the real backend. `npm run build` writes the production client to `app/webapp/build`, +which `chess.x` serves as static content; rebuild the module afterwards (`scripts/build.sh`) to +ship it. ## Game Modes ### Single Player (vs AI) -Play against an intelligent AI opponent that uses: -- **Opening Book**: Recognizes common chess openings and responds with strong moves -- **Randomized Selection**: Chooses from top-scoring moves for unpredictable gameplay -- **Positional Evaluation**: Uses piece-square tables for strategic positioning -- **Tactical Awareness**: Evaluates captures, checks, and material balance +Every move the computer plays comes from the [Stockfish Online](https://stockfish.online) engine +API, reached through `StockfishApi.x`. Nothing picks the computer's moves locally: + +- **Real engine play**: the position is sent as FEN and the engine's `bestmove` is played back +- **Rule check**: the engine's move is validated against this game's simplified rules before it + is applied, since a full engine can suggest moves the simplified rule set cannot play +- **Offline fallback**: if the engine cannot be reached, a random legal move is played so the + game never stalls + +The same engine is exposed to the web client at `/api/engine/analyse`, which is where the +analysis panel's evaluation graph and centipawn-loss figures come from. + +**Session isolation**: each browser tab keeps its own game, under a session id in `localStorage` +(see [Session Management](#session-management)). Multiple tabs play independent games. + +### Play a Friend (Rooms) -The AI adds variety by: -- Randomly selecting from multiple strong opening responses -- Choosing from top moves within a score threshold (not always the "best" move) -- Different play styles in opening, middle, and endgame phases +Two players share a room, identified by a 6-character code (`OnlineChessApi.x`, `/api/online`): -**Session Isolation**: Each browser tab gets its own independent game. You can play multiple games simultaneously in different tabs without interference. +1. On the **Room** tab, **Create room** — optionally with a clock. The creator plays White and + gets a room code plus an invite link (`?room=CODE`). +2. **Copy invite link** and send it to a friend. Opening the link lands them directly on the Room + tab and attempts to join that room — no code to type. A code can also be entered by hand under + **Join a room**. +3. The second player to join plays Black. Once both are seated, the room's state polls for each + player's turn — board, clocks, and move history all come from the server, so either side's + browser is simply a window onto the same `OnlineGame`. +4. Either player can **Leave** at any time, which marks the room as abandoned for the other side. + When the game ends (checkmate, draw, or time out), **Rematch** resets the same room with both + players still seated. -### Online Multiplayer +A room's seat (its room code and player id) is kept in `localStorage`, the same way a +single-player session is — reloading the page returns you to the same seat in the same room. -1. Click the **Online** tab -2. Choose to **Create Game** (generates a unique code) or **Join Game** (enter a code) -3. Share the game code with your opponent -4. Play in real-time with automatic turn synchronization -5. Use the **Chat** feature to communicate during the game +### Daily Puzzle + +The **daily puzzle** button (on the Review tab) loads chess.com's puzzle of the day and plays it +out move by move, not as a static position: attempt the solving side's move, and the opponent's +reply plays itself after a short pause if it's correct. A wrong attempt is rejected on the spot, +with the board staying put and a prompt to try again. The solution comes from the puzzle's own +PGN (`/api/chesscom/puzzle`), checked entirely in the browser — no server round-trip while +solving. Solving the full sequence shows a "Solved!" state with a button to try it again. + +### Review + +Load any `chess.com` player's recent games (`/api/chesscom/*`) and step through them move by +move, with the same engine-evaluation and accuracy panel used in single-player — useful for +seeing how a finished game actually went, move by move, with the engine's own read on each +position. ## How to Play @@ -133,80 +224,57 @@ This implementation includes **complete chess rules**: ### Making Moves -1. **Click a square** with your piece (you play as White in single-player) -2. **Click the destination** square where you want to move -3. The move will be validated by the server -4. If legal, the opponent responds (AI instantly picks from good moves, online opponent when they move) +1. **Click a square** with your piece (you play as White in single-player and as the room's + creator; Black otherwise) +2. **Click a highlighted destination** square to move there +3. The server validates and applies the move +4. The opponent responds — the computer after a short pause, a room opponent whenever they move 5. Continue playing until the game ends ### Game Controls -- **Reset Game**: Start a new game with fresh board setup -- **Sync**: Manually refresh the game state from the server -- **Info**: View game status and rules -- **Chat**: Open chat panel (online mode) - -## API Documentation - -The server exposes a RESTful API at `/api`: - -### Single Player Endpoints - -All single-player endpoints include a session ID for game isolation: +- **Game** menu (single-player): pick a time control and start a **New game** +- **Leave** / **Rematch** (rooms): leave the room, or reset it with both players still seated +- **Insights** panel: collapse or reopen the engine-evaluation and accuracy panel beside the board -#### Get Game State -```http -GET /api/state/{sessionId} -``` - -#### Make a Move -```http -POST /api/move/{sessionId}/{from}/{to} -``` - -#### Reset Game -```http -POST /api/reset/{sessionId} -``` - -#### Get Valid Moves -```http -GET /api/validmoves/{sessionId}/{square} -``` +## API -### Online Multiplayer Endpoints +### Single-Player Endpoints -#### Create Game -```http -POST /api/online/create -``` +`ChessApi.x`, under `/api`. Every endpoint includes the browser's session id for game isolation. -#### Join Game -```http -POST /api/online/join/{gameCode}?color={white|black} -``` +| Method | Path | Does | +| --- | --- | --- | +| GET | `/api/state/{sessionId}` | Current state of this session's game | +| POST | `/api/move/{sessionId}/{from}/{target}` | Play a move, e.g. `e2`/`e4` | +| POST | `/api/reset/{sessionId}` | Start a new game; JSON body `{timeControlMs, incrementMs}` for a clock | +| GET | `/api/validmoves/{sessionId}/{square}` | Legal destination squares for the piece on `square` | -#### Get Online Game State -```http -GET /api/online/state/{gameCode}?playerId={playerId} -``` +### Room Endpoints -#### Make Online Move -```http -POST /api/online/move/{gameCode}/{from}/{to}?playerId={playerId} -``` +`OnlineChessApi.x`, under `/api/online`. The room code identifies the game; the player id +(returned by `create`/`join`) identifies which side of it this request is playing. -### Chat Endpoints +| Method | Path | Does | +| --- | --- | --- | +| POST | `/api/online/create` | New room; optional JSON body `{timeControlMs, incrementMs}`. Returns `{roomCode, playerId}` | +| POST | `/api/online/join/{roomCode}` | Join as the second player. Returns game state with a `playerId`, or an error message with none | +| GET | `/api/online/state/{roomCode}/{playerId}` | Current state, from this player's point of view | +| POST | `/api/online/move/{roomCode}/{playerId}/{from}/{target}` | Play a move | +| POST | `/api/online/reset/{roomCode}/{playerId}` | Rematch: reset the board, keep both players seated | +| POST | `/api/online/leave/{roomCode}/{playerId}` | Leave the room | +| GET | `/api/online/validmoves/{roomCode}/{playerId}/{square}` | Legal destination squares for the piece on `square` | -#### Send Message -```http -POST /api/chat/{gameCode}/send?playerId={playerId}&message={message} -``` +### Engine and chess.com Endpoints -#### Get Messages -```http -GET /api/chat/{gameCode}/messages?since={timestamp} -``` +| Method | Path | Does | +| --- | --- | --- | +| GET | `/api/engine/analyse?fen=&depth=` | Stockfish Online's evaluation of a position | +| GET | `/api/engine/bestmove?fen=&depth=` | The engine's move for a position | +| GET | `/api/chesscom/player/{username}` | A chess.com player's public profile | +| GET | `/api/chesscom/archives/{username}` | Monthly archive URLs for a player's games | +| GET | `/api/chesscom/games/{username}/{year}/{month}` | One month's games, with PGN | +| GET | `/api/chesscom/puzzle` | chess.com's daily puzzle: title, FEN, PGN solution | ## Technical Details @@ -233,59 +301,43 @@ Index: 56-63 = Rank 1 (a1-h1) - White's back rank ### AI Strategy -The AI opponent uses sophisticated move selection: - -1. **Opening Book**: Collection of strong opening responses (Sicilian, French, Caro-Kann, etc.) -2. **Piece Values**: Pawn=100, Knight=320, Bishop=330, Rook=500, Queen=900 -3. **Piece-Square Tables**: Positional bonuses for optimal piece placement -4. **Mobility**: Bonus for having more available moves -5. **Tactical Evaluation**: Check bonuses, development bonuses, center control -6. **Randomization**: Selects from top moves within 15% of best score for variety +The computer plays whatever Stockfish Online returns for the position (depth 12), after checking +the move against this game's rules. If the engine cannot be reached, it plays a random legal move +so the game never stalls. See *Single Player (vs AI)* above. ### Session Management -- Single-player games use `sessionStorage` for browser tab isolation -- Each tab generates a unique session ID on first load -- Game state is persisted per-session in the database -- Refreshing the page restores your game; opening a new tab starts fresh +- Each browser keeps one single-player game, under a session id stored in `localStorage` +- Reloading the page, or closing and reopening the browser, returns you to the same game +- Clearing the site's storage starts a fresh session +- Game state is persisted per session in the database ## Development -### Running in Development Mode - -Use Gradle's `--continuous` flag to re-run a task whenever source files change: - -```bash -./gradlew :chess-game:build --continuous -``` - -This recompiles the chess modules on every save. (The `chess.examples.org` -@WebApp itself still needs the XQIZ.IT platform to be hosted; `--continuous` -only handles the build/test loop.) - -### Building for Production - -There is no separate production build profile — the same `./gradlew build` -produces the deployable `chess.xtc` and `chessDB.xtc` modules. - ### Project Architecture -The server uses a modular architecture: -- **ChessApi**: Routes HTTP requests to appropriate handlers -- **ChessGame**: Manages game state and coordinates logic -- **ChessAPIClient**: AI move selection via the Stockfish Online API -- **ChessLogic**: Executes moves and updates state -- **PieceValidator**: Validates move legality per piece type -- **CheckDetection**: Determines check, checkmate, and stalemate -- **OnlineChessApi/Logic**: Handles multiplayer game sessions -- **ChatApi**: Real-time chat for online games +- **ChessApi** (`/api`): single-player games, one per browser session +- **OnlineChessApi** (`/api/online`): rooms for two players +- **EngineApi** (`/api/engine`): the web client's route to Stockfish Online +- **ChessComApi** (`/api/chesscom`): read-only proxy for chess.com's public data +- **StockfishApi**: the engine client; **ChessAPIClient** plays its moves for the computer +- **ChessLogic / ChessGame**: execute moves and update state +- **PieceValidator / CheckDetection**: legality, check, checkmate, stalemate +- **Database** (in `chess.x`): hands each service its own connection — injected by a host when + there is one, otherwise opened over jsondb in the working directory + +The client keeps two kinds of live data in TanStack Query. The game is one query per session, +polled only while the computer is thinking. Engine evaluations are one query per position, cached +for good (in memory and in local storage), and fed through a scheduler that sends one request +per 1.5 seconds, serves the position on the board first, and pauses while the computer chooses +its move so the two never compete for the engine's rate limit. ## Database The game uses Ecstasy's OODB (Object-Oriented Database) for state persistence: -- **Compiled module**: `chess-game/db/build/xtc/main/lib/chessDB.xtc` -- **Schema**: Defined in `db/src/main/x/chessDB.x` +- **Data**: `data/chessDB/`, relative to the server's working directory +- **Schema**: defined in `db/src/main/x/chessDB.x` - **Storage**: - Single-player games in `singlePlayerGames` map (keyed by session ID) - Online games in `onlineGames` map (keyed by game code) @@ -294,46 +346,27 @@ The database persists game state across server restarts. ## Troubleshooting -### Port Already in Use - -If something is already listening on port 8080: - -```bash -lsof -i :8080 -kill -9 -``` - ### Build Failures -Ensure the JDK on your PATH is at least JDK 21 (to launch `./gradlew`): - +Check the toolchain the scripts use: ```bash -java -version +java -version # a JDK your XDK supports +xtc --version # the XDK is on PATH (or set XTC=/path/to/xtc) +node --version # 18 or later ``` -If you see `Dependency requires at least JVM runtime version 25. This build -uses a Java NN JVM.`, the Gradle daemon was started on a JVM older than 25 -and couldn't load the XTC plugin. `gradle/gradle-daemon-jvm.properties` at -the repo root tells Gradle to auto-provision JDK 25 for the daemon via -Foojay — if you removed or modified that file, restore it. +### Hosting Issues -If you suspect a stale Gradle cache, clean and rebuild — but run `clean` -on its own (the outer `examples` build aggregator forbids combining it -with other tasks): - -```bash -./gradlew clean -./gradlew build -``` +`chess.examples.org` is `@WebApp` and has no server of its own — connectivity, TLS, and port +issues are a property of the XQIZ.IT platform instance hosting it, not of this module. See the +[platform's docs](https://github.com/xtclang/platform) for deploying and troubleshooting there. ### Game State Issues If the game gets into a bad state: -1. Click **Reset Game** in the UI. -2. Open a new browser tab for a fresh single-player session. -3. Delete the on-disk database directory under the server's working dir - (search for the `chessDB` jsondb folder created at runtime by the - hosting platform) and restart the server. +1. Start a **New game** under the board +2. Clear the site's storage in the browser for a fresh session +3. On the hosting platform, clear `chessDB`'s persisted data and restart the module ## Learn More diff --git a/chess-game/app/build.gradle.kts b/chess-game/app/build.gradle.kts index f1f92ad..4af9869 100644 --- a/chess-game/app/build.gradle.kts +++ b/chess-game/app/build.gradle.kts @@ -3,11 +3,6 @@ * * Depends on the chessDB module for schema types and on the webapp content * for @StaticContent annotations. - * - * Note: chess-game/app/cli/ChessGameManagement.x is a @TerminalApp CLI tool - * that lives outside any XTC source set; it has pre-existing lexer errors - * in its $|...| JSON template strings and needs to be relocated into its - * own module — tracked in xtclang/examples#14. */ plugins { diff --git a/chess-game/app/cli/ChessGameManagement.x b/chess-game/app/cli/ChessGameManagement.x deleted file mode 100644 index db89a13..0000000 --- a/chess-game/app/cli/ChessGameManagement.x +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Chess Game Management CLI - Functional test tool. - * - * Exercises all chess REST API endpoints (single-player, online multiplayer, chat) - * from the command line using the `@TerminalApp` / `@Command` pattern. - * - * Usage: - * - Launch while the chess-game web app is running. - * - Type a command at the prompt (e.g. "new-game", "move e2 e4"). - * - * Endpoint mapping: - * ChessApi -> /api/... - * OnlineChessApi -> /api/online/... - * ChatApi -> /api/chat/... - * - * Commands are organised into five mixins: - * - SinglePlayerCommands : single-player game operations and edge-case tests - * - OnlineCommands : online multiplayer room management and flows - * - ChatCommands : in-game chat and bulk message tests - * - TimedGameCommands : time-control game creation - * - GameFlowCommands : scripted multi-move game sequences - */ -@TerminalApp("Chess Game Management CLI", "Chess>") -module ChessGameManagement.examples.org { - package webcli import webcli.xtclang.org; - import webcli.*; - - incorporate SinglePlayerCommands; - incorporate OnlineCommands; - incorporate ChatCommands; - incorporate TimedGameCommands; - incorporate GameFlowCommands; -} diff --git a/chess-game/app/cli/ChessGameManagement/ChatCommands.x b/chess-game/app/cli/ChessGameManagement/ChatCommands.x deleted file mode 100644 index 7fd8ca4..0000000 --- a/chess-game/app/cli/ChessGameManagement/ChatCommands.x +++ /dev/null @@ -1,74 +0,0 @@ -import webcli.*; - -/** - * Chat commands for online games. - * - * Covers the /api/chat/... endpoints: - * - messaging : send-message, chat-history, recent-messages - * - flows : chat-flow (send + immediate history), chat-burst (3 rapid messages) - */ -mixin ChatCommands { - - /** - * Send a chat message in an online game room. - */ - @Command("send-message", "Send a chat message (roomCode playerId message)") - String sendMessage(String roomCode, String playerId, String message) = - post($|api/chat/send/{roomCode}/{playerId} - , $|\{"message":"{message}"\} - ); - - /** - * Retrieve full chat history for a room. - */ - @Command("chat-history", "Get chat history (roomCode playerId)") - String chatHistory(String roomCode, String playerId) = - get($"api/chat/history/{roomCode}/{playerId}"); - - /** - * Retrieve recent chat messages since a given timestamp. - */ - @Command("recent-messages", "Get recent messages (roomCode playerId sinceMs)") - String recentMessages(String roomCode, String playerId, String sinceMs) = - get($"api/chat/recent/{roomCode}/{playerId}/{sinceMs}"); - - /** - * Send a chat message and then immediately retrieve history. - */ - @Command("chat-flow", "Send message then read history (roomCode playerId message)") - String chatFlow(String roomCode, String playerId, String message) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Chat Flow ---\n"); - - buf.append("Send: "); - buf.append(post($|api/chat/send/{roomCode}/{playerId} - , $|\{"message":"{message}"\} - )).append('\n'); - - buf.append("History: "); - buf.append(get($"api/chat/history/{roomCode}/{playerId}")).append('\n'); - - return buf.toString(); - } - - /** - * Send three chat messages in quick succession, then fetch history. - */ - @Command("chat-burst", "Send 3 messages quickly then read history (roomCode playerId)") - String chatBurst(String roomCode, String playerId) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Chat Burst Test ---\n"); - - for (Int i : 1..3) { - buf.append($"Send {i}: "); - buf.append(post($|api/chat/send/{roomCode}/{playerId} - , $|\{"message":"Test message {i}"\} - )).append('\n'); - } - - buf.append("History: "); - buf.append(get($"api/chat/history/{roomCode}/{playerId}")).append('\n'); - - return buf.toString(); - } -} diff --git a/chess-game/app/cli/ChessGameManagement/GameFlowCommands.x b/chess-game/app/cli/ChessGameManagement/GameFlowCommands.x deleted file mode 100644 index c418f4b..0000000 --- a/chess-game/app/cli/ChessGameManagement/GameFlowCommands.x +++ /dev/null @@ -1,59 +0,0 @@ -import webcli.*; - -/** - * Scripted multi-move game sequences. - * - * Executes a fixed series of moves against the AI, printing the board state - * after each reply so the output can be inspected manually. - */ -mixin GameFlowCommands { - - /** - * Scholar's Mate (4-move checkmate): 1.e4 e5 2.Bc4 Nc6 3.Qh5 Nf6 4.Qxf7# - * - * Plays White's moves and polls state after each AI reply. - */ - @Command("scholars-mate", "Play Scholar's Mate sequence (sessionId)") - String scholarsMate(String sessionId) { - StringBuffer buf = new StringBuffer(); - - buf.append("--- Scholar's Mate Flow ---\n"); - buf.append(post($"api/reset/{sessionId}")).append('\n'); - - buf.append("1. e4: ").append(post($"api/move/{sessionId}/e2/e4")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("2. Bc4: ").append(post($"api/move/{sessionId}/f1/c4")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("3. Qh5: ").append(post($"api/move/{sessionId}/d1/h5")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("4. Qxf7#: ").append(post($"api/move/{sessionId}/h5/f7")).append('\n'); - buf.append("Final: ").append(get($"api/state/{sessionId}")).append('\n'); - - return buf.toString(); - } - - /** - * Italian Game opening: 1.e4 e5 2.Nf3 Nc6 3.Bc4 - */ - @Command("italian-opening", "Play Italian Game opening (sessionId)") - String italianOpening(String sessionId) { - StringBuffer buf = new StringBuffer(); - - buf.append("--- Italian Game Opening ---\n"); - buf.append(post($"api/reset/{sessionId}")).append('\n'); - - buf.append("1. e4: ").append(post($"api/move/{sessionId}/e2/e4")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("2. Nf3: ").append(post($"api/move/{sessionId}/g1/f3")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("3. Bc4: ").append(post($"api/move/{sessionId}/f1/c4")).append('\n'); - buf.append("Final: ").append(get($"api/state/{sessionId}")).append('\n'); - - return buf.toString(); - } -} diff --git a/chess-game/app/cli/ChessGameManagement/OnlineCommands.x b/chess-game/app/cli/ChessGameManagement/OnlineCommands.x deleted file mode 100644 index 0b63eb0..0000000 --- a/chess-game/app/cli/ChessGameManagement/OnlineCommands.x +++ /dev/null @@ -1,90 +0,0 @@ -import webcli.*; - -/** - * Online multiplayer chess commands. - * - * Covers the /api/online/... endpoints: - * - room lifecycle : create-room, join-room, online-reset, leave-room - * - gameplay : online-move, online-state, online-valid-moves - * - error probes : bad-room - * - scripted flow : online-flow - */ -mixin OnlineCommands { - - /** - * Create a new online room (caller becomes White). - */ - @Command("create-room", "Create a new online game room") - String createRoom() = post("api/online/create"); - - /** - * Join an existing room (caller becomes Black). - */ - @Command("join-room", "Join an online game room (roomCode)") - String joinRoom(String roomCode) = post($"api/online/join/{roomCode}"); - - /** - * Get the state of an online game. - */ - @Command("online-state", "Get online game state (roomCode playerId)") - String onlineState(String roomCode, String playerId) = - get($"api/online/state/{roomCode}/{playerId}"); - - /** - * Make a move in an online game. - */ - @Command("online-move", "Make a move online (roomCode playerId from target)") - String onlineMove(String roomCode, String playerId, String from, String target) = - post($"api/online/move/{roomCode}/{playerId}/{from}/{target}"); - - /** - * Reset an online game (preserves players). - */ - @Command("online-reset", "Reset an online game (roomCode playerId)") - String onlineReset(String roomCode, String playerId) = - post($"api/online/reset/{roomCode}/{playerId}"); - - /** - * Leave an online game. - */ - @Command("leave-room", "Leave an online game (roomCode playerId)") - String leaveRoom(String roomCode, String playerId) = - post($"api/online/leave/{roomCode}/{playerId}"); - - /** - * Get valid moves for a piece in an online game. - */ - @Command("online-valid-moves", "Get valid moves online (roomCode playerId square)") - String onlineValidMoves(String roomCode, String playerId, String square) = - get($"api/online/validmoves/{roomCode}/{playerId}/{square}"); - - /** - * Try to join a non-existent online room. - */ - @Command("bad-room", "Join a non-existent room") - String badRoom() = - post("api/online/join/ZZZZZ9"); - - /** - * Full online game lifecycle: create → join → move → state → reset → leave. - * - * Demonstrates the endpoint sequence; room code and player IDs must be - * extracted from the JSON responses and passed to subsequent commands. - */ - @Command("online-flow", "Run full online game lifecycle") - String onlineFlow() { - StringBuffer buf = new StringBuffer(); - buf.append("--- Full Online Game Flow ---\n"); - - buf.append("Create: ").append(post("api/online/create")).append('\n'); - - buf.append("(Extract roomCode & whitePlayerId from Create response above)\n"); - buf.append("(Then call: join-room )\n"); - buf.append("(Then call: online-move e2 e4)\n"); - buf.append("(Then call: online-state )\n"); - buf.append("(Then call: online-reset )\n"); - buf.append("(Then call: leave-room )\n"); - - return buf.toString(); - } -} diff --git a/chess-game/app/cli/ChessGameManagement/SinglePlayerCommands.x b/chess-game/app/cli/ChessGameManagement/SinglePlayerCommands.x deleted file mode 100644 index 27a6956..0000000 --- a/chess-game/app/cli/ChessGameManagement/SinglePlayerCommands.x +++ /dev/null @@ -1,129 +0,0 @@ -import webcli.*; - -/** - * Single-player chess commands. - * - * Covers the core /api/... endpoints: - * - game lifecycle : new-game, reset, game-state - * - move execution : move, valid-moves, promote - * - state inspection: opening-moves, move-history, reset-verify - * - error probes : bad-move, bad-session - */ -mixin SinglePlayerCommands { - - /** - * Start (or reset) a single-player game for the given session. - */ - @Command("new-game", "Reset/create a single-player game") - String newGame(String sessionId) = post($"api/reset/{sessionId}"); - - /** - * Get the current game state for a session. - */ - @Command("game-state", "Get current game state") - String gameState(String sessionId) = get($"api/state/{sessionId}"); - - /** - * Make a move in a single-player game. - * - * @param sessionId browser session id - * @param from source square (e.g. "e2") - * @param target destination (e.g. "e4") - */ - @Command("move", "Make a move (sessionId from target)") - String move(String sessionId, String from, String target) = - post($"api/move/{sessionId}/{from}/{target}"); - - /** - * List the valid destination squares for a piece. - */ - @Command("valid-moves", "Get valid moves for a square (sessionId square)") - String validMoves(String sessionId, String square) = - get($"api/validmoves/{sessionId}/{square}"); - - /** - * Reset a single-player game. - */ - @Command("reset", "Reset a single-player game") - String reset(String sessionId) = post($"api/reset/{sessionId}"); - - /** - * Make a move with pawn promotion (e.g. promote to queen). - */ - @Command("promote", "Move with promotion (sessionId from target piece)") - String promote(String sessionId, String from, String target, String piece) = - post($"api/move/{sessionId}/{from}/{target}?promotion={piece}"); - - /** - * Attempt an invalid move to verify error handling. - */ - @Command("bad-move", "Try an illegal move (sessionId from target)") - String badMove(String sessionId, String from, String target) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Testing invalid move ---\n"); - buf.append("Move ").append(from).append("->").append(target).append(": "); - buf.append(post($"api/move/{sessionId}/{from}/{target}")).append('\n'); - return buf.toString(); - } - - /** - * Attempt to move for a non-existent session. - */ - @Command("bad-session", "Test move with unknown session") - String badSession() = - post("api/move/nonexistent-session-xyz/e2/e4"); - - /** - * Get valid moves for all starting-position pawns and knights. - */ - @Command("opening-moves", "Show all opening pawn and knight moves (sessionId)") - String openingMoves(String sessionId) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Opening Valid Moves ---\n"); - buf.append(post($"api/reset/{sessionId}")).append('\n'); - - for (Char file : 'a'..'h') { - String square = $"{file}2"; - buf.append($"{square}: ").append(get($"api/validmoves/{sessionId}/{square}")).append('\n'); - } - buf.append("b1: ").append(get($"api/validmoves/{sessionId}/b1")).append('\n'); - buf.append("g1: ").append(get($"api/validmoves/{sessionId}/g1")).append('\n'); - - return buf.toString(); - } - - /** - * Play e4 then d4 and print the resulting move history. - */ - @Command("move-history", "Play e4-d4 and show move history (sessionId)") - String moveHistory(String sessionId) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Move History Test ---\n"); - buf.append(post($"api/reset/{sessionId}")).append('\n'); - - buf.append("1. e4: ").append(post($"api/move/{sessionId}/e2/e4")).append('\n'); - buf.append("State: ").append(get($"api/state/{sessionId}")).append('\n'); - - buf.append("2. d4: ").append(post($"api/move/{sessionId}/d2/d4")).append('\n'); - buf.append("Final state (with move history): ").append(get($"api/state/{sessionId}")).append('\n'); - - return buf.toString(); - } - - /** - * Verify that reset truly clears the board back to the starting position. - */ - @Command("reset-verify", "Make a move, reset, then verify initial state (sessionId)") - String resetVerify(String sessionId) { - StringBuffer buf = new StringBuffer(); - buf.append("--- Reset Verification ---\n"); - - buf.append("Initial: ").append(post($"api/reset/{sessionId}")).append('\n'); - buf.append("Move e4: ").append(post($"api/move/{sessionId}/e2/e4")).append('\n'); - buf.append("After move: ").append(get($"api/state/{sessionId}")).append('\n'); - buf.append("Reset: ").append(post($"api/reset/{sessionId}")).append('\n'); - buf.append("After reset: ").append(get($"api/state/{sessionId}")).append('\n'); - - return buf.toString(); - } -} diff --git a/chess-game/app/cli/ChessGameManagement/TimedGameCommands.x b/chess-game/app/cli/ChessGameManagement/TimedGameCommands.x deleted file mode 100644 index 473a3b0..0000000 --- a/chess-game/app/cli/ChessGameManagement/TimedGameCommands.x +++ /dev/null @@ -1,28 +0,0 @@ -import webcli.*; - -/** - * Time-control game creation commands. - * - * Wraps the standard reset / create endpoints with a JSON body that - * configures the clock for each player (milliseconds + increment). - */ -mixin TimedGameCommands { - - /** - * Start a timed single-player game (e.g. 5 minutes + 3 s increment). - */ - @Command("new-timed-game", "Start a timed game (sessionId timeMs incrementMs)") - String newTimedGame(String sessionId, String timeMs, String incrementMs) = - post($|api/reset/{sessionId} - , $|\{"timeControlMs":{timeMs},"incrementMs":{incrementMs}\} - ); - - /** - * Create an online room with time control. - */ - @Command("create-timed-room", "Create timed online room (timeMs incrementMs)") - String createTimedRoom(String timeMs, String incrementMs) = - post($|api/online/create - , $|\{"timeControlMs":{timeMs},"incrementMs":{incrementMs}\} - ); -} diff --git a/chess-game/app/src/main/x/chess.x b/chess-game/app/src/main/x/chess.x index 996e8e4..c62174c 100644 --- a/chess-game/app/src/main/x/chess.x +++ b/chess-game/app/src/main/x/chess.x @@ -9,6 +9,7 @@ import config.CastlingManager; import core.ChessLogic; import core.OnlineChessLogic; import ai.ChessAPIClient; +import ai.StockfishApi; /** * Chess Game Server Module * @@ -18,10 +19,13 @@ import ai.ChessAPIClient; * * Key features: * - Turn-based chess gameplay with simplified rules (no castling, en-passant, or check detection) - * - Single-player mode with automated opponent (Black player) with AI-driven move selection + * - Single-player mode whose opponent (Black) plays the moves returned by the Stockfish Online + * engine API; no move is chosen locally except as an offline fallback * - Online multiplayer mode with room-based matchmaking * - Game state persistence using the chess database schema * - RESTful API endpoints for moves, game state, room management, and game reset + * - An engine proxy (/api/engine) so the web client can read the same evaluations the + * computer plays by * - Static content serving for the web client interface */ @WebApp @@ -29,6 +33,7 @@ module chess.examples.org { // Package imports: organize dependencies from different modules package db import chessDB.examples.org; // Database schema and data models package web import web.xtclang.org; // Web framework for HTTP handling + package jsondb import jsondb.xtclang.org; // Opens the database when not hosted // Import specific web framework components import web.*; @@ -39,23 +44,74 @@ module chess.examples.org { import db.models.GameStatus; import db.models.Color; import db.models.OnlineGame; - import db.models.ChatMessage; /** - * Home Service - * - * Serves the static web client (HTML, CSS, JavaScript) for the chess game. - * All requests to the root path "/" are served with the index.html file - * from the public directory. + * Database access for the web services. + * + * When a host runs this application it supplies the schema by injection, and that is what the + * services get. Without a host -- e.g. a test invoking a service directly -- the injection + * yields Null, and this opens the `chessDB` module over `jsondb` instead, so the services work + * with nothing but the two compiled modules and a directory to write to. */ - @StaticContent("/", /public/index.html) - service Home {} + static service Database { + /** + * Where the database files are kept, relative to the working directory. + */ + static String DATA_DIR = "data/chessDB"; + + /** + * Where the generated database host module is written, relative to the working directory. + */ + static String BUILD_DIR = "build/db"; + + static String DB_MODULE = "chessDB.examples.org"; + + /** + * The open database. Created once, however many connections are handed out. + */ + @Lazy jsondb.Catalog catalog.calc() { + @Inject Directory curDir; + return jsondb.createCatalog(DB_MODULE, + curDir.dirFor(DATA_DIR).ensure(), + curDir.dirFor(BUILD_DIR).ensure()); + } + + /** + * A connection for one caller. Each web service holds its own, so that two requests are + * never sharing a transaction. + */ + ChessSchema connect() { + if (ChessSchema hosted := hostedSchema()) { + return hosted; + } + return catalog.createConnection().as(ChessSchema); + } + + /** + * The schema a host injects, under the name "schema" that the web services have always + * asked for. + * + * Containers disagree on how to report a resource they do not have: the top-level one + * `xec` creates yields Null for a nullable injection, while a nested one -- the test + * runner, or a platform hosting several apps -- throws. Both mean "not hosted". + */ + private conditional ChessSchema hostedSchema() { + try { + @Inject(resourceName="schema") ChessSchema? schema; + if (schema != Null) { + return True, schema; + } + } catch (Exception notHosted) {} + return False; + } + } /** - * Static Content Service + * Home Service * - * Serves static files (CSS, JS) from the /static path + * Serves the React/Vite web client for the chess game. The built output + * (webapp/build) is served from the root path "/". */ - @StaticContent("/static", /public/static/) - service StaticFiles {} + @StaticContent("/", /) + service Home {} } diff --git a/chess-game/app/src/main/x/chess/ai/AIMoveSelector.x b/chess-game/app/src/main/x/chess/ai/AIMoveSelector.x deleted file mode 100644 index 138b976..0000000 --- a/chess-game/app/src/main/x/chess/ai/AIMoveSelector.x +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Move ordering and heuristic scoring for search. - */ -service AIMoveSelector { - // Heuristic tuning constants used to prioritize move ordering. - static Int CASTLING_BONUS = 60; - static Int DEVELOPMENT_BONUS = 30; - static Int CENTER_BONUS = 25; - static Int CHECK_BONUS = 50; - - /** - * Scores one candidate move for ordering before deeper search. - */ - static Int scoreMoveHeuristic(Char piece, Int from, Int to, Char[] board, GameRecord record) { - Int score = 0; - Char target = board[to]; - - if (target != '.') { - score += AIPositionEvaluator.getPieceValue(target) * 10 - AIPositionEvaluator.getPieceValue(piece); - } - - if (piece == 'p' && BoardUtils.getRank(to) == 7) { - score += AIPositionEvaluator.QUEEN_VALUE - AIPositionEvaluator.PAWN_VALUE; - } - - if (piece == 'p') { - Int file = BoardUtils.getFile(to); - Int rank = BoardUtils.getRank(to); - if ((file == 3 || file == 4) && rank >= 3 && rank <= 5) { - score += CENTER_BONUS; - } - } - - if (record.moveHistory.size < 20 && (piece == 'n' || piece == 'b') && BoardUtils.getRank(from) == 0) { - score += DEVELOPMENT_BONUS; - } - - if (piece == 'k') { - Int fileDiff = (BoardUtils.getFile(to) - BoardUtils.getFile(from)).abs(); - if (fileDiff == 2) { - score += CASTLING_BONUS; - } - } - - Char[] testBoard = BoardUtils.cloneBoard(board); - testBoard[to] = piece; - testBoard[from] = '.'; - if (CheckDetection.isInCheck(testBoard.freeze(), Color.White)) { - score += CHECK_BONUS; - } - - return score; - } - - /** - * Collects all legal Black moves and sorts them by heuristic score (descending). - */ - static (Int[], Int[], Int[]) collectOrderedLegalMoves(GameRecord record, Char[] board) { - Int[] moveFroms = new Int[]; - Int[] moveTos = new Int[]; - Int[] moveScores = new Int[]; - - for (Int from : 0 ..< 64) { - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != Color.Black) { - continue; - } - for (Int to : 0 ..< 64) { - if (from == to) { - continue; - } - Char target = board[to]; - if (target != '.' && BoardUtils.colorOf(target) == Color.Black) { - continue; - } - if (!PieceValidator.isLegal(piece, from, to, board, - record.castlingRights, record.enPassantTarget)) { - continue; - } - - Char[] testBoard = BoardUtils.cloneBoard(record.board); - testBoard[to] = piece; - testBoard[from] = '.'; - if (CheckDetection.isInCheck(testBoard.freeze(), Color.Black)) { - continue; - } - - Int hScore = scoreMoveHeuristic(piece, from, to, board, record); - moveFroms = moveFroms + from; - moveTos = moveTos + to; - moveScores = moveScores + hScore; - } - } - - for (Int i : 0 ..< moveFroms.size) { - Int maxIdx = i; - for (Int j : i + 1 ..< moveFroms.size) { - if (moveScores[j] > moveScores[maxIdx]) { - maxIdx = j; - } - } - if (maxIdx != i) { - Int tmpF = moveFroms[i]; - Int tmpT = moveTos[i]; - Int tmpS = moveScores[i]; - moveFroms = moveFroms.replace(i, moveFroms[maxIdx]); - moveFroms = moveFroms.replace(maxIdx, tmpF); - moveTos = moveTos.replace(i, moveTos[maxIdx]); - moveTos = moveTos.replace(maxIdx, tmpT); - moveScores = moveScores.replace(i, moveScores[maxIdx]); - moveScores = moveScores.replace(maxIdx, tmpS); - } - } - - return (moveFroms, moveTos, moveScores); - } -} diff --git a/chess-game/app/src/main/x/chess/ai/AIOpeningBook.x b/chess-game/app/src/main/x/chess/ai/AIOpeningBook.x deleted file mode 100644 index d842001..0000000 --- a/chess-game/app/src/main/x/chess/ai/AIOpeningBook.x +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Opening book move selection. - */ -service AIOpeningBook { - // Candidate Black responses for early-game randomization. - static String[][] OPENING_RESPONSES = [ - ["e7e5", "c7c5", "e7e6", "c7c6", "d7d5", "g8f6"], - ["d7d5", "g8f6", "e7e6", "c7c5", "f7f5"], - ["g8f6", "d7d5", "e7e6", "c7c6", "e7e5", "c7c5", "g7g6"] - ]; - - /** - * Returns a legal opening move if one is available from the lightweight book. - */ - static (Int, Int) getOpeningMove(GameRecord record) { - if (record.moveHistory.size >= 12) { - return (-1, -1); - } - - Char[] board = BoardUtils.cloneBoard(record.board); - Int moveCount = record.moveHistory.size; - - Int[] validFroms = new Int[]; - Int[] validTos = new Int[]; - - for (String[] responses : OPENING_RESPONSES) { - for (String move : responses) { - if (move.size != 4) { - continue; - } - Int fromFile = move[0] - 'a'; - Int fromRank = 8 - (move[1] - '0'); - Int toFile = move[2] - 'a'; - Int toRank = 8 - (move[3] - '0'); - Int from = fromRank * 8 + fromFile; - Int to = toRank * 8 + toFile; - - if (from < 0 || from >= 64 || to < 0 || to >= 64) { - continue; - } - - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != Black) { - continue; - } - Char target = board[to]; - if (target != '.' && BoardUtils.colorOf(target) == Black) { - continue; - } - if (!PieceValidator.isLegal(piece, from, to, board, - record.castlingRights, record.enPassantTarget)) { - continue; - } - - Char[] testBoard = BoardUtils.cloneBoard(board); - testBoard[to] = piece; - testBoard[from] = '.'; - if (CheckDetection.isInCheck(testBoard.freeze(), Black)) { - continue; - } - - validFroms = validFroms + from; - validTos = validTos + to; - } - } - - if (validFroms.empty) { - return (-1, -1); - } - - Int index = AIUtility.hashRandom(moveCount * 1009, validFroms.size) % validFroms.size; - return (validFroms[index], validTos[index]); - } -} diff --git a/chess-game/app/src/main/x/chess/ai/AIPositionEvaluator.x b/chess-game/app/src/main/x/chess/ai/AIPositionEvaluator.x deleted file mode 100644 index 3920faf..0000000 --- a/chess-game/app/src/main/x/chess/ai/AIPositionEvaluator.x +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Position evaluation helpers for chess AI. - * Pure functions: no external mutable state. - */ -service AIPositionEvaluator { - // Evaluation bonuses and penalties. - static Int CHECK_BONUS = 50; - static Int ROOK_7TH_BONUS = 20; - static Int KING_PROXIMITY = 10; - - // Material values. - static Int PAWN_VALUE = 100; - static Int KNIGHT_VALUE = 320; - static Int BISHOP_VALUE = 330; - static Int ROOK_VALUE = 500; - static Int QUEEN_VALUE = 900; - static Int KING_VALUE = 20000; - - static Int[] PAWN_TABLE = [ - 0, 0, 0, 0, 0, 0, 0, 0, - 50, 50, 50, 50, 50, 50, 50, 50, - 10, 10, 20, 30, 30, 20, 10, 10, - 5, 5, 10, 25, 25, 10, 5, 5, - 0, 0, 0, 20, 20, 0, 0, 0, - 5, -5,-10, 0, 0,-10, -5, 5, - 5, 10, 10,-20,-20, 10, 10, 5, - 0, 0, 0, 0, 0, 0, 0, 0 - ]; - - static Int[] KNIGHT_TABLE = [ - -50,-40,-30,-30,-30,-30,-40,-50, - -40,-20, 0, 0, 0, 0,-20,-40, - -30, 0, 10, 15, 15, 10, 0,-30, - -30, 5, 15, 20, 20, 15, 5,-30, - -30, 0, 15, 20, 20, 15, 0,-30, - -30, 5, 10, 15, 15, 10, 5,-30, - -40,-20, 0, 5, 5, 0,-20,-40, - -50,-40,-30,-30,-30,-30,-40,-50 - ]; - - static Int[] BISHOP_TABLE = [ - -20,-10,-10,-10,-10,-10,-10,-20, - -10, 0, 0, 0, 0, 0, 0,-10, - -10, 0, 5, 10, 10, 5, 0,-10, - -10, 5, 5, 10, 10, 5, 5,-10, - -10, 0, 10, 10, 10, 10, 0,-10, - -10, 10, 10, 10, 10, 10, 10,-10, - -10, 5, 0, 0, 0, 0, 5,-10, - -20,-10,-10,-10,-10,-10,-10,-20 - ]; - - static Int[] ROOK_TABLE = [ - 0, 0, 0, 0, 0, 0, 0, 0, - 5, 10, 10, 10, 10, 10, 10, 5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - 0, 0, 0, 5, 5, 0, 0, 0 - ]; - - static Int[] QUEEN_TABLE = [ - -20,-10,-10, -5, -5,-10,-10,-20, - -10, 0, 0, 0, 0, 0, 0,-10, - -10, 0, 5, 5, 5, 5, 0,-10, - -5, 0, 5, 5, 5, 5, 0, -5, - 0, 0, 5, 5, 5, 5, 0, -5, - -10, 5, 5, 5, 5, 5, 0,-10, - -10, 0, 5, 0, 0, 0, 0,-10, - -20,-10,-10, -5, -5,-10,-10,-20 - ]; - - static Int[] KING_TABLE_MID = [ - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -20,-30,-30,-40,-40,-30,-30,-20, - -10,-20,-20,-20,-20,-20,-20,-10, - 20, 20, 0, 0, 0, 0, 20, 20, - 20, 30, 10, 0, 0, 10, 30, 20 - ]; - - static Int[] KING_TABLE_END = [ - -50,-40,-30,-20,-20,-30,-40,-50, - -30,-20,-10, 0, 0,-10,-20,-30, - -30,-10, 20, 30, 30, 20,-10,-30, - -30,-10, 30, 40, 40, 30,-10,-30, - -30,-10, 30, 40, 40, 30,-10,-30, - -30,-10, 20, 30, 30, 20,-10,-30, - -30,-30, 0, 0, 0, 0,-30,-30, - -50,-30,-30,-30,-30,-30,-30,-50 - ]; - - static Int[] PASSED_PAWN_BONUS = [0, 120, 80, 50, 30, 15, 10, 0]; - - /** - * Returns the material value for a piece symbol. - */ - static Int getPieceValue(Char piece) { - switch (piece.lowercase) { - case 'p': return PAWN_VALUE; - case 'n': return KNIGHT_VALUE; - case 'b': return BISHOP_VALUE; - case 'r': return ROOK_VALUE; - case 'q': return QUEEN_VALUE; - case 'k': return KING_VALUE; - default: return 0; - } - } - - /** - * Returns piece-square table value, mirrored for Black pieces. - */ - static Int getPSTValue(Char piece, Int square, Boolean isEndgame) { - Boolean isWhite = 'A' <= piece <= 'Z'; - Int index = isWhite ? square : (63 - square); - - switch (piece.lowercase) { - case 'p': return PAWN_TABLE[index]; - case 'n': return KNIGHT_TABLE[index]; - case 'b': return BISHOP_TABLE[index]; - case 'r': return ROOK_TABLE[index]; - case 'q': return QUEEN_TABLE[index]; - case 'k': return isEndgame ? KING_TABLE_END[index] : KING_TABLE_MID[index]; - default: return 0; - } - } - - /** - * Detects simplified positions where endgame king tables are preferred. - */ - static Boolean isEndgame(Char[] board) { - Int whiteQueens = 0; - Int blackQueens = 0; - Int whiteMinor = 0; - Int blackMinor = 0; - - for (Int i : 0 ..< 64) { - switch (board[i]) { - case 'Q': whiteQueens++; break; - case 'q': blackQueens++; break; - case 'R': whiteMinor++; break; - case 'r': blackMinor++; break; - case 'B': whiteMinor++; break; - case 'b': blackMinor++; break; - case 'N': whiteMinor++; break; - case 'n': blackMinor++; break; - default: break; - } - } - - if (whiteQueens == 0 && blackQueens == 0) { - return True; - } - return whiteQueens <= 1 && whiteMinor <= 1 - && blackQueens <= 1 && blackMinor <= 1; - } - - /** - * Checks whether a pawn has no opposing pawns ahead on adjacent files. - */ - static Boolean isPassedPawn(Char[] board, Int square, Char pawn) { - Int file = BoardUtils.getFile(square); - Int rank = BoardUtils.getRank(square); - Int minFile = file > 0 ? file - 1 : 0; - Int maxFile = file < 7 ? file + 1 : 7; - - if (pawn == 'p') { - for (Int r : rank + 1 ..< 8) { - for (Int f : minFile ..< maxFile + 1) { - if (board[r * 8 + f] == 'P') { - return False; - } - } - } - } else { - for (Int r : 0 ..< rank) { - for (Int f : minFile ..< maxFile + 1) { - if (board[r * 8 + f] == 'p') { - return False; - } - } - } - } - return True; - } - - /** - * Computes king distance for endgame opposition/proximity scoring. - */ - static Int chebyshevDistance(Int sq1, Int sq2) { - Int rankDiff = (BoardUtils.getRank(sq1) - BoardUtils.getRank(sq2)).abs(); - Int fileDiff = (BoardUtils.getFile(sq1) - BoardUtils.getFile(sq2)).abs(); - return rankDiff.maxOf(fileDiff); - } - - /** - * Produces a signed score from Black's perspective (higher is better for Black). - */ - static Int evaluateBoard(Char[] board, GameRecord record) { - Int score = 0; - Boolean endgame = isEndgame(board); - Int whiteKingPos = -1; - Int blackKingPos = -1; - - for (Int i : 0 ..< 64) { - Char piece = board[i]; - if (piece == '.') { - continue; - } - - if (piece == 'K') { whiteKingPos = i; } - if (piece == 'k') { blackKingPos = i; } - - Int matValue = getPieceValue(piece); - Int posValue = getPSTValue(piece, i, endgame); - - if ('A' <= piece <= 'Z') { - score -= matValue + posValue; - } else { - score += matValue + posValue; - } - - if (piece == 'r' && BoardUtils.getRank(i) == 6) { - score += ROOK_7TH_BONUS; - } else if (piece == 'R' && BoardUtils.getRank(i) == 1) { - score -= ROOK_7TH_BONUS; - } - - if (endgame && (piece == 'p' || piece == 'P')) { - if (isPassedPawn(board, i, piece)) { - Int rank = BoardUtils.getRank(i); - if (piece == 'p') { - score += PASSED_PAWN_BONUS[rank]; - } else { - score -= PASSED_PAWN_BONUS[7 - rank]; - } - } - } - } - - immutable Char[] immutableBoard = board.freeze(); - if (CheckDetection.isInCheck(immutableBoard, Color.White)) { - score += CHECK_BONUS; - } - if (CheckDetection.isInCheck(immutableBoard, Color.Black)) { - score -= CHECK_BONUS; - } - - if (endgame && whiteKingPos >= 0 && blackKingPos >= 0) { - score -= chebyshevDistance(whiteKingPos, blackKingPos) * KING_PROXIMITY; - } - - return score; - } -} diff --git a/chess-game/app/src/main/x/chess/ai/AISearchEngine.x b/chess-game/app/src/main/x/chess/ai/AISearchEngine.x deleted file mode 100644 index 2db72b3..0000000 --- a/chess-game/app/src/main/x/chess/ai/AISearchEngine.x +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Minimax search with alpha-beta pruning. - */ -service AISearchEngine { - // Search score bounds and terminal score. - static Int MIN_SCORE = -1000000; - static Int MAX_SCORE = 1000000; - static Int CHECKMATE_SCORE = 100000; - - /** - * Runs depth-limited minimax with alpha-beta pruning. - */ - static Int minimax(Char[] board, GameRecord record, Int depth, - Int alpha, Int beta, Boolean isMaximizing) { - if (depth <= 0) { - return AIPositionEvaluator.evaluateBoard(board, record); - } - - Color turn = isMaximizing ? Black : White; - Boolean inCheck = CheckDetection.isInCheck(board.freeze(), turn); - Boolean hasLegalMove = False; - - if (isMaximizing) { - Int maxEval = MIN_SCORE; - for (Int from : 0 ..< 64) { - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != turn) { - continue; - } - for (Int to : 0 ..< 64) { - if (from == to) { - continue; - } - Char target = board[to]; - if (target != '.' && BoardUtils.colorOf(target) == turn) { - continue; - } - if (!PieceValidator.isLegal(piece, from, to, board, - record.castlingRights, record.enPassantTarget)) { - continue; - } - - Char[] newBoard = BoardUtils.cloneBoard(board); - newBoard[to] = piece; - newBoard[from] = '.'; - if (piece == 'p' && BoardUtils.getRank(to) == 7) { - newBoard[to] = 'q'; - } - if (CheckDetection.isInCheck(newBoard.freeze(), turn)) { - continue; - } - - hasLegalMove = True; - Int eval = minimax(newBoard, record, depth - 1, alpha, beta, False); - if (eval > maxEval) { - maxEval = eval; - } - if (eval > alpha) { - alpha = eval; - } - if (beta <= alpha) { - return maxEval; - } - } - } - if (!hasLegalMove) { - return inCheck ? -CHECKMATE_SCORE : 0; - } - return maxEval; - } - - Int minEval = MAX_SCORE; - for (Int from : 0 ..< 64) { - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != turn) { - continue; - } - for (Int to : 0 ..< 64) { - if (from == to) { - continue; - } - Char target = board[to]; - if (target != '.' && BoardUtils.colorOf(target) == turn) { - continue; - } - if (!PieceValidator.isLegal(piece, from, to, board, - record.castlingRights, record.enPassantTarget)) { - continue; - } - - Char[] newBoard = BoardUtils.cloneBoard(board); - newBoard[to] = piece; - newBoard[from] = '.'; - if (piece == 'P' && BoardUtils.getRank(to) == 0) { - newBoard[to] = 'Q'; - } - if (CheckDetection.isInCheck(newBoard.freeze(), turn)) { - continue; - } - - hasLegalMove = True; - Int eval = minimax(newBoard, record, depth - 1, alpha, beta, True); - if (eval < minEval) { - minEval = eval; - } - if (eval < beta) { - beta = eval; - } - if (beta <= alpha) { - return minEval; - } - } - } - - if (!hasLegalMove) { - return inCheck ? CHECKMATE_SCORE : 0; - } - return minEval; - } -} diff --git a/chess-game/app/src/main/x/chess/ai/ChessAI.x b/chess-game/app/src/main/x/chess/ai/ChessAI.x deleted file mode 100644 index 73ada3a..0000000 --- a/chess-game/app/src/main/x/chess/ai/ChessAI.x +++ /dev/null @@ -1,217 +0,0 @@ -/** - * Legacy AI facade kept for compatibility. - * Core logic lives in dedicated helper services. - */ -service ChessAI { - // Legacy score constants retained for older call sites. - static Int MIN_SCORE = -1000000; - static Int MAX_SCORE = 1000000; - static Int CHECKMATE_SCORE = 100000; - - static Int getPieceValue(Char piece) { - return AIPositionEvaluator.getPieceValue(piece); - } - - static Int getPieceSquareValue(Char piece, Int square, Boolean isBlack) { - Boolean isEndgame = False; - return AIPositionEvaluator.getPSTValue(piece, square, isEndgame); - } - - static Boolean isEndgame(Char[] board) { - return AIPositionEvaluator.isEndgame(board); - } - - static Int totalMaterial(Char[] board) { - Int total = 0; - for (Int i : 0 ..< 64) { - Char piece = board[i]; - if (piece != '.' && piece != 'K' && piece != 'k') { - total += AIPositionEvaluator.getPieceValue(piece); - } - } - return total; - } - - static Int evaluateBoard(Char[] board, GameRecord record) { - return AIPositionEvaluator.evaluateBoard(board, record); - } - /** - * Counts pseudo-legal mobility for a side. - */ - - static Int chebyshevDistance(Int sq1, Int sq2) { - return AIPositionEvaluator.chebyshevDistance(sq1, sq2); - } - - static Boolean isPassedPawn(Char[] board, Int square, Char pawn) { - return AIPositionEvaluator.isPassedPawn(board, square, pawn); - } - - static Int countMobility(Char[] board, Color color, GameRecord record) { - Int moveCount = 0; - for (Int from : 0 ..< 64) { - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != color) { - continue; - } - for (Int to : 0 ..< 64) { - if (from != to && PieceValidator.isLegal(piece, from, to, board, record.castlingRights, record.enPassantTarget)) { - Char target = board[to]; - if (target == '.' || BoardUtils.colorOf(target) != color) { - moveCount++; - } - } - } - } - return moveCount; - } - - /** - * Scores one move using heuristic + shallow evaluation blend. - */ - static Int scoreMove(Char piece, Int from, Int to, Char[] board, GameRecord record) { - Int score = AIMoveSelector.scoreMoveHeuristic(piece, from, to, board, record); - - Char[] testBoard = BoardUtils.cloneBoard(board); - testBoard[to] = piece; - testBoard[from] = '.'; - if (piece == 'p' && BoardUtils.getRank(to) == 7) { - testBoard[to] = 'q'; - score += AIPositionEvaluator.QUEEN_VALUE - AIPositionEvaluator.PAWN_VALUE; - } - - score += AIPositionEvaluator.evaluateBoard(testBoard, record) / 10; - return score; - } - - static Int hashRandom(Int seed, Int counter) { - return AIUtility.hashRandom(seed, counter); - } - - static Int randomInt(Int max, Int moveCount, Int counter) { - if (max <= 0) { - return 0; - } - Int rand = AIUtility.hashRandom(moveCount * 1009 + counter * 7919, counter); - return rand % max; - } - - static Boolean isOpeningPhase(GameRecord record) { - return record.moveHistory.size < 12; - } - - static (Int, Int) getOpeningMove(GameRecord record) { - return AIOpeningBook.getOpeningMove(record); - } - - /** - * Queries the modern API client and returns move with evaluation score. - */ - static (Int, Int, Int) findBestMove(GameRecord record) { - ChessAPIClient client = new ChessAPIClient(); - (Int from, Int to, String? promotion) = client.findBestMove(record); - if (from < 0 || to < 0) { - return (-1, -1, MIN_SCORE); - } - - Char[] board = BoardUtils.cloneBoard(record.board); - Char piece = board[from]; - board[to] = piece; - board[from] = '.'; - if (promotion != Null && promotion == "q") { - board[to] = 'q'; - } - - Int score = AIPositionEvaluator.evaluateBoard(board, record); - return (from, to, score); - } - - /** - * Legacy minimax wrapper that picks best move from ordered candidates. - */ - static (Int, Int, Int) findBestMoveWithMinimax(GameRecord record, Char[] board, Int depth) { - (Int[] froms, Int[] tos, Int[] scores) = AIMoveSelector.collectOrderedLegalMoves(record, board); - if (froms.empty) { - return (-1, -1, MIN_SCORE); - } - - Int bestScore = MIN_SCORE; - Int bestFrom = froms[0]; - Int bestTo = tos[0]; - Int alpha = MIN_SCORE; - Int beta = MAX_SCORE; - - for (Int i : 0 ..< froms.size) { - Int from = froms[i]; - Int to = tos[i]; - Char piece = board[from]; - - Char[] newBoard = BoardUtils.cloneBoard(board); - newBoard[to] = piece; - newBoard[from] = '.'; - if (piece == 'p' && BoardUtils.getRank(to) == 7) { - newBoard[to] = 'q'; - } - - Int score = AISearchEngine.minimax(newBoard, record, depth - 1, alpha, beta, False); - if (score > bestScore) { - bestScore = score; - bestFrom = from; - bestTo = to; - } - if (score > alpha) { - alpha = score; - } - } - - return (bestFrom, bestTo, bestScore); - } - - static Int minimax(Char[] board, GameRecord record, Int depth, Int alpha, Int beta, Boolean isMaximizing) { - return AISearchEngine.minimax(board, record, depth, alpha, beta, isMaximizing); - } - - /** - * Heuristic-only move picker with bounded randomness among top choices. - */ - static (Int, Int, Int) findBestMoveHeuristic(GameRecord record, Char[] board) { - (Int[] allFroms, Int[] allTos, Int[] allScores) = AIMoveSelector.collectOrderedLegalMoves(record, board); - if (allFroms.empty) { - return (-1, -1, MIN_SCORE); - } - - Int bestScore = allScores[0]; - for (Int i : 1 ..< allScores.size) { - if (allScores[i] > bestScore) { - bestScore = allScores[i]; - } - } - - Int threshold = (bestScore.abs() * 15) / 100; - if (threshold < 50) { - threshold = 50; - } - Int minAcceptableScore = bestScore - threshold; - - Int[] topFroms = new Int[]; - Int[] topTos = new Int[]; - Int[] topScores = new Int[]; - - for (Int i : 0 ..< allFroms.size) { - if (allScores[i] >= minAcceptableScore) { - topFroms = topFroms + allFroms[i]; - topTos = topTos + allTos[i]; - topScores = topScores + allScores[i]; - } - } - - if (topFroms.size > 5) { - topFroms = topFroms[0 ..< 5]; - topTos = topTos[0 ..< 5]; - topScores = topScores[0 ..< 5]; - } - - Int index = randomInt(topFroms.size, record.moveHistory.size, topFroms.size + allFroms.size); - return (topFroms[index], topTos[index], topScores[index]); - } -} diff --git a/chess-game/app/src/main/x/chess/ai/ChessAPIClient.x b/chess-game/app/src/main/x/chess/ai/ChessAPIClient.x index 41a70dd..0fbfdeb 100644 --- a/chess-game/app/src/main/x/chess/ai/ChessAPIClient.x +++ b/chess-game/app/src/main/x/chess/ai/ChessAPIClient.x @@ -1,133 +1,68 @@ /** * Chess AI public entrypoint. * - * Responsibilities are split into dedicated services: - * - AIPositionEvaluator: board/position scoring - * - AISearchEngine: minimax + alpha-beta - * - AIOpeningBook: opening move suggestions - * - AIMoveSelector: legal move collection + ordering + * Computer gameplay comes from the Stockfish Online API via [StockfishApi]; this service does + * not choose moves of its own. A random legal move is the only fallback when the engine cannot + * be reached: + * - StockfishApi: the engine that plays the computer's moves * - AIUtility: randomness, fallback move, FEN conversion */ service ChessAPIClient { - // Shared score constants for search decisions. - static Int MIN_SCORE = -1000000; - static Int MAX_SCORE = 1000000; - static Int CHECKMATE_SCORE = 100000; - - static Int getPieceValue(Char piece) { - return AIPositionEvaluator.getPieceValue(piece); - } - - static Int getPSTValue(Char piece, Int square, Boolean isEndgame) { - return AIPositionEvaluator.getPSTValue(piece, square, isEndgame); - } - - static Boolean isEndgame(Char[] board) { - return AIPositionEvaluator.isEndgame(board); - } - - static Boolean isPassedPawn(Char[] board, Int square, Char pawn) { - return AIPositionEvaluator.isPassedPawn(board, square, pawn); - } - - static Int chebyshevDistance(Int sq1, Int sq2) { - return AIPositionEvaluator.chebyshevDistance(sq1, sq2); - } - - static Int evaluateBoard(Char[] board, GameRecord record) { - return AIPositionEvaluator.evaluateBoard(board, record); - } - - static Int minimax(Char[] board, GameRecord record, Int depth, - Int alpha, Int beta, Boolean isMaximizing) { - return AISearchEngine.minimax(board, record, depth, alpha, beta, isMaximizing); - } - - static Int scoreMoveHeuristic(Char piece, Int from, Int to, Char[] board, GameRecord record) { - return AIMoveSelector.scoreMoveHeuristic(piece, from, to, board, record); - } - - static Int hashRandom(Int seed, Int counter) { - return AIUtility.hashRandom(seed, counter); - } + /** + * Search depth asked of the engine for computer moves. Deeper play costs response time, and + * the upstream API rejects anything over 15. + */ + static Int SEARCH_DEPTH = 12; - static (Int, Int) getOpeningMove(GameRecord record) { - return AIOpeningBook.getOpeningMove(record); - } + // The engine that plays every computer move + StockfishApi engine = new StockfishApi(); /** * Main AI move selection entrypoint used by game logic. + * + * The move comes from the engine. It is still checked against this board's rules before + * being returned, because the game uses a simplified rule set and cannot always play what + * a full engine suggests (castling, for instance). An unusable or missing answer falls back + * to a random legal move so that the game never stalls when the engine is unreachable. */ (Int, Int, String?) findBestMove(GameRecord record) { - Int moveCount = record.moveHistory.size; + String fen = AIUtility.boardToFen(record); + StockfishApi.EngineMove move = engine.bestMove(fen, SEARCH_DEPTH); - (Int openFrom, Int openTo) = AIOpeningBook.getOpeningMove(record); - if (openFrom >= 0 && openTo >= 0) { - if (AIUtility.hashRandom(moveCount, 1) % 100 < 70) { - return (openFrom, openTo, Null); - } + if (move.usable && isPlayable(record, move.fromIndex, move.toIndex)) { + return (move.fromIndex, move.toIndex, move.promotion); } - Char[] board = BoardUtils.cloneBoard(record.board); - Boolean endgame = AIPositionEvaluator.isEndgame(board); - Int depth = endgame ? 3 : 2; + return AIUtility.findRandomLegalMove(record); + } - (Int[] moveFroms, Int[] moveTos, Int[] moveScores) = AIMoveSelector.collectOrderedLegalMoves(record, board); - if (moveFroms.empty) { - return (-1, -1, Null); + /** + * Whether the side to move can legally play from one square to another under this game's + * rules, and without leaving its own king in check. + */ + private static Boolean isPlayable(GameRecord record, Int from, Int to) { + if (!BoardUtils.isValidSquare(from) || !BoardUtils.isValidSquare(to) || from == to) { + return False; } - Int bestScore = MIN_SCORE; - Int bestFrom = moveFroms[0]; - Int bestTo = moveTos[0]; - String? bestPromotion = Null; - Int alpha = MIN_SCORE; - Int beta = MAX_SCORE; - - for (Int i : 0 ..< moveFroms.size) { - Int from = moveFroms[i]; - Int to = moveTos[i]; - Char piece = board[from]; - - Char[] newBoard = BoardUtils.cloneBoard(record.board); - newBoard[to] = piece; - newBoard[from] = '.'; - String? promo = Null; - if (piece == 'p' && BoardUtils.getRank(to) == 7) { - newBoard[to] = 'q'; - promo = "q"; - } - - Int score = AISearchEngine.minimax(newBoard, record, depth - 1, alpha, beta, False); - - Int variety = AIUtility.hashRandom(from * 64 + to, moveCount + i) % 5; - score += variety; - - if (score > bestScore) { - bestScore = score; - bestFrom = from; - bestTo = to; - bestPromotion = promo; - } - if (score > alpha) { - alpha = score; - } + Char[] board = BoardUtils.cloneBoard(record.board); + Char piece = board[from]; + if (piece == '.' || BoardUtils.colorOf(piece) != record.turn) { + return False; } - return (bestFrom, bestTo, bestPromotion); - } - - /** - * Returns a legal random fallback move when needed. - */ - static (Int, Int, String?) findRandomLegalMove(GameRecord record) { - return AIUtility.findRandomLegalMove(record); - } + Char target = board[to]; + if (target != '.' && BoardUtils.colorOf(target) == record.turn) { + return False; + } + if (!PieceValidator.isLegal(piece, from, to, board, + record.castlingRights, record.enPassantTarget)) { + return False; + } - /** - * Exposes FEN conversion for external consumers. - */ - static String boardToFen(GameRecord record) { - return AIUtility.boardToFen(record); + Char[] tested = BoardUtils.cloneBoard(board); + tested[to] = piece; + tested[from] = '.'; + return !CheckDetection.isInCheck(tested.freeze(), record.turn); } } diff --git a/chess-game/app/src/main/x/chess/ai/StockfishApi.x b/chess-game/app/src/main/x/chess/ai/StockfishApi.x new file mode 100644 index 0000000..56d0014 --- /dev/null +++ b/chess-game/app/src/main/x/chess/ai/StockfishApi.x @@ -0,0 +1,188 @@ +import web.HttpClient; +import web.RequestOut; +import web.ResponseIn; +/** + * Stockfish Online client. + * + * All computer gameplay comes from this API; nothing in this service decides a move on its own. + * The upstream endpoint is https://stockfish.online/api/s/v2.php, which answers for any legal + * FEN with: + * + * {"success":true,"evaluation":0.46,"mate":null, + * "bestmove":"bestmove e7e5 ponder g1f3","continuation":"e7e5 g1f3 b8c6 ..."} + * + * or, on a rejected request: + * + * {"success":false,"error":"Invalid FEN"} + * + * Numbers are relayed as text so that this service never has to interpret them; the only field + * it reads is `bestmove`, which it turns into a pair of board indices for the game logic. + */ +service StockfishApi { + static String BASE_URI = "https://stockfish.online/api/s/v2.php"; + static String USER_AGENT = "xtc-chess-game-example"; + + /** + * Search depth used for computer moves. The upstream API rejects anything over 15, and the + * response time grows quickly with depth, so this sits in the middle of the usable range. + */ + static Int DEFAULT_DEPTH = 12; + static Int MAX_DEPTH = 15; + static Int MIN_DEPTH = 1; + + // Nibble-to-hex lookup used by urlEncode + static String HEX_DIGITS = "0123456789ABCDEF"; + + // Reused across requests; HttpClient is a const and holds no per-request state + HttpClient client = new HttpClient(); + + /** + * One answer from the engine. Every numeric field is kept as text, exactly as the API sent + * it: `evaluation` is in pawns from White's point of view and is Null in a forced mate, + * where `mate` carries the signed distance to mate instead. + */ + static const EngineReply(Boolean success, + String? bestMove = Null, + String? evaluation = Null, + String? mate = Null, + String? continuation = Null, + String? error = Null); + + /** + * A move as the game logic needs it: two board indices plus an optional promotion piece. + * Both indices are -1 when the engine gave no usable move. + */ + static const EngineMove(Int fromIndex, Int toIndex, String? promotion = Null) { + @RO Boolean usable.get() = fromIndex >= 0 && toIndex >= 0; + } + + /** + * Asks the engine to analyse a position. + * + * @param fen the position in Forsyth-Edwards notation + * @param depth search depth, clamped to the range the API accepts + * + * @return the engine's reply, or an unsuccessful reply if the API could not be reached + */ + EngineReply analyse(String fen, Int depth = DEFAULT_DEPTH) { + Int safeDepth = depth.notLessThan(MIN_DEPTH).notGreaterThan(MAX_DEPTH); + String uri = $"{BASE_URI}?fen={urlEncode(fen)}&depth={safeDepth}"; + + String json; + try { + RequestOut request = client.createRequest(GET, new Uri(uri)); + request.header["User-Agent"] = USER_AGENT; + request.header["Accept"] = "application/json"; + + ResponseIn response = client.send(request); + Byte[] bytes = response.body?.bytes : []; + json = bytes.unpackUtf8(); + } catch (Exception e) { + return new EngineReply(False, error = "Stockfish request failed"); + } + + if (jsonField(json, "success") != "true") { + return new EngineReply(False, error = jsonField(json, "error") ?: "Engine declined"); + } + + return new EngineReply(True, + bestMove = jsonField(json, "bestmove"), + evaluation = jsonField(json, "evaluation"), + mate = jsonField(json, "mate"), + continuation = jsonField(json, "continuation")); + } + + /** + * Asks the engine for the move to play in a position. + * + * @return the engine's move, or an unusable move if the engine gave no answer + */ + EngineMove bestMove(String fen, Int depth = DEFAULT_DEPTH) { + EngineReply reply = analyse(fen, depth); + if (String line ?= reply.bestMove) { + return parseBestMove(line); + } + return new EngineMove(-1, -1); + } + + /** + * Pulls the move out of a UCI `bestmove` line, e.g. "bestmove e7e5 ponder g1f3" or + * "bestmove a7a8q". A missing or malformed move yields an unusable [EngineMove]. + */ + static EngineMove parseBestMove(String line) { + String uci = ""; + for (String token : line.split(' ')) { + String trimmed = token.trim(); + if (trimmed.size >= 4 && trimmed != "bestmove" && trimmed != "ponder") { + uci = trimmed; + break; + } + } + if (uci.size < 4) { + return new EngineMove(-1, -1); + } + + Int from = BoardUtils.parseSquare(uci[0 ..< 2]); + Int to = BoardUtils.parseSquare(uci[2 ..< 4]); + if (from < 0 || to < 0) { + return new EngineMove(-1, -1); + } + + String? promotion = uci.size > 4 ? uci[4 ..< 5].toLowercase() : Null; + return new EngineMove(from, to, promotion); + } + + /** + * Reads one field out of the flat JSON object the API returns. Quoted strings come back + * unquoted; bare numbers and booleans come back as their text; `null` and absent fields come + * back as Null. + */ + static String? jsonField(String json, String name) { + String needle = $"\"{name}\""; + if (Int keyAt := json.indexOf(needle)) { + Int cursor = keyAt + needle.size; + while (cursor < json.size && (json[cursor] == ' ' || json[cursor] == ':')) { + cursor++; + } + if (cursor >= json.size) { + return Null; + } + + if (json[cursor] == '"') { + cursor++; + Int start = cursor; + while (cursor < json.size && json[cursor] != '"') { + cursor++; + } + return json[start ..< cursor]; + } + + Int start = cursor; + while (cursor < json.size && json[cursor] != ',' && json[cursor] != '}') { + cursor++; + } + String raw = json[start ..< cursor].trim(); + return raw == "null" || raw.size == 0 ? Null : raw; + } + return Null; + } + + /** + * Percent-encodes everything outside the unreserved set, so a FEN -- which contains spaces + * and slashes -- can be carried in a query string. + */ + static String urlEncode(String text) { + StringBuffer encoded = new StringBuffer(); + for (Char ch : text) { + if (ch.asciiLetter() || ch.asciiDigit() || ch == '-' || ch == '_' || ch == '.' || ch == '~') { + encoded.add(ch); + } else { + Int code = ch.codepoint.toInt(); + encoded.add('%'); + encoded.add(HEX_DIGITS[(code & 0xF0) >> 4]); + encoded.add(HEX_DIGITS[code & 0x0F]); + } + } + return encoded.toString(); + } +} diff --git a/chess-game/app/src/main/x/chess/api/ChatApi.x b/chess-game/app/src/main/x/chess/api/ChatApi.x deleted file mode 100644 index 496bd13..0000000 --- a/chess-game/app/src/main/x/chess/api/ChatApi.x +++ /dev/null @@ -1,175 +0,0 @@ -import utils.BoardUtils; -import utils.BoardOperations; -import utils.DirectionUtils; -import utils.ChatAPIResponseTypes.*; -import validation.PieceValidator; -import validation.CheckDetection; -import validation.MoveValidator; -import validation.ValidMovesHelper; -import config.CastlingManager; -import core.ChessLogic; -import core.OnlineChessLogic; -/** - * ChatApi Service - * - * RESTful API service for online chat functionality in multiplayer chess games. - * Provides endpoints for: - * - Sending chat messages in a game room - * - Retrieving chat history for a room - * - * All operations require a valid room code and player ID for authentication. - */ -@WebService("/api/chat") -service ChatApi { - // Injected dependencies - @Inject ChessSchema schema; - @Inject Clock clock; - - /** - * POST /api/chat/send/{roomCode}/{playerId} - * - * Sends a chat message to the specified room. - * - * @param roomCode The room code identifying the game - * @param playerId The player's session ID - * @param request The request body containing the message - * @return SendMessageResponse indicating success or failure - */ - @Post("send/{roomCode}/{playerId}") - @Produces(Json) - @HttpsRequired - SendMessageResponse sendMessage(String roomCode, String playerId, @BodyParam SendMessageRequest request) { - using (schema.createTransaction()) { - // Verify the room exists - if (OnlineGame game := schema.onlineGames.get(roomCode)) { - // Verify the player is in this room - if (!game.hasPlayer(playerId)) { - return new SendMessageResponse(False, "You are not a player in this room", Null); - } - - // Get player's color - Color? color = game.getPlayerColor(playerId); - if (color == Null) { - return new SendMessageResponse(False, "Could not determine player color", Null); - } - - // Validate message content - String trimmed = request.message.trim(); - if (trimmed.size == 0) { - return new SendMessageResponse(False, "Message cannot be empty", Null); - } - if (trimmed.size > 500) { - return new SendMessageResponse(False, "Message too long (max 500 characters)", Null); - } - - // Create and store the chat message - // Use message count for ordering - Time timestamp = clock.now; - ChatMessage msg = new ChatMessage(roomCode, playerId, color, trimmed, timestamp); - String msgKey = $"{roomCode}_{timestamp}_{playerId}"; - schema.chatMessages.put(msgKey, msg); - - return new SendMessageResponse(True, Null, "Message sent successfully"); - } - return new SendMessageResponse(False, "Room not found", Null); - } - } - - /** - * GET /api/chat/history/{roomCode}/{playerId}?limit={number} - * - * Retrieves chat message history for the specified room. - * Only returns messages from the current room. - * - * @param roomCode The room code identifying the game - * @param playerId The player's session ID - * @param limit Optional limit on number of messages (default: 100) - * @return ChatHistoryResponse with array of messages - */ - @Get("history/{roomCode}/{playerId}") - @Produces(Json) - @HttpsRequired - ChatHistoryResponse getHistory(String roomCode, String playerId, @QueryParam("limit") Int limit = 100) { - using (schema.createTransaction()) { - // Verify the room exists - if (OnlineGame game := schema.onlineGames.get(roomCode)) { - // Verify the player is in this room - if (!game.hasPlayer(playerId)) { - return new ChatHistoryResponse(False, "You are not a player in this room", []); - } - - // Filter messages for this room and convert to response format - ChatMessageResponse[] messages = new Array(); - Int count = 0; - - // Iterate through all chat messages and filter by room code - for (ChatMessage msg : schema.chatMessages.values) { - if (msg.roomCode == roomCode) { - String colorName = msg.playerColor == White ? "White" : "Black"; - // Convert Time to epoch milliseconds (picoseconds / 1_000_000_000) - Int epochMs = (msg.timestamp.epochPicos / 1_000_000_000).toInt64(); - messages.add(new ChatMessageResponse( - msg.playerId, - colorName, - msg.message, - epochMs - )); - count++; - if (count >= limit) { - break; - } - } - } - - return new ChatHistoryResponse(True, Null, messages.freeze(inPlace=True)); - } - return new ChatHistoryResponse(False, "Room not found", []); - } - } - - /** - * GET /api/chat/recent/{roomCode}/{playerId}/{since} - * - * Retrieves chat messages sent after a specific timestamp. - * Used for polling to get only new messages. - * - * @param roomCode The room code identifying the game - * @param playerId The player's session ID - * @param since Timestamp (milliseconds) - only return messages after this time - * @return ChatHistoryResponse with array of new messages - */ - @Get("recent/{roomCode}/{playerId}/{since}") - @Produces(Json) - @HttpsRequired - ChatHistoryResponse getRecent(String roomCode, String playerId, Int since) { - using (schema.createTransaction()) { - // Verify the room exists - if (OnlineGame game := schema.onlineGames.get(roomCode)) { - // Verify the player is in this room - if (!game.hasPlayer(playerId)) { - return new ChatHistoryResponse(False, "You are not a player in this room", []); - } - - // Filter messages for this room that are newer than 'since' - ChatMessageResponse[] messages = new Array(); - - for (ChatMessage msg : schema.chatMessages.values) { - // Convert Time to epoch milliseconds for comparison - Int epochMs = (msg.timestamp.epochPicos / 1_000_000_000).toInt64(); - if (msg.roomCode == roomCode && epochMs > since) { - String colorName = msg.playerColor == White ? "White" : "Black"; - messages.add(new ChatMessageResponse( - msg.playerId, - colorName, - msg.message, - epochMs - )); - } - } - - return new ChatHistoryResponse(True, Null, messages.freeze(inPlace=True)); - } - return new ChatHistoryResponse(False, "Room not found", []); - } - } -} diff --git a/chess-game/app/src/main/x/chess/api/ChessApi.x b/chess-game/app/src/main/x/chess/api/ChessApi.x index d2f63a6..03e1894 100644 --- a/chess-game/app/src/main/x/chess/api/ChessApi.x +++ b/chess-game/app/src/main/x/chess/api/ChessApi.x @@ -1,5 +1,3 @@ -import core.OnlineChessLogic.RoomCreated; -import core.OnlineChessLogic.OnlineApiState; import core.ChessGame.MoveOutcome; import core.ChessGame.AutoResponse; import db.models.GameStatus; @@ -8,6 +6,7 @@ import db.models.MoveHistoryEntry; import services.TimeControlService; import validation.ValidMovesHelper; import core.ChessLogic; +import ai.AIUtility; /** * ChessApi Service * @@ -27,7 +26,8 @@ import core.ChessLogic; @WebService("/api") service ChessApi { // Injected dependencies for database access and time tracking - @Inject ChessSchema schema; // Database schema for game persistence + // Database access; see the Database service in chess.x + @Lazy ChessSchema schema.calc() = Database.connect(); @Inject Clock clock; // System clock for timing opponent moves TimeControlService timeControlService = new TimeControlService(); ChessAPIClient apiClient = new ChessAPIClient(); @@ -206,7 +206,8 @@ service ChessApi { Boolean opponentPending, TimeControl? timeControl = Null, MoveHistoryEntry[] moveHistory = [], - String sessionId = ""); + String sessionId = "", + String fen = ""); // ----- Helper Methods ------------------------------------------------------ @@ -291,7 +292,8 @@ service ChessApi { pending, // Is opponent thinking? adjustedTc, // Time control with current remaining time record.moveHistory, // Complete move history - sessionId); // Echo sessionId for client sanity-check + sessionId, // Echo sessionId for client sanity-check + AIUtility.boardToFen(record)); // The position, for the client's analysis } /** diff --git a/chess-game/app/src/main/x/chess/api/ChessComApi.x b/chess-game/app/src/main/x/chess/api/ChessComApi.x new file mode 100644 index 0000000..37b63f8 --- /dev/null +++ b/chess-game/app/src/main/x/chess/api/ChessComApi.x @@ -0,0 +1,137 @@ +import web.HttpClient; +import web.RequestOut; +import web.ResponseIn; +import web.responses.SimpleResponse; +/** + * ChessComApi Service + * + * Read-only proxy for the chess.com Published-Data API (https://api.chess.com/pub). + * The browser cannot call chess.com directly without depending on their CORS policy, + * so the web client goes through this service. Responses are passed through as JSON. + * + * Endpoints: + * - GET /api/chesscom/player/{username} + * - GET /api/chesscom/archives/{username} + * - GET /api/chesscom/games/{username}/{year}/{month} + * - GET /api/chesscom/puzzle + */ +@WebService("/api/chesscom") +service ChessComApi { + static String BASE_URI = "https://api.chess.com/pub"; + static String USER_AGENT = "xtc-chess-game-example"; + + // Reused across requests; HttpClient is a const and holds no per-request state + HttpClient client = new HttpClient(); + + /** + * GET /api/chesscom/player/{username} + * + * @return the player's chess.com profile + */ + @Get("player/{username}") + @Produces(Json) + @HttpsRequired + SimpleResponse player(String username) { + if (!isValidUsername(username)) { + return badRequest("Invalid username"); + } + return fetch($"{BASE_URI}/player/{username.toLowercase()}"); + } + + /** + * GET /api/chesscom/archives/{username} + * + * @return the list of monthly game archive URLs for the player + */ + @Get("archives/{username}") + @Produces(Json) + @HttpsRequired + SimpleResponse archives(String username) { + if (!isValidUsername(username)) { + return badRequest("Invalid username"); + } + return fetch($"{BASE_URI}/player/{username.toLowercase()}/games/archives"); + } + + /** + * GET /api/chesscom/games/{username}/{year}/{month} + * + * @return the player's games for the month, including PGN and final FEN + */ + @Get("games/{username}/{year}/{month}") + @Produces(Json) + @HttpsRequired + SimpleResponse games(String username, String year, String month) { + if (!isValidUsername(username) || !isDigits(year, 4) || !isDigits(month, 2)) { + return badRequest("Invalid username, year or month"); + } + return fetch($"{BASE_URI}/player/{username.toLowercase()}/games/{year}/{month}"); + } + + /** + * GET /api/chesscom/puzzle + * + * @return the chess.com daily puzzle (title, FEN, PGN) + */ + @Get("puzzle") + @Produces(Json) + @HttpsRequired + SimpleResponse puzzle() { + return fetch($"{BASE_URI}/puzzle"); + } + + // ----- helpers ------------------------------------------------------------------------------- + + /** + * Performs a GET against chess.com and relays the status and body. + */ + private SimpleResponse fetch(String uri) { + try { + RequestOut request = client.createRequest(GET, new Uri(uri)); + request.header["User-Agent"] = USER_AGENT; + request.header["Accept"] = "application/json"; + + ResponseIn response = client.send(request); + Byte[] bytes = response.body?.bytes : []; + return new SimpleResponse(response.status, Json, bytes); + } catch (Exception e) { + return new SimpleResponse(BadGateway, Json, errorBody("chess.com request failed")); + } + } + + private SimpleResponse badRequest(String message) { + return new SimpleResponse(BadRequest, Json, errorBody(message)); + } + + private Byte[] errorBody(String message) { + return ("{\"message\":\"" + message + "\"}").utf8(); + } + + /** + * chess.com usernames are 3-25 characters: letters, digits, '_' and '-'. Anything else is + * rejected so the value can never alter the upstream URL path. + */ + static Boolean isValidUsername(String name) { + if (name.size < 3 || name.size > 25) { + return False; + } + for (Char ch : name) { + if (!(ch.asciiLetter() || ch.asciiDigit() || ch == '_' || ch == '-')) { + return False; + } + } + return True; + } + + static Boolean isDigits(String text, Int length) { + if (text.size != length) { + return False; + } + for (Char ch : text) { + if (!ch.asciiDigit()) { + return False; + } + } + return True; + } +} diff --git a/chess-game/app/src/main/x/chess/api/EngineApi.x b/chess-game/app/src/main/x/chess/api/EngineApi.x new file mode 100644 index 0000000..2212703 --- /dev/null +++ b/chess-game/app/src/main/x/chess/api/EngineApi.x @@ -0,0 +1,188 @@ +import ai.StockfishApi; +import web.responses.SimpleResponse; +/** + * EngineApi Service + * + * Exposes the Stockfish Online engine to the web client. The browser never calls the engine + * directly: every request goes through here, so the upstream URL, user agent, depth limits and + * failure handling live in one place -- the same arrangement [ChessComApi] uses for chess.com. + * + * Endpoints: + * - GET /api/engine/analyse?fen={fen}&depth={depth} + * - GET /api/engine/bestmove?fen={fen}&depth={depth} + */ +@WebService("/api/engine") +service EngineApi { + StockfishApi engine = new StockfishApi(); + + /** + * GET /api/engine/analyse?fen={fen}&depth={depth} + * + * Analyses a position. `evaluation` is in pawns from White's point of view, and is null in a + * forced mate, where `mate` carries the distance to mate instead. + * + * @param fen the position in Forsyth-Edwards notation + * @param depth search depth, clamped to 1..15 + * + * @return the engine's evaluation, best move and principal variation as JSON + */ + @Get("analyse") + @Produces(Json) + @HttpsRequired + SimpleResponse analyse(@QueryParam String fen, + @QueryParam Int depth = StockfishApi.DEFAULT_DEPTH) { + if (!isPlausibleFen(fen)) { + return error(BadRequest, "Invalid FEN"); + } + + StockfishApi.EngineReply reply = engine.analyse(fen, depth); + if (!reply.success) { + return error(BadGateway, reply.error ?: "Engine unavailable"); + } + + StockfishApi.EngineMove move = StockfishApi.parseBestMove(reply.bestMove ?: ""); + + StringBuffer body = new StringBuffer(); + body.addAll("{\"success\":true"); + addField(body, "evaluation", jsonNumber(reply.evaluation)); + addField(body, "mate", jsonNumber(reply.mate)); + addField(body, "bestmove", jsonText(uciOf(reply.bestMove))); + addField(body, "from", move.fromIndex.toString()); + addField(body, "to", move.toIndex.toString()); + addField(body, "promotion", jsonText(move.promotion)); + addField(body, "continuation", jsonText(reply.continuation)); + body.addAll("}"); + return new SimpleResponse(OK, Json, body.toString().utf8()); + } + + /** + * GET /api/engine/bestmove?fen={fen}&depth={depth} + * + * The move the engine would play, already converted to the board indices the game uses. + * + * @param fen the position in Forsyth-Edwards notation + * @param depth search depth, clamped to 1..15 + * + * @return the move as JSON + */ + @Get("bestmove") + @Produces(Json) + @HttpsRequired + SimpleResponse bestmove(@QueryParam String fen, + @QueryParam Int depth = StockfishApi.DEFAULT_DEPTH) { + if (!isPlausibleFen(fen)) { + return error(BadRequest, "Invalid FEN"); + } + + StockfishApi.EngineMove move = engine.bestMove(fen, depth); + if (!move.usable) { + return error(BadGateway, "Engine returned no move"); + } + + StringBuffer body = new StringBuffer(); + body.addAll("{\"success\":true"); + addField(body, "from", move.fromIndex.toString()); + addField(body, "to", move.toIndex.toString()); + addField(body, "fromSquare", jsonText(BoardUtils.toAlgebraic(move.fromIndex))); + addField(body, "toSquare", jsonText(BoardUtils.toAlgebraic(move.toIndex))); + addField(body, "promotion", jsonText(move.promotion)); + body.addAll("}"); + return new SimpleResponse(OK, Json, body.toString().utf8()); + } + + // ----- helpers ------------------------------------------------------------------------------- + + private SimpleResponse error(HttpStatus status, String message) { + StringBuffer body = new StringBuffer(); + body.addAll("{\"success\":false"); + addField(body, "message", jsonText(message)); + body.addAll("}"); + return new SimpleResponse(status, Json, body.toString().utf8()); + } + + /** + * Appends `,"name":value` to a JSON object being built. The value is already JSON-encoded. + */ + private static void addField(StringBuffer body, String name, String value) { + body.addAll(",\""); + body.addAll(name); + body.addAll("\":"); + body.addAll(value); + } + + /** + * Renders a value the engine sent as a number back as JSON: the digits as they arrived, or + * `null`. Anything that is not a number is dropped rather than relayed. + */ + static String jsonNumber(String? value) { + if (String text ?= value) { + Boolean digits = False; + for (Char ch : text) { + if (ch.asciiDigit()) { + digits = True; + } else if (ch != '-' && ch != '+' && ch != '.') { + return "null"; + } + } + if (digits) { + return text; + } + } + return "null"; + } + + /** + * Renders a string as a JSON string literal, or `null`. The engine only ever sends plain + * ASCII moves and notation, so anything outside that set is dropped. + */ + static String jsonText(String? value) { + if (String text ?= value) { + for (Char ch : text) { + if (!ch.ascii || ch == '"' || ch == '\\' || ch.codepoint < 0x20) { + return "null"; + } + } + return $"\"{text}\""; + } + return "null"; + } + + /** + * Pulls the plain UCI move out of a "bestmove e7e5 ponder g1f3" line. + */ + static String? uciOf(String? bestMoveLine) { + if (String line ?= bestMoveLine) { + for (String token : line.split(' ')) { + String trimmed = token.trim(); + if (trimmed.size >= 4 && trimmed != "bestmove" && trimmed != "ponder") { + return trimmed; + } + } + } + return Null; + } + + /** + * Cheap shape check so a malformed value is rejected here rather than upstream: a FEN is + * ASCII, has a board field of eight '/'-separated ranks, and names the side to move. + */ + static Boolean isPlausibleFen(String fen) { + if (fen.size < 10 || fen.size > 120) { + return False; + } + for (Char ch : fen) { + if (!ch.ascii || ch.codepoint < 0x20) { + return False; + } + } + + String[] fields = fen.trim().split(' '); + if (fields.size < 2) { + return False; + } + if (fields[0].split('/').size != 8) { + return False; + } + return fields[1] == "w" || fields[1] == "b"; + } +} diff --git a/chess-game/app/src/main/x/chess/api/OnlineChessApi.x b/chess-game/app/src/main/x/chess/api/OnlineChessApi.x index 978336e..186aa9f 100644 --- a/chess-game/app/src/main/x/chess/api/OnlineChessApi.x +++ b/chess-game/app/src/main/x/chess/api/OnlineChessApi.x @@ -24,7 +24,8 @@ import core.ChessLogic; @WebService("/api/online") service OnlineChessApi { // Injected dependencies - @Inject ChessSchema schema; + // Database access; see the Database service in chess.x + @Lazy ChessSchema schema.calc() = Database.connect(); @Inject Random random; TimeControlService timeControlService = new TimeControlService(); diff --git a/chess-game/app/src/main/x/chess/config/CastlingManager.x b/chess-game/app/src/main/x/chess/config/CastlingManager.x index 8feb357..ebdb8d2 100644 --- a/chess-game/app/src/main/x/chess/config/CastlingManager.x +++ b/chess-game/app/src/main/x/chess/config/CastlingManager.x @@ -67,47 +67,4 @@ service CastlingManager { return new CastlingRights(whiteKingside, whiteQueenside, blackKingside, blackQueenside); } - - /** - * Check if castling is available for a specific side. - */ - static Boolean canCastle(CastlingRights rights, Color color, Boolean kingside) { - return color == White - ? (kingside ? rights.whiteKingside : rights.whiteQueenside) - : (kingside ? rights.blackKingside : rights.blackQueenside); - } - - /** - * Create default castling rights (all castling available). - */ - static CastlingRights defaultRights() { - return new CastlingRights(True, True, True, True); - } - - /** - * Create castling rights with no castling available. - */ - static CastlingRights noRights() { - return new CastlingRights(False, False, False, False); - } - - /** - * Get a string representation of castling rights (FEN notation). - */ - static String toFEN(CastlingRights rights) { - String fen = ""; - if (rights.whiteKingside) { - fen += "K"; - } - if (rights.whiteQueenside) { - fen += "Q"; - } - if (rights.blackKingside) { - fen += "k"; - } - if (rights.blackQueenside) { - fen += "q"; - } - return fen.empty ? "-" : fen; - } } diff --git a/chess-game/app/src/main/x/chess/config/MoveContext.x b/chess-game/app/src/main/x/chess/config/MoveContext.x deleted file mode 100644 index a888464..0000000 --- a/chess-game/app/src/main/x/chess/config/MoveContext.x +++ /dev/null @@ -1,27 +0,0 @@ -import db.models.CastlingRights; -import db.models.Color; - -/** - * Move Context - * Encapsulates all contextual information needed for move validation. - * Reduces parameter passing and makes code more maintainable. - */ -const MoveContext( - CastlingRights? castlingRights = Null, - String? enPassantTarget = Null, - Color playerColor = Color.White, - Char piece = '.' -) { - /** - * Check if castling is allowed for a specific side. - */ - Boolean canCastle(Color color, Boolean kingside) { - CastlingRights? rights = castlingRights; - if (rights == Null) { - return False; - } - return color == White - ? (kingside ? rights.whiteKingside : rights.whiteQueenside) - : (kingside ? rights.blackKingside : rights.blackQueenside); - } -} diff --git a/chess-game/app/src/main/x/chess/config/MoveStrategy.x b/chess-game/app/src/main/x/chess/config/MoveStrategy.x deleted file mode 100644 index a9aaf8e..0000000 --- a/chess-game/app/src/main/x/chess/config/MoveStrategy.x +++ /dev/null @@ -1,20 +0,0 @@ -import db.models.CastlingRights; -import db.models.Color; - -/** - * Move Strategy Interface - * Defines a common interface for different piece movement strategies. - * This enables the Strategy pattern for piece validation, reducing code duplication. - */ -interface MoveStrategy { - /** - * Validate if a move is legal for this piece type. - * - * @param from Source square index (0-63) - * @param to Destination square index (0-63) - * @param board Current board state - * @param context Additional context (castling rights, en passant, etc.) - * @return True if the move is valid for this piece type - */ - Boolean validateMove(Int from, Int to, Char[] board, MoveContext context); -} diff --git a/chess-game/app/src/main/x/chess/core/ChessGame.x b/chess-game/app/src/main/x/chess/core/ChessGame.x index 156baf2..61b4038 100644 --- a/chess-game/app/src/main/x/chess/core/ChessGame.x +++ b/chess-game/app/src/main/x/chess/core/ChessGame.x @@ -283,11 +283,10 @@ class ChessGame { // ----- Game Status Detection ------------------------------------------------- /** - * Check if the game has ended (legacy method for backward compatibility). + * Determines game status from board material alone: checkmate when either king is missing, + * stalemate when only the two kings remain, ongoing otherwise. */ static GameStatus checkGameStatus(String board, Color turn) { - // Use simplified legacy rules for backward compatibility - // Count pieces Int whitePieces = 0; Int blackPieces = 0; Boolean whiteKing = False; diff --git a/chess-game/app/src/main/x/chess/core/ChessLogic.x b/chess-game/app/src/main/x/chess/core/ChessLogic.x index c5c3540..6d783fb 100644 --- a/chess-game/app/src/main/x/chess/core/ChessLogic.x +++ b/chess-game/app/src/main/x/chess/core/ChessLogic.x @@ -25,22 +25,6 @@ service ChessLogic { return ChessGame.applyHumanMove(record, fromSquare, toSquare, promotion); } - /** - * Apply a move with pre-computed square indices. Delegates to ChessGame.applyMove. - */ - static GameRecord applyMove(GameRecord record, Char[] board, Int from, Int to, String? promotion) { - return ChessGame.applyMove(record, board, from, to, promotion); - } - - /** - * Build SAN-style notation for a move. Delegates to ChessGame.createMoveNotation. - */ - static String createMoveNotation(Char piece, Int from, Int to, Boolean isCapture, - Char? promotedTo, Boolean givesCheck, Boolean isCheckmate, - String? castleType) { - return ChessGame.createMoveNotation(piece, from, to, isCapture, promotedTo, givesCheck, isCheckmate, castleType); - } - /** * Apply an AI opponent move with pre-computed from/to squares. */ diff --git a/chess-game/app/src/main/x/chess/services/TimeControlService.x b/chess-game/app/src/main/x/chess/services/TimeControlService.x index 13801dd..7b9e984 100644 --- a/chess-game/app/src/main/x/chess/services/TimeControlService.x +++ b/chess-game/app/src/main/x/chess/services/TimeControlService.x @@ -86,27 +86,4 @@ service TimeControlService { ? (tc.whiteTimeMs - elapsed).maxOf(0) : (tc.blackTimeMs - elapsed).maxOf(0); } - - // ------------------------------------------------------------------------- - // Common time control presets (FIDE standards, all values in milliseconds) - // ------------------------------------------------------------------------- - - // Bullet - TimeControl bullet() = create(60_000, 0); // 1 min - TimeControl bullet1plus1() = create(60_000, 1_000); // 1+1 - TimeControl bullet2plus1() = create(120_000, 1_000); // 2+1 - - // Blitz - TimeControl blitz3() = create(180_000, 0); // 3 min - TimeControl blitz3plus2() = create(180_000, 2_000); // 3+2 - TimeControl blitz5() = create(300_000, 0); // 5 min - TimeControl blitz5plus3() = create(300_000, 3_000); // 5+3 - - // Rapid - TimeControl rapid10() = create(600_000, 0); // 10 min - TimeControl rapid15plus10() = create(900_000, 10_000); // 15+10 - TimeControl rapid30() = create(1_800_000, 0); // 30 min - - // Classical - TimeControl classical() = create(5_400_000, 30_000); // 90+30 (FIDE standard) } \ No newline at end of file diff --git a/chess-game/app/src/main/x/chess/utils/BoardOperations.x b/chess-game/app/src/main/x/chess/utils/BoardOperations.x index f9b43fc..5e427da 100644 --- a/chess-game/app/src/main/x/chess/utils/BoardOperations.x +++ b/chess-game/app/src/main/x/chess/utils/BoardOperations.x @@ -1,5 +1,3 @@ -import db.models.Color; - /** * Board Operations * Consolidates common board manipulation patterns to reduce code duplication. @@ -21,38 +19,6 @@ service BoardOperations { return -1; } - /** - * Find all pieces of a specific type and color. - * @param board The board to search - * @param pieceType The piece type ('p', 'n', 'b', 'r', 'q', 'k') - * @param color The color to match - * @return Array of square indices - */ - static Int[] findPieces(Char[] board, Char pieceType, Color color) { - Char targetChar = color == Color.White ? pieceType.uppercase : pieceType.lowercase; - Int[] positions = new Int[]; - for (Int i = 0; i < 64; i++) { - if (board[i] == targetChar) { - positions = positions.add(i); - } - } - return positions; - } - - /** - * Count pieces of a specific color on the board. - */ - static Int countPieces(Char[] board, Color color) { - Int count = 0; - for (Int i = 0; i < 64; i++) { - Char piece = board[i]; - if (piece != '.' && BoardUtils.colorOf(piece) == color) { - count++; - } - } - return count; - } - /** * Apply a move to the board (mutates the board). * @param board The board to modify @@ -77,118 +43,10 @@ service BoardOperations { return newBoard; } - /** - * Check if a square is empty. - */ - static Boolean isEmpty(Char[] board, Int square) { - return BoardUtils.isValidSquare(square) && board[square] == '.'; - } - - /** - * Check if a square is occupied by a piece of specific color. - */ - static Boolean isOccupiedBy(Char[] board, Int square, Color color) { - if (!BoardUtils.isValidSquare(square)) { - return False; - } - Char piece = board[square]; - return piece != '.' && BoardUtils.colorOf(piece) == color; - } - - /** - * Get all occupied squares for a color. - */ - static Int[] getOccupiedSquares(Char[] board, Color color) { - Int[] squares = new Int[]; - for (Int i = 0; i < 64; i++) { - if (isOccupiedBy(board, i, color)) { - squares = squares.add(i); - } - } - return squares; - } - - /** - * Calculate material balance (positive = White ahead, negative = Black ahead). - * Uses standard piece values: P=100, N=320, B=330, R=500, Q=900. - */ - static Int calculateMaterialBalance(Char[] board) { - Int whiteValue = 0; - Int blackValue = 0; - - for (Int i = 0; i < 64; i++) { - Char piece = board[i]; - if (piece == '.') { - continue; - } - Int value = switch (piece.lowercase) { - case 'p': 100; - case 'n': 320; - case 'b': 330; - case 'r': 500; - case 'q': 900; - default: 0; - }; - if ('A' <= piece <= 'Z') { - whiteValue += value; - } else { - blackValue += value; - } - } - - return whiteValue - blackValue; - } - /** * Check if a move is a capture. */ static Boolean isCapture(Char[] board, Int from, Int to) { return board[to] != '.' && board[from] != '.'; } - - /** - * Check if two squares are adjacent (touching, including diagonals). - */ - static Boolean areAdjacent(Int square1, Int square2) { - return BoardUtils.getDistance(square1, square2) == 1; - } - - /** - * Get all empty squares on the board. - */ - static Int[] getEmptySquares(Char[] board) { - Int[] squares = new Int[]; - for (Int i = 0; i < 64; i++) { - if (board[i] == '.') { - squares = squares.add(i); - } - } - return squares; - } - - /** - * Convert board array to string representation. - */ - static String boardToString(Char[] board) { - return new String(board); - } - - /** - * Validate board integrity (has exactly one king of each color). - */ - static Boolean isValidBoard(Char[] board) { - Int whiteKings = 0; - Int blackKings = 0; - - for (Int i = 0; i < 64; i++) { - Char piece = board[i]; - if (piece == 'K') { - whiteKings++; - } else if (piece == 'k') { - blackKings++; - } - } - - return whiteKings == 1 && blackKings == 1; - } } diff --git a/chess-game/app/src/main/x/chess/utils/ChatAPIResponseTypes.x b/chess-game/app/src/main/x/chess/utils/ChatAPIResponseTypes.x deleted file mode 100644 index a7c3ed2..0000000 --- a/chess-game/app/src/main/x/chess/utils/ChatAPIResponseTypes.x +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Chat API Response Types Package - * Contains all data structures for chat API request/response handling - */ -package ChatAPIResponseTypes { - // ===== Chat API Response Types ===== - - /** - * ChatMessageResponse - API response format for a single chat message - */ - const ChatMessageResponse(String playerId, - String playerColor, - String message = "", - Int timestamp); - - /** - * ChatHistoryResponse - API response containing chat messages - */ - const ChatHistoryResponse(Boolean success, - String? error, - ChatMessageResponse[] messages = []); - - /** - * SendMessageResponse - API response after sending a message - */ - const SendMessageResponse(Boolean success, - String? error, - String? message = Null); - - /** - * SendMessageRequest - API request body for sending a message - */ - const SendMessageRequest(String message = ""); -} diff --git a/chess-game/app/src/main/x/chess/utils/DirectionUtils.x b/chess-game/app/src/main/x/chess/utils/DirectionUtils.x index 755b658..a3290de 100644 --- a/chess-game/app/src/main/x/chess/utils/DirectionUtils.x +++ b/chess-game/app/src/main/x/chess/utils/DirectionUtils.x @@ -94,40 +94,4 @@ service DirectionUtils { static Boolean isStraightLine(Int from, Int to) { return (isSameFile(from, to) || isSameRank(from, to)) && from != to; } - - /** - * Get all squares along a ray in a specific direction. - * Useful for sliding piece attack detection. - */ - static Int[] getRaySquares(Int from, Int direction, Int maxDistance = 8) { - Int[] squares = new Int[]; - Int current = from + direction; - Int distance = 0; - - Loop: - while (BoardUtils.isValidSquare(current) && distance < maxDistance) { - // Check for wrapping (file overflow) - Int fromFile = BoardUtils.getFile(from); - Int currentFile = BoardUtils.getFile(current); - - switch (direction) { - case EAST, NORTHEAST, SOUTHEAST: - if (currentFile < fromFile) { - break Loop; - } - break; - - case WEST, NORTHWEST, SOUTHWEST: - if (currentFile > fromFile) { - break Loop; - } - break; - } - - squares = squares.add(current); - current += direction; - distance++; - } - return squares; - } } diff --git a/chess-game/app/src/main/x/chess/validation/MoveValidator.x b/chess-game/app/src/main/x/chess/validation/MoveValidator.x index a2bd749..b6774fb 100644 --- a/chess-game/app/src/main/x/chess/validation/MoveValidator.x +++ b/chess-game/app/src/main/x/chess/validation/MoveValidator.x @@ -85,75 +85,4 @@ service MoveValidator { return ValidationResult.success(); } - - /** - * Quick validation for AI move generation (skips some checks for performance). - */ - static Boolean isQuickValid( - Char[] board, - Int from, - Int to, - Color turn, - CastlingRights? castlingRights = Null, - String? enPassantTarget = Null - ) { - Char piece = board[from]; - if (piece == '.' || BoardUtils.colorOf(piece) != turn) { - return False; - } - - Char target = board[to]; - if (target != '.' && BoardUtils.colorOf(target) == turn) { - return False; - } - - return PieceValidator.isLegal(piece, from, to, board, castlingRights, enPassantTarget); - } - - /** - * Check if a move would be a capture. - */ - static Boolean isCapture(Char[] board, Int from, Int to) { - return BoardOperations.isCapture(board, from, to); - } - - /** - * Check if a move would be a pawn promotion. - */ - static Boolean isPromotion(Char[] board, Int from, Int to) { - Char piece = board[from]; - if (!PieceValidator.isPawn(piece)) { - return False; - } - Int toRank = BoardUtils.getRank(to); - return (piece == 'P' && toRank == 0) || (piece == 'p' && toRank == 7); - } - - /** - * Check if a move would be castling. - */ - static Boolean isCastling(Char[] board, Int from, Int to) { - Char piece = board[from]; - if (!PieceValidator.isKing(piece)) { - return False; - } - Int fileDiff = (BoardUtils.getFile(to) - BoardUtils.getFile(from)).abs(); - return fileDiff == 2; - } - - /** - * Check if a move would be en passant. - */ - static Boolean isEnPassant(Char[] board, Int from, Int to, String? enPassantTarget) { - if (enPassantTarget == Null) { - return False; - } - Char piece = board[from]; - if (!PieceValidator.isPawn(piece)) { - return False; - } - String toSquare = BoardUtils.toAlgebraic(to); - Char target = board[to]; - return toSquare == enPassantTarget && target == '.'; - } } diff --git a/chess-game/app/src/main/x/chess/validation/PieceValidator.x b/chess-game/app/src/main/x/chess/validation/PieceValidator.x index 0a56b76..aa91969 100644 --- a/chess-game/app/src/main/x/chess/validation/PieceValidator.x +++ b/chess-game/app/src/main/x/chess/validation/PieceValidator.x @@ -11,10 +11,6 @@ service PieceValidator { // ----- Piece Type Detection ------------------------------------------------- static Boolean isPawn(Char piece) = piece == 'p' || piece == 'P'; - static Boolean isKnight(Char piece) = piece == 'n' || piece == 'N'; - static Boolean isBishop(Char piece) = piece == 'b' || piece == 'B'; - static Boolean isRook(Char piece) = piece == 'r' || piece == 'R'; - static Boolean isQueen(Char piece) = piece == 'q' || piece == 'Q'; static Boolean isKing(Char piece) = piece == 'k' || piece == 'K'; // ----- Path Checking ------------------------------------------------- diff --git a/chess-game/app/src/test/x/ChessAIEvaluatorTest.x b/chess-game/app/src/test/x/ChessAIEvaluatorTest.x deleted file mode 100644 index e6d5159..0000000 --- a/chess-game/app/src/test/x/ChessAIEvaluatorTest.x +++ /dev/null @@ -1,84 +0,0 @@ -module ChessAIEvaluatorTest { - package chess import chess.examples.org; - package db import chessDB.examples.org; - package xunit import xunit.xtclang.org; - - import chess.core.ChessLogic; - import chess.ai.AIPositionEvaluator; - import chess.utils.BoardUtils; - - import db.models.Color; - import db.models.CastlingRights; - import db.models.GameRecord; - import db.models.GameStatus; - - import xunit.annotations.Disabled; - - /** - * Tests for position evaluation: material values, endgame detection, passed pawns. - */ - class AIPositionEvaluatorTests { - @Test - void shouldEvaluateMaterialAndEndgameHelpers() { - val board = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - assert AIPositionEvaluator.getPieceValue('p') == 100; - assert AIPositionEvaluator.getPieceValue('q') == 900; - assert AIPositionEvaluator.getPieceValue('k') == 20000; - assert AIPositionEvaluator.chebyshevDistance(0, 63) == 7; - assert AIPositionEvaluator.evaluateBoard(board, ChessLogic.defaultGame()) == 0; - - val endgame = new Char[64](i -> '.'); - endgame[0] = 'k'; - endgame[63] = 'K'; - assert AIPositionEvaluator.isEndgame(endgame); - assert AIPositionEvaluator.isPassedPawn(endgame, 48, 'P'); - } - - @Test - void shouldReturnCorrectPieceValues() { - assert AIPositionEvaluator.getPieceValue('p') == 100; - assert AIPositionEvaluator.getPieceValue('n') == 320; - assert AIPositionEvaluator.getPieceValue('b') == 330; - assert AIPositionEvaluator.getPieceValue('r') == 500; - assert AIPositionEvaluator.getPieceValue('q') == 900; - assert AIPositionEvaluator.getPieceValue('k') == 20000; - } - - @Test - void shouldCalculateChebyshevDistanceCorrectly() { - assert AIPositionEvaluator.chebyshevDistance(0, 0) == 0; - assert AIPositionEvaluator.chebyshevDistance(0, 1) == 1; - assert AIPositionEvaluator.chebyshevDistance(0, 8) == 1; - assert AIPositionEvaluator.chebyshevDistance(0, 9) == 1; - assert AIPositionEvaluator.chebyshevDistance(0, 63) == 7; - } - - @Test - void shouldDetectEndgameWithFewPieces() { - // Endgame: only kings - val kingsOnly = new Char[64](i -> '.'); - kingsOnly[0] = 'k'; - kingsOnly[63] = 'K'; - assert AIPositionEvaluator.isEndgame(kingsOnly); - - // Not endgame: starting position - val full = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - assert !AIPositionEvaluator.isEndgame(full); - } - - @Disabled("AIPositionEvaluator.evaluateBoard returns -975 for a position where White has an extra queen — sign convention / perspective bug in evaluator") - @Test - void shouldEvaluatePositionWithMaterialAdvantage() { - // Board where white has an extra queen - val board = new Char[64](i -> '.'); - board[0] = 'k'; - board[63] = 'K'; - board[35] = 'Q'; // White queen - val record = new GameRecord( - new String(board), Color.White, GameStatus.Ongoing, Null, - 0, 0, new CastlingRights(False, False, False, False), Null, [], Null, 0); - val eval = AIPositionEvaluator.evaluateBoard(board, record); - assert eval > 0; // White should have positive evaluation - } - } -} diff --git a/chess-game/app/src/test/x/ChessAIMoveSelectionTest.x b/chess-game/app/src/test/x/ChessAIMoveSelectionTest.x index ed50b3b..7d7edb7 100644 --- a/chess-game/app/src/test/x/ChessAIMoveSelectionTest.x +++ b/chess-game/app/src/test/x/ChessAIMoveSelectionTest.x @@ -4,27 +4,17 @@ module ChessAIMoveSelectionTest { import chess.core.ChessLogic; import chess.ai.ChessAPIClient; - import chess.ai.AIOpeningBook; - import chess.ai.AIPositionEvaluator; - import chess.ai.AIMoveSelector; - import chess.ai.AISearchEngine; - import chess.ai.ChessAI; import chess.utils.BoardUtils; import db.models.Color; - import db.models.GameRecord; /** - * Tests for move selection, opening book, and search engine. + * Tests for the computer's move selection. */ class AISelectionTests { @Test - void shouldPreferOpeningAndLegalCandidates() { + void shouldReturnALegalMoveForTheSideToMove() { val afterE4 = ChessLogic.applyHumanMove(ChessLogic.defaultGame(), "e2", "e4", Null).record; - (Int openFrom, Int openTo) = AIOpeningBook.getOpeningMove(afterE4); - assert openFrom >= 0; - assert openTo >= 0; - assert BoardUtils.colorOf(afterE4.board[openFrom]) == Color.Black; ChessAPIClient client = new ChessAPIClient(); (Int from, Int to, String? promotion) = client.findBestMove(afterE4); @@ -32,60 +22,6 @@ module ChessAIMoveSelectionTest { assert to >= 0; assert BoardUtils.colorOf(afterE4.board[from]) == Color.Black; assert promotion == Null || promotion == "q"; - - (Int[] orderedFroms, Int[] orderedTos, Int[] scores) = AIMoveSelector.collectOrderedLegalMoves(afterE4, BoardUtils.cloneBoard(afterE4.board)); - assert orderedFroms.size == orderedTos.size; - assert orderedFroms.size == scores.size; - assert orderedFroms.size > 0; - - val eval = AISearchEngine.minimax(BoardUtils.cloneBoard(afterE4.board), afterE4, 0, -1000000, 1000000, True); - assert eval == AIPositionEvaluator.evaluateBoard(BoardUtils.cloneBoard(afterE4.board), afterE4); - } - - @Test - void shouldExposeLegacyFacadeHelpers() { - val game = ChessLogic.defaultGame(); - assert ChessAI.isOpeningPhase(game); - assert ChessAI.totalMaterial(BoardUtils.cloneBoard(game.board)) == 8000; - assert ChessAI.randomInt(10, 5, 2) >= 0; - - (Int from, Int to, Int score) = ChessAI.findBestMove(game); - assert from >= -1; - assert to >= -1; - assert score <= ChessAI.MAX_SCORE; - } - - @Test - void shouldCollectNonZeroLegalMovesFromStartingPosition() { - val afterE4 = ChessLogic.applyHumanMove(ChessLogic.defaultGame(), "e2", "e4", Null).record; - (Int[] froms, Int[] tos, Int[] scores) = AIMoveSelector.collectOrderedLegalMoves(afterE4, BoardUtils.cloneBoard(afterE4.board)); - // Black should have 20 legal moves in response to 1. e4 - assert froms.size == 20; - // Scores should be ordered (move ordering) - for (Int i : 0 ..< scores.size - 1) { - assert scores[i] >= scores[i + 1]; - } - } - - @Test - void shouldReturnOpeningMoveForBlack() { - val afterE4 = ChessLogic.applyHumanMove(ChessLogic.defaultGame(), "e2", "e4", Null).record; - (Int from, Int to) = AIOpeningBook.getOpeningMove(afterE4); - // Opening book should return a valid Black piece - assert from >= 0 && from < 64; - assert to >= 0 && to < 64; - Char piece = afterE4.board[from]; - assert piece >= 'a' && piece <= 'z'; // Black piece (lowercase) - } - - @Test - void shouldEvaluateToZeroAtDepthZero() { - val game = ChessLogic.defaultGame(); - val board = BoardUtils.cloneBoard(game.board); - // At depth 0, minimax should return static evaluation - val eval = AISearchEngine.minimax(board, game, 0, -1000000, 1000000, True); - val staticEval = AIPositionEvaluator.evaluateBoard(board, game); - assert eval == staticEval; } } } diff --git a/chess-game/app/src/test/x/ChessAIUtilityTest.x b/chess-game/app/src/test/x/ChessAIUtilityTest.x index cae71fe..680ad6a 100644 --- a/chess-game/app/src/test/x/ChessAIUtilityTest.x +++ b/chess-game/app/src/test/x/ChessAIUtilityTest.x @@ -7,7 +7,6 @@ module ChessAIUtilityTest { import chess.utils.BoardUtils; import db.models.Color; - import db.models.GameRecord; /** * Tests for AI utility functions: hashing, FEN generation, random move finding. diff --git a/chess-game/app/src/test/x/ChessApiHelperTest.x b/chess-game/app/src/test/x/ChessApiHelperTest.x index 71bc3a4..6cb4362 100644 --- a/chess-game/app/src/test/x/ChessApiHelperTest.x +++ b/chess-game/app/src/test/x/ChessApiHelperTest.x @@ -5,9 +5,6 @@ module ChessApiHelperTest { import chess.core.ChessLogic; import chess.api.ChessApi; - import chess.utils.ChatAPIResponseTypes.*; - - import db.models.GameRecord; import xunit.annotations.Disabled; @@ -33,26 +30,6 @@ module ChessApiHelperTest { assert state.board[0] == "rnbqkbnr"; } - @Test - void shouldBuildOnlineAndChatResponseTypes() { - val request = new SendMessageRequest(" hello chess "); - assert request.message == " hello chess "; - - val message = new ChatMessageResponse("p1", "White", "hi", 123); - assert message.playerId == "p1"; - assert message.playerColor == "White"; - assert message.message == "hi"; - assert message.timestamp == 123; - - val history = new ChatHistoryResponse(True, Null, [message]); - assert history.success; - assert history.messages.size == 1; - - val sent = new SendMessageResponse(True, Null, "Message sent successfully"); - assert sent.success; - assert sent.message == "Message sent successfully"; - } - @Test void shouldBuildApiStateWithCorrectBoardLayout() { val api = new ChessApi(); @@ -75,17 +52,5 @@ module ChessApiHelperTest { // After Black responds (simulate via autoMove or manual), describe should include last move assert api.describeState(afterE4, False).indexOf("e2e4"); } - - @Test - void shouldBuildFailedChatResponses() { - val failed = new ChatHistoryResponse(False, "Room not found", []); - assert !failed.success; - assert failed.error == "Room not found"; - assert failed.messages.empty; - - val failSend = new SendMessageResponse(False, "Not a player", Null); - assert !failSend.success; - assert failSend.error == "Not a player"; - } } } diff --git a/chess-game/app/src/test/x/ChessApiTest.x b/chess-game/app/src/test/x/ChessApiTest.x new file mode 100644 index 0000000..029b5ef --- /dev/null +++ b/chess-game/app/src/test/x/ChessApiTest.x @@ -0,0 +1,166 @@ +module ChessApiTest { + package chess import chess.examples.org; + package db import chessDB.examples.org; + + import chess.api.ChessApi; + import chess.validation.ValidMovesHelper.ValidMovesResponse; + + /** + * Endpoint tests for the single-player service (`/api`): state, move, valid moves and reset, + * each called the way a request would call it, against a real database. + * + * The computer's reply needs its thinking delay to pass and the engine to answer, so it is + * covered by the opt-in network suite, `ChessLiveApiTest`. + */ + class ChessApiTests { + static String START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + + /** + * A session id no earlier run has used, so a test never inherits another's game. + */ + static String freshSession(String label) { + @Inject Random random; + return $"{label}-{random.int(1_000_000_000)}"; + } + + @Test + void shouldStartANewSessionAtTheInitialPosition() { + ChessApi api = new ChessApi(); + String id = freshSession("start"); + val state = api.state(id); + + assert state.sessionId == id; + assert state.turn == "White"; + assert state.status == "Ongoing"; + assert !state.opponentPending; + assert state.moveHistory.empty; + assert state.board[0] == "rnbqkbnr"; + assert state.board[7] == "RNBQKBNR"; + assert state.fen == START_FEN; + } + + @Test + void shouldReturnTheSameGameOnEveryRead() { + ChessApi api = new ChessApi(); + String id = freshSession("reread"); + api.move(id, "e2", "e4"); + + val first = api.state(id); + val second = api.state(id); + assert first.fen == second.fen; + assert first.moveHistory.size == 1; + } + + @Test + void shouldApplyALegalMoveAndHandTheTurnToTheComputer() { + ChessApi api = new ChessApi(); + String id = freshSession("legal"); + val state = api.move(id, "e2", "e4"); + + assert state.turn == "Black"; + assert state.lastMove == "e2e4"; + assert state.opponentPending; + assert state.moveHistory.size == 1; + assert state.moveHistory[0].fromSquare == "e2"; + assert state.moveHistory[0].toSquare == "e4"; + assert state.board[4] == "....P..."; + assert state.board[6] == "PPPP.PPP"; + assert state.fen.startsWith("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b"); + } + + @Test + void shouldRejectAnIllegalMoveAndLeaveTheBoardAlone() { + ChessApi api = new ChessApi(); + String id = freshSession("illegal"); + val state = api.move(id, "e2", "e5"); + + assert state.turn == "White"; + assert state.moveHistory.empty; + assert state.fen == START_FEN; + } + + @Test + void shouldRejectMovingTheComputersPieces() { + ChessApi api = new ChessApi(); + String id = freshSession("theirs"); + val state = api.move(id, "e7", "e5"); + + assert state.turn == "White"; + assert state.moveHistory.empty; + assert state.fen == START_FEN; + } + + @Test + void shouldListTheSquaresAPieceCanReach() { + ChessApi api = new ChessApi(); + String id = freshSession("valid"); + ValidMovesResponse pawn = api.getValidMoves(id, "e2"); + ValidMovesResponse night = api.getValidMoves(id, "g1"); + + assert pawn.success; + assert pawn.validMoves.size == 2; + assert pawn.validMoves.contains("e3") && pawn.validMoves.contains("e4"); + + assert night.success; + assert night.validMoves.size == 2; + assert night.validMoves.contains("f3") && night.validMoves.contains("h3"); + } + + @Test + void shouldListNothingForAnEmptySquareOrABlackPiece() { + ChessApi api = new ChessApi(); + String id = freshSession("nothing"); + + assert api.getValidMoves(id, "e4").validMoves.empty; + assert api.getValidMoves(id, "e7").validMoves.empty; + } + + @Test + void shouldOfferNoMovesWhileTheComputerIsToMove() { + ChessApi api = new ChessApi(); + String id = freshSession("blackturn"); + api.move(id, "e2", "e4"); + + ValidMovesResponse reply = api.getValidMoves(id, "d2"); + assert !reply.success; + assert reply.validMoves.empty; + } + + @Test + void shouldResetToTheInitialPosition() { + ChessApi api = new ChessApi(); + String id = freshSession("reset"); + api.move(id, "e2", "e4"); + + val state = api.reset(id); + assert state.fen == START_FEN; + assert state.moveHistory.empty; + assert !state.opponentPending; + assert state.timeControl == Null; + } + + @Test + void shouldStartAClockWhenResetWithATimeControl() { + ChessApi api = new ChessApi(); + String id = freshSession("clock"); + val state = api.reset(id, new ChessApi.ResetRequest(300_000, 5_000)); + + assert val clock ?= state.timeControl; + assert clock.whiteTimeMs == 300_000; + assert clock.blackTimeMs == 300_000; + assert clock.incrementMs == 5_000; + } + + @Test + void shouldKeepSessionsIndependent() { + ChessApi api = new ChessApi(); + String one = freshSession("one"); + String two = freshSession("two"); + api.move(one, "e2", "e4"); + + assert api.state(one).moveHistory.size == 1; + assert api.state(two).moveHistory.empty; + assert api.state(two).fen == START_FEN; + } + } +} diff --git a/chess-game/app/src/test/x/ChessBoardOpsTest.x b/chess-game/app/src/test/x/ChessBoardOpsTest.x index 0096ca9..61d394c 100644 --- a/chess-game/app/src/test/x/ChessBoardOpsTest.x +++ b/chess-game/app/src/test/x/ChessBoardOpsTest.x @@ -6,23 +6,18 @@ module ChessBoardOpsTest { import chess.utils.BoardUtils; import chess.utils.BoardOperations; import chess.config.CastlingManager; - import chess.config.MoveContext; - import db.models.Color; import db.models.CastlingRights; /** - * Tests for board-level operations: find, count, move, material. + * Tests for board-level operations: find, move, capture. */ class BoardOperationsTests { @Test - void shouldFindAndCountPieces() { + void shouldFindPieces() { val array = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); assert BoardOperations.findPiece(array, 'K') == 60; - assert BoardOperations.countPieces(array, Color.White) == 16; - assert BoardOperations.countPieces(array, Color.Black) == 16; - assert BoardOperations.getOccupiedSquares(array, Color.White).size == 16; - assert BoardOperations.getEmptySquares(array).size == 32; + assert BoardOperations.findPiece(array, 'k') == 4; } @Test @@ -39,12 +34,9 @@ module ChessBoardOpsTest { } @Test - void shouldMeasureMaterialAndBoardIntegrity() { + void shouldNotTreatAMoveToAnEmptySquareAsACapture() { val board = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - assert BoardOperations.calculateMaterialBalance(board) == 0; - assert BoardOperations.isValidBoard(board); assert BoardOperations.isCapture(board, 52, 36) == False; - assert BoardOperations.areAdjacent(0, 1); } @Test @@ -57,55 +49,15 @@ module ChessBoardOpsTest { assert BoardOperations.isCapture(board, 35, 26); assert !BoardOperations.isCapture(board, 35, 27); } - - @Test - void shouldFindMultiplePieces() { - val array = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - val pawns = BoardOperations.findPieces(array, 'P', Color.White); - assert pawns.size == 8; - val knights = BoardOperations.findPieces(array, 'N', Color.White); - assert knights.size == 2; - } - - @Test - void shouldDetectEmptyAndOccupiedSquares() { - val board = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - assert BoardOperations.isEmpty(board, 32); // a4, empty - assert !BoardOperations.isEmpty(board, 0); // a8, has rook - assert BoardOperations.isOccupiedBy(board, 0, Color.Black); - assert BoardOperations.isOccupiedBy(board, 56, Color.White); - assert !BoardOperations.isOccupiedBy(board, 32, Color.White); - } - - @Test - void shouldReportMaterialBalanceWithMissingPieces() { - val board = new Char[64](i -> '.'); - board[0] = 'k'; - board[63] = 'K'; - board[60] = 'Q'; // White queen worth 9 - val balance = BoardOperations.calculateMaterialBalance(board); - assert balance > 0; // White has more material - } - - @Test - void shouldDetectAdjacentSquares() { - assert BoardOperations.areAdjacent(0, 1); // Same rank - assert BoardOperations.areAdjacent(0, 8); // Same file - assert BoardOperations.areAdjacent(0, 9); // Diagonal - assert !BoardOperations.areAdjacent(0, 16); // Two ranks apart - assert !BoardOperations.areAdjacent(0, 2); // Two files apart - } } /** - * Tests for castling rights management and move context. + * Tests for castling rights management. */ class CastlingAndContextTests { @Test void shouldUpdateCastlingRightsAndFormatFEN() { - val rights = CastlingManager.defaultRights(); - assert CastlingManager.toFEN(rights) == "KQkq"; - assert CastlingManager.toFEN(CastlingManager.noRights()) == "-"; + val rights = new CastlingRights(); val afterWhiteKingMove = CastlingManager.updateRights(rights, 'K', 60, 62); assert !afterWhiteKingMove.whiteKingside; @@ -117,19 +69,9 @@ module ChessBoardOpsTest { assert !afterRookCapture.whiteKingside; } - @Test - void shouldRespectMoveContextCastleChecks() { - val noRights = new MoveContext(); - assert !noRights.canCastle(Color.White, True); - - val whiteRights = new MoveContext(new CastlingRights(True, False, False, False)); - assert whiteRights.canCastle(Color.White, True); - assert !whiteRights.canCastle(Color.White, False); - } - @Test void shouldUpdateRightsWhenRookMoves() { - val rights = CastlingManager.defaultRights(); + val rights = new CastlingRights(); // White kingside rook moves from h1 (index 63) val afterKingsideRookMove = CastlingManager.updateRights(rights, 'R', 63, 55); assert !afterKingsideRookMove.whiteKingside; @@ -143,33 +85,12 @@ module ChessBoardOpsTest { @Test void shouldUpdateRightsForBlackKingMove() { - val rights = CastlingManager.defaultRights(); + val rights = new CastlingRights(); val afterBlackKingMove = CastlingManager.updateRights(rights, 'k', 4, 5); assert afterBlackKingMove.whiteKingside; assert afterBlackKingMove.whiteQueenside; assert !afterBlackKingMove.blackKingside; assert !afterBlackKingMove.blackQueenside; } - - @Test - void shouldCheckCanCastleForBothColors() { - val full = CastlingManager.defaultRights(); - assert CastlingManager.canCastle(full, Color.White, True); - assert CastlingManager.canCastle(full, Color.White, False); - assert CastlingManager.canCastle(full, Color.Black, True); - assert CastlingManager.canCastle(full, Color.Black, False); - - val none = CastlingManager.noRights(); - assert !CastlingManager.canCastle(none, Color.White, True); - assert !CastlingManager.canCastle(none, Color.White, False); - assert !CastlingManager.canCastle(none, Color.Black, True); - assert !CastlingManager.canCastle(none, Color.Black, False); - } - - @Test - void shouldCreateMoveContextWithEnPassant() { - val ctx = new MoveContext(new CastlingRights(), "e3"); - assert ctx.enPassantTarget == "e3"; - } } } diff --git a/chess-game/app/src/test/x/ChessBoardUtilsTest.x b/chess-game/app/src/test/x/ChessBoardUtilsTest.x index 069da62..f1b204f 100644 --- a/chess-game/app/src/test/x/ChessBoardUtilsTest.x +++ b/chess-game/app/src/test/x/ChessBoardUtilsTest.x @@ -85,11 +85,6 @@ module ChessBoardUtilsTest { board[40] = '.'; board[48] = '.'; assert DirectionUtils.isPathClear(0, 56, board); - - val ray = DirectionUtils.getRaySquares(0, DirectionUtils.SOUTH, 3); - assert ray.size == 3; - assert ray[0] == 8; - assert ray[2] == 24; } @Test diff --git a/chess-game/app/src/test/x/ChessComApiTest.x b/chess-game/app/src/test/x/ChessComApiTest.x new file mode 100644 index 0000000..e97604a --- /dev/null +++ b/chess-game/app/src/test/x/ChessComApiTest.x @@ -0,0 +1,76 @@ +module ChessComApiTest { + package chess import chess.examples.org; + package web import web.xtclang.org; + + import chess.api.ChessComApi; + + import web.responses.SimpleResponse; + + /** + * Tests for the chess.com proxy (`/api/chesscom`): every path segment the client controls is + * checked before it is placed in the upstream URL, so a bad value is refused here and never + * reaches chess.com. + * + * Calls that actually reach chess.com live in the opt-in `ChessLiveApiTest`. + */ + class ChessComApiTests { + static String bodyOf(SimpleResponse response) = response.body?.bytes.unpackUtf8() : ""; + + // ----- refused before reaching chess.com ------------------------------------------------- + + @Test + void shouldRefuseAMalformedUsername() { + ChessComApi api = new ChessComApi(); + + for (String name : ["ab", "has space", "../etc", "semi;colon", "slash/name"]) { + SimpleResponse player = api.player(name); + SimpleResponse archives = api.archives(name); + assert player.status == BadRequest; + assert archives.status == BadRequest; + assert bodyOf(player).indexOf("Invalid username"); + } + } + + @Test + void shouldRefuseAMalformedArchiveMonth() { + ChessComApi api = new ChessComApi(); + + assert api.games("hikaru", "26", "10").status == BadRequest; + assert api.games("hikaru", "2026", "1").status == BadRequest; + assert api.games("hikaru", "20x6", "10").status == BadRequest; + assert api.games("hikaru", "2026", "1a").status == BadRequest; + assert api.games("x", "2026", "10").status == BadRequest; + } + + // ----- the validation rules themselves --------------------------------------------------- + + @Test + void shouldAcceptChessComUsernames() { + assert ChessComApi.isValidUsername("hikaru"); + assert ChessComApi.isValidUsername("Magnus_Carlsen"); + assert ChessComApi.isValidUsername("a-b-c"); + assert ChessComApi.isValidUsername("abc"); + assert ChessComApi.isValidUsername("abcdefghijklmnopqrstuvwxy"); // 25, the maximum + } + + @Test + void shouldRejectAnythingThatCouldAlterTheUpstreamPath() { + assert !ChessComApi.isValidUsername("ab"); // too short + assert !ChessComApi.isValidUsername("abcdefghijklmnopqrstuvwxyz"); // 26, too long + assert !ChessComApi.isValidUsername("../admin"); + assert !ChessComApi.isValidUsername("name?x=1"); + assert !ChessComApi.isValidUsername("name%2F"); + assert !ChessComApi.isValidUsername("naïve"); + } + + @Test + void shouldRequireExactlyTheRightNumberOfDigits() { + assert ChessComApi.isDigits("2026", 4); + assert ChessComApi.isDigits("09", 2); + assert !ChessComApi.isDigits("202", 4); + assert !ChessComApi.isDigits("20266", 4); + assert !ChessComApi.isDigits("20a6", 4); + assert !ChessComApi.isDigits("", 2); + } + } +} diff --git a/chess-game/app/src/test/x/ChessDBEnumTest.x b/chess-game/app/src/test/x/ChessDBEnumTest.x index 10322b6..368ab0a 100644 --- a/chess-game/app/src/test/x/ChessDBEnumTest.x +++ b/chess-game/app/src/test/x/ChessDBEnumTest.x @@ -12,7 +12,6 @@ module ChessDBEnumTest { import db.models.TimeControl; import db.models.GameRecord; import db.models.OnlineGame; - import db.models.ChatMessage; /** * Tests for core enum values, value objects, and record construction. @@ -76,22 +75,6 @@ module ChessDBEnumTest { assert entry.toSquare == "e5"; assert entry.piece == 'p'; } - - @Test - void shouldConstructChatMessage() { - ChatMessage message = new ChatMessage("ROOM01", "player-1", Color.Black, "hello", new Time(0)); - assert message.roomCode == "ROOM01"; - assert message.playerColor == Color.Black; - assert message.message == "hello"; - } - - @Test - void shouldConstructChatMessageForWhite() { - ChatMessage msg = new ChatMessage("ROOM02", "player-2", Color.White, "good game", new Time(0)); - assert msg.roomCode == "ROOM02"; - assert msg.playerColor == Color.White; - assert msg.message == "good game"; - } } /** diff --git a/chess-game/app/src/test/x/ChessDBPieceTest.x b/chess-game/app/src/test/x/ChessDBPieceTest.x deleted file mode 100644 index 20114a4..0000000 --- a/chess-game/app/src/test/x/ChessDBPieceTest.x +++ /dev/null @@ -1,100 +0,0 @@ -module ChessDBPieceTest { - package db import chessDB.examples.org; - - import db.models.Color; - import db.types.PieceType; - import db.factory.PieceFactory; - import db.base.Piece; - import db.pieces.Pawn; - import db.pieces.Knight; - import db.pieces.Bishop; - import db.pieces.Rook; - import db.pieces.Queen; - import db.pieces.King; - - /** - * Tests for PieceType properties and PieceFactory product creation. - */ - class PieceTypeAndFactoryTests { - @Test - void shouldExposePieceTypeProperties() { - assert PieceType.Pawn.symbol == 'p'; - assert PieceType.Knight.value == 320; - assert PieceType.Queen.isMajorPiece(); - assert PieceType.Bishop.isMinorPiece(); - assert PieceType.Rook.isSliding(); - assert PieceType.King.getChar(Color.White) == 'K'; - } - - @Test - void shouldCreateAllPiecesFromFactory() { - Piece pawn; - Piece knight; - Piece bishop; - Piece rook; - Piece queen; - Piece king; - - if (Piece p := PieceFactory.createPiece('p', Color.White)) { pawn = p; } else { assert False; } - if (Piece n := PieceFactory.createPiece('n', Color.Black)) { knight = n; } else { assert False; } - if (Piece b := PieceFactory.createPiece('b', Color.White)) { bishop = b; } else { assert False; } - if (Piece r := PieceFactory.createPiece('r', Color.Black)) { rook = r; } else { assert False; } - if (Piece q := PieceFactory.createPiece('q', Color.White)) { queen = q; } else { assert False; } - if (Piece k := PieceFactory.createPiece('k', Color.Black)) { king = k; } else { assert False; } - - assert pawn.getChar() == 'p'; - assert knight.getChar() == 'N'; - assert bishop.getChar() == 'b'; - assert rook.getChar() == 'R'; - assert queen.getChar() == 'q'; - assert king.getChar() == 'K'; - } - - @Test - void shouldRecognizePieceTypes() { - assert PieceFactory.isPieceType('Q', 'q'); - assert PieceFactory.isPieceType('q', 'q'); - assert !PieceFactory.isPieceType('R', 'q'); - } - - @Test - void shouldCreateStandardSet() { - assert PieceFactory.createStandardSet(Color.White).size == 16; - assert PieceFactory.createStandardSet(Color.Black).size == 16; - } - - @Test - void shouldIdentifyMajorAndMinorPieces() { - assert PieceType.Queen.isMajorPiece(); - assert PieceType.Rook.isMajorPiece(); - assert !PieceType.Bishop.isMajorPiece(); - assert !PieceType.Knight.isMajorPiece(); - assert !PieceType.Pawn.isMajorPiece(); - - assert PieceType.Bishop.isMinorPiece(); - assert PieceType.Knight.isMinorPiece(); - assert !PieceType.Queen.isMinorPiece(); - assert !PieceType.Rook.isMinorPiece(); - } - - @Test - void shouldIdentifySlidingPieces() { - assert PieceType.Rook.isSliding(); - assert PieceType.Bishop.isSliding(); - assert PieceType.Queen.isSliding(); - assert !PieceType.Knight.isSliding(); - assert !PieceType.King.isSliding(); - assert !PieceType.Pawn.isSliding(); - } - - @Test - void shouldReturnCorrectCharForBothColors() { - assert PieceType.Pawn.getChar(Color.White) == 'P'; - assert PieceType.Pawn.getChar(Color.Black) == 'p'; - assert PieceType.King.getChar(Color.White) == 'K'; - assert PieceType.King.getChar(Color.Black) == 'k'; - assert PieceType.Queen.getChar(Color.White) == 'Q'; - assert PieceType.Queen.getChar(Color.Black) == 'q'; - } - } -} diff --git a/chess-game/app/src/test/x/ChessEngineApiTest.x b/chess-game/app/src/test/x/ChessEngineApiTest.x new file mode 100644 index 0000000..c7e3e5f --- /dev/null +++ b/chess-game/app/src/test/x/ChessEngineApiTest.x @@ -0,0 +1,79 @@ +module ChessEngineApiTest { + package chess import chess.examples.org; + + import chess.ai.StockfishApi; + import chess.utils.BoardUtils; + + /** + * Tests for the Stockfish Online client's pure helpers: reading the engine's JSON reply, + * turning a UCI `bestmove` line into board indices, and escaping a FEN for a query string. + * + * Nothing here reaches the network; the live call is exercised by running the app. + */ + class StockfishApiTests { + static String OK_REPLY = + "{\"success\":true,\"evaluation\":0.46,\"mate\":null," + + "\"bestmove\":\"bestmove e7e5 ponder g1f3\",\"continuation\":\"e7e5 g1f3 b8c6\"}"; + + static String MATE_REPLY = + "{\"success\":true,\"evaluation\":null,\"mate\":\"1\"," + + "\"bestmove\":\"bestmove e1e8\",\"continuation\":\"e1e8\"}"; + + // Note the space after the comma: the API sends this form on a rejected request. + static String ERROR_REPLY = "{\"success\":false, \"error\":\"Invalid FEN\"}"; + + @Test + void shouldReadStringAndNumberFields() { + assert StockfishApi.jsonField(OK_REPLY, "success") == "true"; + assert StockfishApi.jsonField(OK_REPLY, "evaluation") == "0.46"; + assert StockfishApi.jsonField(OK_REPLY, "bestmove") == "bestmove e7e5 ponder g1f3"; + assert StockfishApi.jsonField(OK_REPLY, "continuation") == "e7e5 g1f3 b8c6"; + } + + @Test + void shouldReadNullAndMissingFieldsAsNull() { + assert StockfishApi.jsonField(OK_REPLY, "mate") == Null; + assert StockfishApi.jsonField(OK_REPLY, "nonesuch") == Null; + assert StockfishApi.jsonField(MATE_REPLY, "evaluation") == Null; + assert StockfishApi.jsonField(MATE_REPLY, "mate") == "1"; + } + + @Test + void shouldReadARejectedRequest() { + assert StockfishApi.jsonField(ERROR_REPLY, "success") == "false"; + assert StockfishApi.jsonField(ERROR_REPLY, "error") == "Invalid FEN"; + } + + @Test + void shouldParseABestMoveLineIntoBoardIndices() { + val move = StockfishApi.parseBestMove("bestmove e7e5 ponder g1f3"); + assert move.usable; + assert BoardUtils.toAlgebraic(move.fromIndex) == "e7"; + assert BoardUtils.toAlgebraic(move.toIndex) == "e5"; + assert move.promotion == Null; + } + + @Test + void shouldParseAPromotion() { + val move = StockfishApi.parseBestMove("bestmove a7a8q"); + assert move.usable; + assert BoardUtils.toAlgebraic(move.fromIndex) == "a7"; + assert BoardUtils.toAlgebraic(move.toIndex) == "a8"; + assert move.promotion == "q"; + } + + @Test + void shouldRejectAnAnswerWithNoMove() { + assert !StockfishApi.parseBestMove("bestmove (none)").usable; + assert !StockfishApi.parseBestMove("bestmove").usable; + assert !StockfishApi.parseBestMove("").usable; + assert !StockfishApi.parseBestMove("bestmove z9z9").usable; + } + + @Test + void shouldEscapeAFenForAQueryString() { + assert StockfishApi.urlEncode("rnbq/8 w KQkq - 0 1") == "rnbq%2F8%20w%20KQkq%20-%200%201"; + assert StockfishApi.urlEncode("abcXYZ019-_.~") == "abcXYZ019-_.~"; + } + } +} diff --git a/chess-game/app/src/test/x/ChessGameInitTest.x b/chess-game/app/src/test/x/ChessGameInitTest.x index 33a8201..9ab8b78 100644 --- a/chess-game/app/src/test/x/ChessGameInitTest.x +++ b/chess-game/app/src/test/x/ChessGameInitTest.x @@ -4,13 +4,11 @@ module ChessGameInitTest { import chess.core.ChessLogic; import chess.core.ChessGame; - import chess.core.ChessGame.MoveOutcome; import db.models.Color; import db.models.CastlingRights; import db.models.GameRecord; import db.models.GameStatus; - import db.models.MoveHistoryEntry; /** * Tests for game initialization, default state and board setup. @@ -114,25 +112,25 @@ module ChessGameInitTest { @Test void shouldFormatMoveNotation() { - assert ChessLogic.createMoveNotation('P', 52, 36, False, Null, False, False, Null) == "e4"; - assert ChessLogic.createMoveNotation('N', 62, 45, False, Null, True, False, Null) == "Nf3+"; - assert ChessLogic.createMoveNotation('K', 60, 62, False, Null, False, False, "O-O") == "O-O"; - assert ChessLogic.createMoveNotation('p', 8, 0, False, 'Q', False, True, Null) == "a8=Q#"; + assert ChessGame.createMoveNotation('P', 52, 36, False, Null, False, False, Null) == "e4"; + assert ChessGame.createMoveNotation('N', 62, 45, False, Null, True, False, Null) == "Nf3+"; + assert ChessGame.createMoveNotation('K', 60, 62, False, Null, False, False, "O-O") == "O-O"; + assert ChessGame.createMoveNotation('p', 8, 0, False, 'Q', False, True, Null) == "a8=Q#"; } @Test void shouldFormatCaptureNotation() { // Pawn capture - assert ChessLogic.createMoveNotation('P', 52, 43, True, Null, False, False, Null) == "xd3"; + assert ChessGame.createMoveNotation('P', 52, 43, True, Null, False, False, Null) == "xd3"; // Knight capture with check - assert ChessLogic.createMoveNotation('N', 62, 45, True, Null, True, False, Null) == "Nxf3+"; + assert ChessGame.createMoveNotation('N', 62, 45, True, Null, True, False, Null) == "Nxf3+"; // Queen capture with checkmate - assert ChessLogic.createMoveNotation('Q', 59, 4, True, Null, False, True, Null) == "Qxe8#"; + assert ChessGame.createMoveNotation('Q', 59, 4, True, Null, False, True, Null) == "Qxe8#"; } } /** - * Tests for legacy checkGameStatus method. + * Tests for checkGameStatus: checkmate, stalemate, and ongoing detection from board material. */ class LegacyStatusTests { @Test diff --git a/chess-game/app/src/test/x/ChessGamePlayTest.x b/chess-game/app/src/test/x/ChessGamePlayTest.x index 2b965db..ae6c5b9 100644 --- a/chess-game/app/src/test/x/ChessGamePlayTest.x +++ b/chess-game/app/src/test/x/ChessGamePlayTest.x @@ -3,8 +3,6 @@ module ChessGamePlayTest { package db import chessDB.examples.org; import chess.core.ChessLogic; - import chess.core.ChessGame.MoveOutcome; - import chess.core.ChessGame.AutoResponse; import db.models.Color; import db.models.CastlingRights; diff --git a/chess-game/app/src/test/x/ChessLiveApiTest.x b/chess-game/app/src/test/x/ChessLiveApiTest.x new file mode 100644 index 0000000..92fac5e --- /dev/null +++ b/chess-game/app/src/test/x/ChessLiveApiTest.x @@ -0,0 +1,96 @@ +module ChessLiveApiTest { + package chess import chess.examples.org; + package web import web.xtclang.org; + + import chess.api.ChessApi; + import chess.api.ChessComApi; + import chess.api.EngineApi; + + import web.responses.SimpleResponse; + + /** + * End-to-end tests against the real upstream services: Stockfish Online and chess.com. + * + * These need an internet connection and are subject to the upstream rate limits, so they are + * not part of the default run. Run them with `scripts/test.sh --live`. + */ + class LiveApiTests { + static String AFTER_E4 = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1"; + + static String bodyOf(SimpleResponse response) = response.body?.bytes.unpackUtf8() : ""; + + /** + * Stockfish Online answers 429 to a burst; leave the documented gap between calls. + */ + static void pace() { + @Inject Clock clock; + Time start = clock.now; + while (clock.now - start < Duration.ofMillis(1600)) {} + } + + @Test + void shouldAnalyseAPositionWithTheEngine() { + SimpleResponse response = new EngineApi().analyse(AFTER_E4, 10); + String body = bodyOf(response); + + assert response.status == OK; + assert body.indexOf("\"success\":true"); + assert body.indexOf("\"bestmove\":\""); + assert body.indexOf("\"evaluation\":"); + pace(); + } + + @Test + void shouldReturnTheEnginesMoveAsBoardIndices() { + SimpleResponse response = new EngineApi().bestmove(AFTER_E4, 10); + String body = bodyOf(response); + + assert response.status == OK; + assert body.indexOf("\"fromSquare\":\""); + assert body.indexOf("\"toSquare\":\""); + pace(); + } + + @Test + void shouldFetchTheChessComDailyPuzzle() { + SimpleResponse response = new ChessComApi().puzzle(); + String body = bodyOf(response); + + assert response.status == OK; + assert body.indexOf("\"fen\":"); + } + + @Test + void shouldFetchAChessComProfile() { + SimpleResponse response = new ChessComApi().player("hikaru"); + + assert response.status == OK; + assert bodyOf(response).indexOf("\"username\":"); + } + + @Test + void shouldGetAReplyFromTheComputer() { + @Inject Random random; + ChessApi api = new ChessApi(); + String id = $"live-{random.int(1_000_000_000)}"; + + api.move(id, "e2", "e4"); + + // The server holds the reply back for its thinking delay, then asks the engine on the + // first request after it. Poll the way the client does. + @Inject Clock clock; + Time started = clock.now; + while (api.state(id).turn != "White") { + assert clock.now - started < Duration.ofSeconds(30) as "No reply within 30s"; + Time pause = clock.now; + while (clock.now - pause < Duration.ofMillis(500)) {} + } + + val state = api.state(id); + assert state.moveHistory.size == 2; + assert state.moveHistory[1].color.toString() == "Black"; + assert state.fen.indexOf(" w "); + pace(); + } + } +} diff --git a/chess-game/app/src/test/x/ChessMoveValidatorTest.x b/chess-game/app/src/test/x/ChessMoveValidatorTest.x index bbc1340..96f82ce 100644 --- a/chess-game/app/src/test/x/ChessMoveValidatorTest.x +++ b/chess-game/app/src/test/x/ChessMoveValidatorTest.x @@ -67,45 +67,6 @@ module ChessMoveValidatorTest { assert result.errorMessage == "Move leaves king in check"; } - @Disabled("MoveValidator.isCapture/isPromotion flag detection failing — needs investigation") - @Test - void shouldDetectCapturePromoAndCastlingFlags() { - val board = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); - // isCapture: black pawn on d5 vs white pawn on e4 - val captureBoard = new Char[64](i -> '.'); - captureBoard[0] = 'k'; - captureBoard[63] = 'K'; - captureBoard[36] = 'P'; // e4 - captureBoard[27] = 'p'; // d5 - assert MoveValidator.isCapture(captureBoard, 36, 27); - assert !MoveValidator.isCapture(captureBoard, 36, 28); - - // isPromotion: pawn reaching last rank - assert MoveValidator.isPromotion(captureBoard, 8, 0); // white pawn index 8 to 0 would be promo, but we need a pawn - val promoBoard = new Char[64](i -> '.'); - promoBoard[0] = 'k'; - promoBoard[63] = 'K'; - promoBoard[8] = 'P'; - assert MoveValidator.isPromotion(promoBoard, 8, 0); - assert !MoveValidator.isPromotion(promoBoard, 63, 55); // King is not a pawn - - // isCastling: king moving two squares - assert MoveValidator.isCastling(board, 60, 62); - assert !MoveValidator.isCastling(board, 60, 61); - } - - @Test - void shouldDetectEnPassantCapture() { - val board = new Char[64](i -> '.'); - board[0] = 'k'; - board[63] = 'K'; - board[28] = 'P'; // e5 - board[27] = 'p'; // d5 - assert MoveValidator.isEnPassant(board, 28, 19, "d6"); - assert !MoveValidator.isEnPassant(board, 28, 19, Null); - assert !MoveValidator.isEnPassant(board, 28, 20, "d6"); - } - @Test void shouldValidateMoveWithTargetIndexOutOfRange() { val board = BoardUtils.cloneBoard(ChessLogic.defaultBoard()); diff --git a/chess-game/app/src/test/x/ChessOnlineLogicTest.x b/chess-game/app/src/test/x/ChessOnlineLogicTest.x index 3b6e7ed..b87a2c5 100644 --- a/chess-game/app/src/test/x/ChessOnlineLogicTest.x +++ b/chess-game/app/src/test/x/ChessOnlineLogicTest.x @@ -9,7 +9,6 @@ module ChessOnlineLogicTest { import db.models.Color; import db.models.GameMode; - import db.models.GameRecord; import db.models.GameStatus; import db.models.TimeControl; import db.models.OnlineGame; diff --git a/chess-game/app/src/test/x/ChessSpecialMovesTest.x b/chess-game/app/src/test/x/ChessSpecialMovesTest.x index 65c165e..1c195c6 100644 --- a/chess-game/app/src/test/x/ChessSpecialMovesTest.x +++ b/chess-game/app/src/test/x/ChessSpecialMovesTest.x @@ -3,7 +3,7 @@ module ChessSpecialMovesTest { package db import chessDB.examples.org; import chess.core.ChessLogic; - import chess.core.ChessGame.MoveOutcome; + import chess.core.ChessGame; import chess.utils.BoardUtils; import db.models.Color; @@ -28,7 +28,7 @@ module ChessSpecialMovesTest { val record = new GameRecord( new String(board), Color.White, GameStatus.Ongoing, Null, 0, 0, new CastlingRights(True, True, True, True), Null, [], Null, 0); - val castled = ChessLogic.applyMove(record, board, 60, 62, Null); + val castled = ChessGame.applyMove(record, board, 60, 62, Null); assert castled.board[62] == 'K'; assert castled.board[61] == 'R'; assert castled.board[63] == '.'; @@ -49,7 +49,7 @@ module ChessSpecialMovesTest { val record = new GameRecord( new String(board), Color.White, GameStatus.Ongoing, Null, 0, 0, new CastlingRights(True, True, True, True), Null, [], Null, 0); - val castled = ChessLogic.applyMove(record, board, 60, 58, Null); + val castled = ChessGame.applyMove(record, board, 60, 58, Null); assert castled.board[58] == 'K'; assert castled.board[59] == 'R'; assert castled.board[56] == '.'; @@ -66,7 +66,7 @@ module ChessSpecialMovesTest { val record = new GameRecord( new String(board), Color.White, GameStatus.Ongoing, Null, 0, 0, new CastlingRights(False, False, False, False), Null, [], Null, 0); - val promoted = ChessLogic.applyMove(record, board, 8, 0, Null); + val promoted = ChessGame.applyMove(record, board, 8, 0, Null); assert promoted.board[0] == 'Q'; assert promoted.board[8] == '.'; } @@ -81,7 +81,7 @@ module ChessSpecialMovesTest { val record = new GameRecord( new String(board), Color.White, GameStatus.Ongoing, Null, 0, 0, new CastlingRights(False, False, False, False), "d6", [], Null, 0); - val enPassant = ChessLogic.applyMove(record, board, 28, 19, Null); + val enPassant = ChessGame.applyMove(record, board, 28, 19, Null); assert enPassant.board[19] == 'P'; assert enPassant.board[27] == '.'; assert enPassant.board[28] == '.'; @@ -124,7 +124,7 @@ module ChessSpecialMovesTest { new String(board), Color.White, GameStatus.Ongoing, Null, 0, 0, new CastlingRights(True, True, True, True), Null, [], Null, 0); // Move white king one square (not castling) - val moved = ChessLogic.applyMove(record, board, 60, 61, Null); + val moved = ChessGame.applyMove(record, board, 60, 61, Null); assert !moved.castlingRights.whiteKingside; assert !moved.castlingRights.whiteQueenside; // Black castling rights should remain diff --git a/chess-game/app/src/test/x/ChessTimeControlTest.x b/chess-game/app/src/test/x/ChessTimeControlTest.x index ed9028a..84ae4f7 100644 --- a/chess-game/app/src/test/x/ChessTimeControlTest.x +++ b/chess-game/app/src/test/x/ChessTimeControlTest.x @@ -10,7 +10,7 @@ module ChessTimeControlTest { import xunit.annotations.Disabled; /** - * Tests for TimeControlService: creation, move updates, timeout detection, presets. + * Tests for TimeControlService: creation, move updates, timeout detection. */ class TimeControlCreationTests { TimeControlService tcs = new TimeControlService(); @@ -112,79 +112,4 @@ module ChessTimeControlTest { assert tcs.getRemainingTime(tc, Color.Black) == 0; } } - - /** - * Tests for preset time control factories. - */ - class TimeControlPresetTests { - TimeControlService tcs = new TimeControlService(); - - @Test - void shouldCreateBulletPresets() { - val bullet = tcs.bullet(); - assert bullet.whiteTimeMs == 60_000; - assert bullet.blackTimeMs == 60_000; - assert bullet.incrementMs == 0; - - val bullet1plus1 = tcs.bullet1plus1(); - assert bullet1plus1.whiteTimeMs == 60_000; - assert bullet1plus1.incrementMs == 1_000; - - val bullet2plus1 = tcs.bullet2plus1(); - assert bullet2plus1.whiteTimeMs == 120_000; - assert bullet2plus1.incrementMs == 1_000; - } - - @Test - void shouldCreateBlitzPresets() { - val blitz3 = tcs.blitz3(); - assert blitz3.whiteTimeMs == 180_000; - assert blitz3.incrementMs == 0; - - val blitz3plus2 = tcs.blitz3plus2(); - assert blitz3plus2.whiteTimeMs == 180_000; - assert blitz3plus2.incrementMs == 2_000; - - val blitz5 = tcs.blitz5(); - assert blitz5.whiteTimeMs == 300_000; - assert blitz5.incrementMs == 0; - - val blitz5plus3 = tcs.blitz5plus3(); - assert blitz5plus3.whiteTimeMs == 300_000; - assert blitz5plus3.incrementMs == 3_000; - } - - @Test - void shouldCreateRapidPresets() { - val rapid10 = tcs.rapid10(); - assert rapid10.whiteTimeMs == 600_000; - assert rapid10.incrementMs == 0; - - val rapid15plus10 = tcs.rapid15plus10(); - assert rapid15plus10.whiteTimeMs == 900_000; - assert rapid15plus10.incrementMs == 10_000; - - val rapid30 = tcs.rapid30(); - assert rapid30.whiteTimeMs == 1_800_000; - assert rapid30.incrementMs == 0; - } - - @Test - void shouldCreateClassicalPreset() { - val classical = tcs.classical(); - assert classical.whiteTimeMs == 5_400_000; - assert classical.incrementMs == 30_000; - } - - @Test - void shouldEnsureAllPresetsHaveEqualStartingTimes() { - TimeControl[] presets = [tcs.bullet(), tcs.bullet1plus1(), tcs.bullet2plus1(), - tcs.blitz3(), tcs.blitz3plus2(), tcs.blitz5(), tcs.blitz5plus3(), - tcs.rapid10(), tcs.rapid15plus10(), tcs.rapid30(), - tcs.classical()]; - for (TimeControl preset : presets) { - assert preset.whiteTimeMs == preset.blackTimeMs; - } - } - } } diff --git a/chess-game/app/src/test/x/EngineApiTest.x b/chess-game/app/src/test/x/EngineApiTest.x new file mode 100644 index 0000000..77b870a --- /dev/null +++ b/chess-game/app/src/test/x/EngineApiTest.x @@ -0,0 +1,91 @@ +module EngineApiTest { + package chess import chess.examples.org; + package web import web.xtclang.org; + + import chess.api.EngineApi; + + import web.responses.SimpleResponse; + + /** + * Tests for the engine proxy (`/api/engine`): input that must be refused before any request + * leaves the server, and the encoding of the engine's reply into JSON. + * + * Calls that actually reach Stockfish Online live in the opt-in `ChessLiveApiTest`. + */ + class EngineApiTests { + static String START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + + static String bodyOf(SimpleResponse response) = response.body?.bytes.unpackUtf8() : ""; + + // ----- refused before reaching the engine ------------------------------------------------ + + @Test + void shouldRefuseToAnalyseSomethingThatIsNotAFen() { + SimpleResponse response = new EngineApi().analyse("not a position", 10); + + assert response.status == BadRequest; + assert bodyOf(response).indexOf("\"success\":false"); + assert bodyOf(response).indexOf("Invalid FEN"); + } + + @Test + void shouldRefuseABestMoveRequestForSomethingThatIsNotAFen() { + SimpleResponse response = new EngineApi().bestmove("8/8/8 w", 10); + assert response.status == BadRequest; + } + + // ----- what counts as a plausible FEN ---------------------------------------------------- + + @Test + void shouldAcceptRealPositions() { + assert EngineApi.isPlausibleFen(START); + assert EngineApi.isPlausibleFen("r4rk1/b4pp1/8/R2N4/1p5p/1P5P/4BPP1/6K1 w - - 0 1"); + assert EngineApi.isPlausibleFen("rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 2"); + } + + @Test + void shouldRejectMalformedPositions() { + assert !EngineApi.isPlausibleFen(""); + assert !EngineApi.isPlausibleFen("short"); + assert !EngineApi.isPlausibleFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP w KQkq - 0 1"); // seven ranks + assert !EngineApi.isPlausibleFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR x KQkq - 0 1"); + assert !EngineApi.isPlausibleFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"); // no side to move + assert !EngineApi.isPlausibleFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\n"); + assert !EngineApi.isPlausibleFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 ♞"); + } + + // ----- encoding the reply ---------------------------------------------------------------- + + @Test + void shouldPassNumbersThroughAndDropAnythingElse() { + assert EngineApi.jsonNumber("0.46") == "0.46"; + assert EngineApi.jsonNumber("-3.2") == "-3.2"; + assert EngineApi.jsonNumber("1") == "1"; + assert EngineApi.jsonNumber(Null) == "null"; + assert EngineApi.jsonNumber("") == "null"; + assert EngineApi.jsonNumber("-") == "null"; + assert EngineApi.jsonNumber("1e9") == "null"; + assert EngineApi.jsonNumber("0.4,\"x\":1") == "null"; + } + + @Test + void shouldQuotePlainTextAndRefuseAnythingThatCouldBreakTheJson() { + assert EngineApi.jsonText("e7e5") == "\"e7e5\""; + assert EngineApi.jsonText("e7e5 g1f3 b8c6") == "\"e7e5 g1f3 b8c6\""; + assert EngineApi.jsonText(Null) == "null"; + assert EngineApi.jsonText("a\"b") == "null"; + assert EngineApi.jsonText("a\\b") == "null"; + assert EngineApi.jsonText("tab\there") == "null"; + assert EngineApi.jsonText("é") == "null"; + } + + @Test + void shouldPullTheMoveOutOfABestMoveLine() { + assert EngineApi.uciOf("bestmove e7e5 ponder g1f3") == "e7e5"; + assert EngineApi.uciOf("bestmove a7a8q") == "a7a8q"; + assert EngineApi.uciOf("bestmove") == Null; + assert EngineApi.uciOf("") == Null; + assert EngineApi.uciOf(Null) == Null; + } + } +} diff --git a/chess-game/app/src/test/x/OnlineChessApiTest.x b/chess-game/app/src/test/x/OnlineChessApiTest.x new file mode 100644 index 0000000..14418e6 --- /dev/null +++ b/chess-game/app/src/test/x/OnlineChessApiTest.x @@ -0,0 +1,145 @@ +module OnlineChessApiTest { + package chess import chess.examples.org; + package db import chessDB.examples.org; + + import chess.api.OnlineChessApi; + import chess.core.OnlineChessLogic.RoomCreated; + + /** + * Endpoint tests for the two-player service (`/api/online`): creating and joining rooms, + * turn order, moves, valid moves, reset and leaving, against a real database. + */ + class OnlineChessApiTests { + /** + * A room with both seats taken, as (api, room code, White's id, Black's id). + */ + static (OnlineChessApi, String, String, String) fullRoom() { + OnlineChessApi api = new OnlineChessApi(); + RoomCreated created = api.createRoom(); + val joined = api.joinRoom(created.roomCode); + return api, created.roomCode, created.playerId, joined.playerId; + } + + @Test + void shouldCreateARoomWithAShareableCode() { + OnlineChessApi api = new OnlineChessApi(); + RoomCreated created = api.createRoom(); + + assert created.roomCode.size == 6; + for (Char ch : created.roomCode) { + assert ch.asciiUppercase() || ch.asciiDigit(); + } + assert created.playerId.size > 0; + } + + @Test + void shouldSeatTheCreatorAsWhiteAndWaitForAnOpponent() { + OnlineChessApi api = new OnlineChessApi(); + RoomCreated created = api.createRoom(); + val state = api.getState(created.roomCode, created.playerId); + + assert state.playerColor == "White"; + assert state.waitingForOpponent; + assert !state.isYourTurn; + } + + @Test + void shouldSeatTheSecondPlayerAsBlack() { + (OnlineChessApi api, String room, String white, String black) = fullRoom(); + + assert black.size > 0 && black != white; + assert api.getState(room, black).playerColor == "Black"; + assert api.getState(room, white).isYourTurn; + assert !api.getState(room, black).isYourTurn; + } + + @Test + void shouldTurnAwayAThirdPlayer() { + (OnlineChessApi api, String room, _, _) = fullRoom(); + + val third = api.joinRoom(room); + assert third.message == "Room is full."; + assert third.playerColor == "Spectator"; + } + + @Test + void shouldReportAnUnknownRoom() { + OnlineChessApi api = new OnlineChessApi(); + + assert api.joinRoom("ZZZZZ9").message == "Room not found."; + assert api.getState("ZZZZZ9", "anyone").message == "Room not found."; + } + + @Test + void shouldPlayAMoveAndPassTheTurn() { + (OnlineChessApi api, String room, String white, String black) = fullRoom(); + + val afterWhite = api.makeMove(room, white, "e2", "e4"); + assert afterWhite.turn == "Black"; + assert afterWhite.lastMove == "e2e4"; + assert api.getState(room, black).isYourTurn; + + val afterBlack = api.makeMove(room, black, "e7", "e5"); + assert afterBlack.turn == "White"; + assert afterBlack.moveHistory.size == 2; + } + + @Test + void shouldRefuseAMoveOutOfTurn() { + (OnlineChessApi api, String room, String white, String black) = fullRoom(); + + val state = api.makeMove(room, black, "e7", "e5"); + assert state.turn == "White"; + assert state.moveHistory.empty; + } + + @Test + void shouldRefuseAMoveBeforeTheOpponentArrives() { + OnlineChessApi api = new OnlineChessApi(); + RoomCreated created = api.createRoom(); + + val state = api.makeMove(created.roomCode, created.playerId, "e2", "e4"); + assert state.moveHistory.empty; + } + + @Test + void shouldListValidMovesOnlyForThePlayerToMove() { + (OnlineChessApi api, String room, String white, String black) = fullRoom(); + + val mine = api.getValidMoves(room, white, "e2"); + assert mine.success; + assert mine.validMoves.contains("e3") && mine.validMoves.contains("e4"); + + assert api.getValidMoves(room, black, "e7").validMoves.empty; + assert !api.getValidMoves(room, "stranger", "e2").success; + } + + @Test + void shouldResetTheBoardForBothPlayers() { + (OnlineChessApi api, String room, String white, String black) = fullRoom(); + api.makeMove(room, white, "e2", "e4"); + + val state = api.resetGame(room, white); + assert state.moveHistory.empty; + assert state.turn == "White"; + assert api.getState(room, black).moveHistory.empty; + } + + @Test + void shouldStartAClockWhenTheRoomHasATimeControl() { + OnlineChessApi api = new OnlineChessApi(); + RoomCreated created = api.createRoom(new OnlineChessApi.CreateRoomRequest(180_000, 2_000)); + + assert val clock ?= api.getState(created.roomCode, created.playerId).timeControl; + assert clock.incrementMs == 2_000; + } + + @Test + void shouldCloseTheRoomWhenAPlayerLeaves() { + (OnlineChessApi api, String room, String white, _) = fullRoom(); + + val left = api.leaveGame(room, white); + assert left.message.indexOf("left the game"); + } + } +} diff --git a/chess-game/app/webapp/index.html b/chess-game/app/webapp/index.html new file mode 100644 index 0000000..7e8669b --- /dev/null +++ b/chess-game/app/webapp/index.html @@ -0,0 +1,23 @@ + + + + + + + Chess Playground + + + +
+ + + diff --git a/chess-game/app/webapp/package-lock.json b/chess-game/app/webapp/package-lock.json new file mode 100644 index 0000000..c31801f --- /dev/null +++ b/chess-game/app/webapp/package-lock.json @@ -0,0 +1,2384 @@ +{ + "name": "chess-game-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "chess-game-web", + "version": "0.1.0", + "dependencies": { + "@fontsource/dosis": "5.3.0", + "@fontsource/dynapuff": "5.3.0", + "@tanstack/charts": "1.0.0", + "@tanstack/react-query": "5.104.0", + "@tanstack/react-table": "9.2.4", + "chess.js": "^1.4.0", + "motion": "13.4.4", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", + "vite": "^5.4.11" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", + "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.8", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@fontsource/dosis": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/dosis/-/dosis-5.3.0.tgz", + "integrity": "sha512-qW82PZqGdPK7KsOm3tkCWohdyPltMxJ/detZSwsAplZVFqQPh1JwpwFQOuZ5/wFKcBSjD7ORx1SKcHFkkH+Rqw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/dynapuff": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/dynapuff/-/dynapuff-5.3.0.tgz", + "integrity": "sha512-6QPd4M/F46ADrRAA3pu3Dob4iXgmac0YhNunK/1Sl+7wa2xOy7+espZ1gzC49kaozenrdBpqiSr7dYZScHzrKg==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.5.tgz", + "integrity": "sha512-J25QJU+B78T4FhhBsNpLJyVWOi31mwtpcMwywHmOKH65Q9IWGA81gPj+dnwlhU8wktVriYE+tFAaQgrnJRzAZg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.5.tgz", + "integrity": "sha512-LDopB3zuZM5Ux9TT2luNEBJW/tYbGU2g1d+VpKk6I+gSKDb+/7sYE6M225gRQt4RbMX6MSwMsVR/phdjVUgRLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.5.tgz", + "integrity": "sha512-wlJEERGfeuHeBavCL2qVnNacOK43NDoZM4sjkeRPymd04OAE9T1zBqDJgmZ+CIsPTYKwdzpUC8vmOw84dwY4Tg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.5.tgz", + "integrity": "sha512-4nJJGg5jbo2wwPP4JP+LfEBA3bvP8rU9CLuhp7jWvq9sxEyhjQFTFdrqi+/dHEin/pd8jpT0vcehIpnZtmEdcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.5.tgz", + "integrity": "sha512-DrZbyCDF1hneuO6jRbvZ2D7+PIBM6yIwYnJpg2vIk58T+wuFpiaGZrfUr59lDWw45bg+IrpTGLPiNi/Fk4w3Cg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.5.tgz", + "integrity": "sha512-gqfUVMJMB3mehqywxp6hTBFfgtMQykZY19+cfiaYP0toIJLb/1DZRJHVkQQGP13W4TAwfZDWeg1qBcheTRioXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.5.tgz", + "integrity": "sha512-CFmhpvAwzSaWMlN3VN7UtmoTihlZNzoP0juQib5TQRnYUyDV8dXeWOp29sobWAT6gXl/hQgAClLlEiYozQG3OQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.5.tgz", + "integrity": "sha512-Uc9H8eXCOayV6JLTH5bXKMId6qbhNHa818/BgYjm4jrlq3vZquC9cqyvHBw17xy5Mnj5f+I3gFK5JcEf3hSqrw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.5.tgz", + "integrity": "sha512-VcPr/szv/1BFw112Kt//fxulXt/JPqzzidU84iW68L2DdjnOO8QFUv2zTSYBEPHD6movBD4z+bbr5y60GYM7Jw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.5.tgz", + "integrity": "sha512-BnxtJ5/91BrIHYIkGrmjz/lbMhqEHt1dPFqIxIFR+jPn0xVc/oUSCtIT089zfp5ufwGDlYz2UC+Fe1SRBpYFbQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.5.tgz", + "integrity": "sha512-LrYcHZwF+fAMNKHYTOQ5osWM4AZF7YF6D+XtsjDyEvljtt11twc+zHVXBLNEjxVSUnKYsOhvVz4Z213eW02COQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.5.tgz", + "integrity": "sha512-nj7QKQePAAUpCpJHtg0pR0W/b92A9NO17JS3BAQmHDn/yhmkir2p8llrKY9TOhleKIaSzy1JhxS3T9FVld6coA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.5.tgz", + "integrity": "sha512-5ylkX6dWMeBKge9nTU+Rxfb+ZfaCIJ9lRqIFaK0eAMcWp7OJbYnLveLgXmm0VrvuLKb8qIK+mHyH0qu88RM+iA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.5.tgz", + "integrity": "sha512-oHK4ZHYFDKjZviK34I+NwgfbGxgI7ztrNxj2hPTSSNFgeq1a/lEd7dHV2fdGAuTH4Iym3RHJg+vAbWaWG4B7Zg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.5.tgz", + "integrity": "sha512-UcetmHZ6XOXuUByiKZyQmb55ZPr0LABr3Ec/HB9wKZn6CEAFWZkE+hsJErJ9hbPBC7nI0dKuELx7CoV6IM7TMg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.5.tgz", + "integrity": "sha512-C5CmDPQBtvjVo8cgQsBs+w6WB0JLkiixhgi6hVLV11hERWdn/p0XcPU2OUcZzac9BPOFq7SbaHFa8r3SWEysCQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.5.tgz", + "integrity": "sha512-lHVQHJFKsuuxLMi3MQO9XVL8Tje3JR82CzB+QDKC5NWBcsIWuwsn9uIM5e3lBhI+fF1/s63qnyYqsg65+8rV/w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.5.tgz", + "integrity": "sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.5.tgz", + "integrity": "sha512-VDC7rRJlee/scpki96GZ27Omf6yU87s1YXwVTpjE5841faVlDYYT565rgfmoR1U0sqL7z5ivQSDjcsF6VRXyBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.5.tgz", + "integrity": "sha512-z86Ok2p4pTdv5xqCKZsTooO7yBEiaJR/HzU3Wx8RmWsPoLppnMKROhJusQob8B3IE1ghC343kUW9rC2r+Wf3ig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.5.tgz", + "integrity": "sha512-IzQmj+xXwQFGhMAMKMQVXkMwMZN3TqkJgAE0nSsqvVwWWciP4AIPMmWRqOQ2GfX7TUDZr+xqGFcBS36CRPGw0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.5.tgz", + "integrity": "sha512-F6qpTaPc9bwBH85kjy0/BLmLSW1uv7AoOXCoRIkg2arlgCYlWYcAbiMkvZuAcaWk9TpCRG//okznLAqLGshkMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.5.tgz", + "integrity": "sha512-igoDsTFhhwECBeGbUuLeIk7t8Y1apa+cs6mDWpx2EZ0ch7oEQgzHbFUXN9euoHekCAQzXdXApAGkV6jznS7tWw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.5.tgz", + "integrity": "sha512-U3teMeMbXFmaM5D+OTJpsOXd+wV/qftIeYF9kBKL4v73641qyJmoXFtA28DQLsnmlyayEsTe72xpLHrArq6vHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.5.tgz", + "integrity": "sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tanstack/charts": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@tanstack/charts/-/charts-1.0.0.tgz", + "integrity": "sha512-4U+zbn5jzQF8MNDsvjMG7TE4Fv68mfIIiFlFmrWiBIHor8zCX+7W8gpyDcT1SYJYvOIZXv3uxbK/IjwGY40Sig==", + "license": "MIT", + "dependencies": { + "@types/d3-force": "^3.0.10", + "@types/d3-geo": "^3.1.0", + "@types/d3-hierarchy": "^3.1.7", + "@types/d3-sankey": "^0.12.5", + "@types/d3-shape": "^3.1.8", + "d3-array": "3.2.4", + "d3-brush": "3.0.0", + "d3-contour": "4.0.2", + "d3-delaunay": "6.0.4", + "d3-force": "3.0.0", + "d3-geo": "3.1.1", + "d3-hexbin": "0.2.2", + "d3-hierarchy": "3.1.2", + "d3-sankey": "0.12.3", + "d3-scale": "4.0.2", + "d3-selection": "3.0.0", + "d3-shape": "3.2.0", + "d3-zoom": "3.0.0", + "tslib": "^2.8.1" + }, + "peerDependencies": { + "@angular/core": ">=19", + "@angular/platform-browser": ">=19", + "alpinejs": ">=3.15", + "lit": ">=3.1.3", + "octane": "^0.1.13", + "preact": ">=10", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0", + "react-native": "^0.86.0", + "react-native-svg": ">=15.15.4 <16", + "solid-js": ">=1.8", + "svelte": "^5.20.0", + "vue": ">=3.5" + }, + "peerDependenciesMeta": { + "@angular/core": { + "optional": true + }, + "@angular/platform-browser": { + "optional": true + }, + "alpinejs": { + "optional": true + }, + "lit": { + "optional": true + }, + "octane": { + "optional": true + }, + "preact": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + }, + "react-native-svg": { + "optional": true + }, + "solid-js": { + "optional": true + }, + "svelte": { + "optional": true + }, + "vue": { + "optional": true + } + } + }, + "node_modules/@tanstack/query-core": { + "version": "5.104.0", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.104.0.tgz", + "integrity": "sha512-JrC2r/JQlXt7khBSdUpsgxNvybzOg+aITa+ARRMlP2AFo93Y8vIqz077rp+e61mJetSZ0T6AJbwW1JHer1vrPQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.104.0", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.104.0.tgz", + "integrity": "sha512-e1TZmDCQnWIfiDVryIHeA6Idj+Lfx1hORLOhXS/l5wcgvtVD4yYqbTDl378sGQKIi2cSgb0TEMC9cKK8GGoJEw==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.104.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@tanstack/react-table": { + "version": "9.2.4", + "resolved": "https://registry.npmjs.org/@tanstack/react-table/-/react-table-9.2.4.tgz", + "integrity": "sha512-Rzp1Q4e0/nIgEjmISYR5HeEgLTNtrG+C7NFZf/AbCxPO5hg+zC3yNGwcoECigUk8SFzzvhXbd2rFdtP2ZiGrfA==", + "license": "MIT", + "dependencies": { + "@tanstack/react-store": "^0.11.1", + "@tanstack/table-core": "9.2.4" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=18" + } + }, + "node_modules/@tanstack/react-table/node_modules/@tanstack/react-store": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.11.2.tgz", + "integrity": "sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ==", + "license": "MIT", + "dependencies": { + "@tanstack/store": "0.11.2", + "use-sync-external-store": "^1.6.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/@tanstack/store": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.11.2.tgz", + "integrity": "sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/table-core": { + "version": "9.2.4", + "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-9.2.4.tgz", + "integrity": "sha512-GwdDyGGr6UXAtubF14yAwcXvdaogqfsQgIk89Suebjxob/Rjq2xvfmXsjDF1rQmKmhHsJm9TOY7myxv3i6geJw==", + "license": "MIT", + "dependencies": { + "@tanstack/store": "^0.11.1" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/d3-force": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz", + "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==", + "license": "MIT" + }, + "node_modules/@types/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==", + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-hierarchy": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz", + "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==", + "license": "MIT" + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-sankey": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/d3-sankey/-/d3-sankey-0.12.5.tgz", + "integrity": "sha512-/3RZSew0cLAtzGQ+C89hq/Rp3H20QJuVRSqFy6RKLe7E0B8kd2iOS1oBsodrgds4PcNVpqWhdUEng/SHvBcJ6Q==", + "license": "MIT", + "dependencies": { + "@types/d3-shape": "^1" + } + }, + "node_modules/@types/d3-sankey/node_modules/@types/d3-path": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.11.tgz", + "integrity": "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw==", + "license": "MIT" + }, + "node_modules/@types/d3-sankey/node_modules/@types/d3-shape": { + "version": "1.3.12", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.12.tgz", + "integrity": "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "^1" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.26", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.26.tgz", + "integrity": "sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.1.tgz", + "integrity": "sha512-AUdjuRyCNGUYtqpqfTmWyM4fXay8yIQhmLnvYe/THMGfT9B/34X7xQd3ifKxwyNPPpowVBjLb+64BN9Rn1mizw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.25", + "caniuse-lite": "^1.0.30001810", + "electron-to-chromium": "^1.5.438", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001812", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001812.tgz", + "integrity": "sha512-qN+QNNBr93TCmFrmte0bBCjSDMuRvt78VlHT99qIGPszm4QsqCX8lnyWUFkHi8B7ZBAPq8SH+UqyXNy/odMdng==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chess.js": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/chess.js/-/chess.js-1.4.0.tgz", + "integrity": "sha512-BBJgrrtKQOzFLonR0l+k64A98NLemPwNsCskwb+29bRwobUa4iTm51E1kwGPbWXAcfdDa18nad6vpPPKPWarqw==", + "license": "BSD-2-Clause" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-brush": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz", + "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "3", + "d3-transition": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-contour": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz", + "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==", + "license": "ISC", + "dependencies": { + "d3-array": "^3.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-delaunay": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz", + "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==", + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dispatch": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", + "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-drag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", + "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-selection": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-force": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz", + "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-quadtree": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-hexbin": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/d3-hexbin/-/d3-hexbin-0.2.2.tgz", + "integrity": "sha512-KS3fUT2ReD4RlGCjvCEm1RgMtp2NFZumdMu4DBzQK8AZv3fXRM6Xm8I4fSU07UXvH4xxg03NwWKWdvxfS/yc4w==", + "license": "BSD-3-Clause" + }, + "node_modules/d3-hierarchy": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz", + "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-quadtree": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz", + "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-sankey": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz", + "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-array": "1 - 2", + "d3-shape": "^1.2.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-array": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz", + "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==", + "license": "BSD-3-Clause", + "dependencies": { + "internmap": "^1.0.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-path": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz", + "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==", + "license": "BSD-3-Clause" + }, + "node_modules/d3-sankey/node_modules/d3-shape": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz", + "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-path": "1" + } + }, + "node_modules/d3-sankey/node_modules/internmap": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz", + "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==", + "license": "ISC" + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-selection": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", + "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-transition": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", + "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-dispatch": "1 - 3", + "d3-ease": "1 - 3", + "d3-interpolate": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "d3-selection": "2 - 3" + } + }, + "node_modules/d3-zoom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", + "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "2 - 3", + "d3-transition": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delaunator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", + "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.439", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.439.tgz", + "integrity": "sha512-qu6QIPXhsb+CRcAiTMNjR4A1y/7tCYKkKjr5CZXRVih6qkDf79peZ2BpEU3qoDBNCRrcy3Mra3X9nG5oruuA7Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/framer-motion": { + "version": "13.5.1", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-13.5.1.tgz", + "integrity": "sha512-HeWOaeHD3kyTSIEMT6+nw7fBn4saIfxxabZyAITbycAl4xr1kzGJKIvGt/OWghSlvIA9qTnZ1zTGelHAe6S8DA==", + "license": "MIT", + "dependencies": { + "motion-dom": "13.5.1", + "motion-utils": "13.5.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/motion": { + "version": "13.4.4", + "resolved": "https://registry.npmjs.org/motion/-/motion-13.4.4.tgz", + "integrity": "sha512-lyX5kpAum2MmigecKWrFdIj3Sjn7pHek2EUrXY0WGZbOjJ1f5NfX0g4KQAb2Bp2EqL0a6dUzse11s1n7OYr5jg==", + "license": "MIT", + "dependencies": { + "framer-motion": "^13.4.4", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/motion-dom": { + "version": "13.5.1", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-13.5.1.tgz", + "integrity": "sha512-/7CVCD20Mz1KobktorpdgvowV0V41J7UxqE+qWS3GkSJqrRr5ft+2RloOYtEKv+wvBp3JaSFBclhxt4ja8ovHg==", + "license": "MIT", + "dependencies": { + "motion-utils": "13.5.0" + } + }, + "node_modules/motion-utils": { + "version": "13.5.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-13.5.0.tgz", + "integrity": "sha512-Hqe/sqjIKliPZg8sVjWAkdySDPJNIeKH+euVkDOG8ri3DUUU7ZjndmHsGqEPz2iHpiyVaV5I22iguCMHU2he+Q==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.57", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz", + "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/robust-predicates": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", + "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", + "license": "Unlicense" + }, + "node_modules/rollup": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.5.tgz", + "integrity": "sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.5", + "@rollup/rollup-android-arm64": "4.63.5", + "@rollup/rollup-darwin-arm64": "4.63.5", + "@rollup/rollup-darwin-x64": "4.63.5", + "@rollup/rollup-freebsd-arm64": "4.63.5", + "@rollup/rollup-freebsd-x64": "4.63.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.5", + "@rollup/rollup-linux-arm-musleabihf": "4.63.5", + "@rollup/rollup-linux-arm64-gnu": "4.63.5", + "@rollup/rollup-linux-arm64-musl": "4.63.5", + "@rollup/rollup-linux-loong64-gnu": "4.63.5", + "@rollup/rollup-linux-loong64-musl": "4.63.5", + "@rollup/rollup-linux-ppc64-gnu": "4.63.5", + "@rollup/rollup-linux-ppc64-musl": "4.63.5", + "@rollup/rollup-linux-riscv64-gnu": "4.63.5", + "@rollup/rollup-linux-riscv64-musl": "4.63.5", + "@rollup/rollup-linux-s390x-gnu": "4.63.5", + "@rollup/rollup-linux-x64-gnu": "4.63.5", + "@rollup/rollup-linux-x64-musl": "4.63.5", + "@rollup/rollup-openbsd-x64": "4.63.5", + "@rollup/rollup-openharmony-arm64": "4.63.5", + "@rollup/rollup-win32-arm64-msvc": "4.63.5", + "@rollup/rollup-win32-ia32-msvc": "4.63.5", + "@rollup/rollup-win32-x64-gnu": "4.63.5", + "@rollup/rollup-win32-x64-msvc": "4.63.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "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==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", + "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/chess-game/app/webapp/package.json b/chess-game/app/webapp/package.json new file mode 100644 index 0000000..5bd50c5 --- /dev/null +++ b/chess-game/app/webapp/package.json @@ -0,0 +1,26 @@ +{ + "name": "chess-game-web", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "@fontsource/dosis": "5.3.0", + "@fontsource/dynapuff": "5.3.0", + "@tanstack/charts": "1.0.0", + "@tanstack/react-query": "5.104.0", + "@tanstack/react-table": "9.2.4", + "chess.js": "^1.4.0", + "motion": "13.4.4", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", + "vite": "^5.4.11" + } +} diff --git a/chess-game/app/webapp/public/favicon.svg b/chess-game/app/webapp/public/favicon.svg new file mode 100644 index 0000000..c21b91b --- /dev/null +++ b/chess-game/app/webapp/public/favicon.svg @@ -0,0 +1,6 @@ + + + + ♞ + diff --git a/chess-game/app/webapp/public/index.html b/chess-game/app/webapp/public/index.html deleted file mode 100644 index 7f96d26..0000000 --- a/chess-game/app/webapp/public/index.html +++ /dev/null @@ -1,291 +0,0 @@ - - - - - - Chess Playground - - - - - - - - - - -
- -
- - - White turn - - • - Ongoing -
- - -
-
- ♔ - --:-- -
-
- ♚ - --:-- -
-
- - -
-
-
- - -
-
- - -
- -
-
- You - 0 -
-
- AI - 0 -
-
- ♔ - 0 -
-
- ♚ - 0 -
-
- -
- - - -
-
-
- - - - - - - - - - - - - - - - - -
-
-
-
- Selection - Pick a piece -
-
- Log -
-
Waiting for server…
-
-
- Your Score - White - 0 -
-
- Opponent - Black - 0 -
-
-
-
- - -
- - -
- - - - diff --git a/chess-game/app/webapp/public/static/app.js b/chess-game/app/webapp/public/static/app.js deleted file mode 100644 index 2c8b9e1..0000000 --- a/chess-game/app/webapp/public/static/app.js +++ /dev/null @@ -1,1416 +0,0 @@ -// ===== DOM References ===== -const boardEl = document.getElementById('board'); -const turnEl = document.getElementById('turn'); -const statusEl = document.getElementById('status'); -const selectionEl = document.getElementById('selection'); -const logEl = document.getElementById('log'); -const playerScoreEl = document.getElementById('playerScore'); -const opponentScoreEl = document.getElementById('opponentScore'); -const resetBtn = document.getElementById('reset'); -const refreshBtn = document.getElementById('refresh'); -const toastContainer = document.getElementById('toastContainer'); - -// Inline scores -const playerScoreInline = document.getElementById('playerScoreInline'); -const opponentScoreInline = document.getElementById('opponentScoreInline'); -const playerScoreInlineMulti = document.getElementById('playerScoreInlineMulti'); -const opponentScoreInlineMulti = document.getElementById('opponentScoreInlineMulti'); - -// Mode tabs -const singlePlayerBtn = document.getElementById('singlePlayerBtn'); -const multiplayerBtn = document.getElementById('multiplayerBtn'); - -// Online panel elements -const onlinePanel = document.getElementById('onlinePanel'); -const closeOnlinePanel = document.getElementById('closeOnlinePanel'); -const lobbyOptions = document.getElementById('lobbyOptions'); -const roomInfo = document.getElementById('roomInfo'); -const createRoomBtn = document.getElementById('createRoomBtn'); -const joinRoomBtn = document.getElementById('joinRoomBtn'); -const roomCodeInput = document.getElementById('roomCodeInput'); -const roomCodeDisplay = document.getElementById('roomCodeDisplay'); -const playerColorDisplay = document.getElementById('playerColorDisplay'); -const leaveRoomBtn = document.getElementById('leaveRoom'); -const mpStatusPill = document.getElementById('mpStatusPill'); - -// Chat panel elements -const chatPanel = document.getElementById('chatPanel'); -const closeChatPanel = document.getElementById('closeChatPanel'); -const chatMessages = document.getElementById('chatMessages'); -const chatInput = document.getElementById('chatInput'); -const chatSendBtn = document.getElementById('chatSendBtn'); -const chatBadge = document.getElementById('chatBadge'); -const chatToggleBtn = document.getElementById('chatToggleBtn'); - -// Move history panel elements -const moveHistoryPanel = document.getElementById('moveHistoryPanel'); -const closeMoveHistoryPanel = document.getElementById('closeMoveHistoryPanel'); -const moveHistoryContainer = document.getElementById('moveHistoryContainer'); -const moveHistoryToggleBtn = document.getElementById('moveHistoryToggleBtn'); - -// Info popover -const infoToggle = document.getElementById('infoToggle'); -const infoPopover = document.getElementById('infoPopover'); - -// Time control elements -const timeControlBar = document.getElementById('timeControlBar'); -const whiteTimerEl = document.getElementById('whiteTimer'); -const blackTimerEl = document.getElementById('blackTimer'); -const whiteTimeEl = document.getElementById('whiteTime'); -const blackTimeEl = document.getElementById('blackTime'); - -// Time control modal elements -const timeControlModal = document.getElementById('timeControlModal'); -const closeTimeControlModal = document.getElementById('closeTimeControlModal'); -const timeControlOptions = document.querySelectorAll('.time-control-option'); -const startWithTimeControl = document.getElementById('startWithTimeControl'); -const onlineTimeControl = document.getElementById('onlineTimeControl'); - -// Backdrop -const backdrop = document.getElementById('backdrop'); - -// Game End Modal elements -const gameEndModal = document.getElementById('gameEndModal'); -const gameEndTitle = document.getElementById('gameEndTitle'); -const gameEndIcon = document.getElementById('gameEndIcon'); -const gameEndMessage = document.getElementById('gameEndMessage'); -const finalWhiteScore = document.getElementById('finalWhiteScore'); -const finalBlackScore = document.getElementById('finalBlackScore'); -const playAgainBtn = document.getElementById('playAgainBtn'); -const closeGameEndModal = document.getElementById('closeGameEndModal'); - -// ===== Piece Map ===== -const pieceMap = { - r: '♜︎', n: '♞︎', b: '♝︎', q: '♛︎', k: '♚︎', p: '♟︎', - R: '♖︎', N: '♘︎', B: '♗︎', Q: '♕︎', K: '♔︎', P: '♙︎', - '.': '' -}; - -// ===== State ===== -let selection = null; -let cachedBoard = []; -let opponentRefresh = null; -let lastMove = null; -let hasInitializedState = false; -let activeValidMoves = []; -let validMoveTimer = null; - -let gameMode = 'single'; -let roomCode = null; -let playerId = null; -let playerColor = null; -let isInRoom = false; - -let lastChatTimestamp = 0; -let chatPollInterval = null; -let unreadChatCount = 0; - -// Single player session ID (for browser isolation) -let singlePlayerSessionId = null; - -// Time control state -let timeControl = null; -let clockInterval = null; -let currentTurn = 'White'; -let previousTurn = null; // Track previous turn to detect turn changes -let selectedTimeControlMs = 600000; // Default: 10 min (Rapid) -let selectedIncrementMs = 0; - -// Move history state -let moveHistory = []; - -// ===== Utility Functions ===== -function pushToast(message, variant = 'accent') { - if (!toastContainer) return; - const toast = document.createElement('div'); - toast.className = `toast ${variant}`; - toast.textContent = message; - toastContainer.appendChild(toast); - requestAnimationFrame(() => toast.classList.add('show')); - setTimeout(() => { - toast.classList.remove('show'); - setTimeout(() => toast.remove(), 300); - }, 4000); -} - -function algebraic(row, col) { - const file = String.fromCodePoint('a'.codePointAt(0) + col); - const rank = 8 - row; - return `${file}${rank}`; -} - -function setMessage(text) { - if (logEl) logEl.textContent = text; -} - -function saveSession() { - if (gameMode === 'multi' && roomCode && playerId) { - localStorage.setItem('chess_session', JSON.stringify({ roomCode, playerId, playerColor })); - } else { - localStorage.removeItem('chess_session'); - } -} - -function generateSessionId() { - return 'sp_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); -} - -function getSinglePlayerSessionId() { - if (!singlePlayerSessionId) { - // Try to get from sessionStorage (browser tab specific) - singlePlayerSessionId = sessionStorage.getItem('chess_single_player_id'); - if (!singlePlayerSessionId) { - singlePlayerSessionId = generateSessionId(); - sessionStorage.setItem('chess_single_player_id', singlePlayerSessionId); - } - } - return singlePlayerSessionId; -} - -function isIOSSafari() { - const ua = navigator.userAgent; - const isIOSDevice = /iPad|iPhone|iPod/.test(ua) - || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1); - const isSafariEngine = /WebKit/.test(ua) && /Safari/.test(ua); - const isKnownNonSafari = /CriOS|FxiOS|EdgiOS|OPiOS|YaBrowser/.test(ua); - return isIOSDevice && isSafariEngine && !isKnownNonSafari; -} - -function applyIOSSafariSymbolFallback() { - if (isIOSSafari()) { - document.documentElement.classList.add('ios-safari'); - } -} - -function loadSession() { - try { - const session = JSON.parse(localStorage.getItem('chess_session')); - if (session?.roomCode && session?.playerId) { - return session; - } - } catch { - localStorage.removeItem('chess_session'); - } - return null; -} - -// ===== Valid Moves Management ===== -function clearActiveValidMoves(skipRender = false) { - if (validMoveTimer) { - clearTimeout(validMoveTimer); - validMoveTimer = null; - } - activeValidMoves = []; - if (!skipRender && cachedBoard.length) { - renderBoard(cachedBoard, false); - } -} - -function setActiveValidMoves(moves) { - clearActiveValidMoves(true); - if (moves?.length) { - activeValidMoves = moves; - validMoveTimer = setTimeout(() => clearActiveValidMoves(), 4500); - } - if (cachedBoard.length) { - renderBoard(cachedBoard, false); - } -} - -// ===== Board Rendering ===== -function renderBoard(boardRows, disabled = false, highlightMoves = activeValidMoves) { - cachedBoard = boardRows; - boardEl.innerHTML = ''; - boardEl.classList.toggle('disabled', disabled); - - let lastMoveFrom = null; - let lastMoveTo = null; - if (lastMove?.length >= 4) { - lastMoveFrom = lastMove.substring(0, 2); - lastMoveTo = lastMove.substring(2, 4); - } - - boardRows.forEach((rowString, rowIdx) => { - [...rowString].forEach((ch, colIdx) => { - const btn = document.createElement('button'); - const square = algebraic(rowIdx, colIdx); - btn.className = `square ${(rowIdx + colIdx) % 2 === 0 ? 'dark' : 'light'}`; - btn.dataset.square = square; - btn.textContent = pieceMap[ch] ?? ''; - - if (selection === square) btn.classList.add('selected'); - if (lastMoveFrom === square) btn.classList.add('last-move-from'); - if (lastMoveTo === square) btn.classList.add('last-move-to'); - - if (highlightMoves?.includes(square)) { - btn.classList.add(ch === '.' ? 'valid-move' : 'valid-capture'); - } - - if (!disabled) { - btn.addEventListener('click', () => handleSquareClick(square)); - } - - boardEl.appendChild(btn); - }); - }); -} - -// ===== Click Handling ===== -async function handleSquareClick(square) { - if (!selection) { - selection = square; - if (selectionEl) selectionEl.textContent = `From ${square}`; - clearActiveValidMoves(true); - await loadValidMoves(square); - return; - } - - if (selection === square) { - selection = null; - if (selectionEl) selectionEl.textContent = 'Pick a piece'; - clearActiveValidMoves(); - renderBoard(cachedBoard, false); - return; - } - - const from = selection; - const to = square; - selection = null; - if (selectionEl) selectionEl.textContent = 'Sending move…'; - clearActiveValidMoves(true); - - if (gameMode === 'multi' && isInRoom) { - sendOnlineMove(from, to); - } else { - sendMove(from, to); - } -} - -// ===== API Calls ===== -async function sendMove(from, to) { - try { - const sessionId = getSinglePlayerSessionId(); - const res = await fetch(`/api/move/${sessionId}/${from}/${to}`, { method: 'POST' }); - const payload = await res.json(); - applyState(payload); - if (selectionEl) selectionEl.textContent = 'Pick a piece'; - } catch (err) { - setMessage('Move failed: ' + err.message); - } -} - -async function loadState() { - setMessage('Syncing with server…'); - try { - const sessionId = getSinglePlayerSessionId(); - const res = await fetch(`/api/state/${sessionId}`); - const payload = await res.json(); - applyState(payload); - } catch (err) { - console.error('Failed to load state:', err); - setMessage('Could not reach the chess server.'); - } -} - -async function resetGame() { - setMessage('Resetting…'); - resetGameEndState(); // Reset game end modal state - try { - if (gameMode === 'multi' && isInRoom) { - await resetOnlineGame(); - } else { - const sessionId = getSinglePlayerSessionId(); - const res = await fetch(`/api/reset/${sessionId}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - timeControlMs: selectedTimeControlMs, - incrementMs: selectedIncrementMs - }) - }); - const payload = await res.json(); - lastMove = null; - clearMoveHistory(); - applyState(payload); - } - } catch (err) { - setMessage('Reset failed: ' + err.message); - } -} - -async function loadValidMoves(square) { - try { - let url; - if (gameMode === 'multi' && isInRoom && roomCode && playerId) { - url = `/api/online/validmoves/${roomCode}/${playerId}/${square}`; - } else { - const sessionId = getSinglePlayerSessionId(); - url = `/api/validmoves/${sessionId}/${square}`; - } - const res = await fetch(url); - const data = await res.json(); - if (data.success && data.validMoves) { - setActiveValidMoves(data.validMoves); - } else { - clearActiveValidMoves(); - } - } catch (err) { - console.error('Failed to load valid moves:', err); - clearActiveValidMoves(); - } -} - -// ===== State Application ===== -function syncScores(state) { - const playerScore = state.playerScore ?? 0; - const opponentScore = state.opponentScore ?? 0; - if (playerScoreEl) playerScoreEl.textContent = playerScore; - if (opponentScoreEl) opponentScoreEl.textContent = opponentScore; - if (playerScoreInline) playerScoreInline.textContent = playerScore; - if (opponentScoreInline) opponentScoreInline.textContent = opponentScore; - if (playerScoreInlineMulti) playerScoreInlineMulti.textContent = playerScore; - if (opponentScoreInlineMulti) opponentScoreInlineMulti.textContent = opponentScore; -} - -// ===== Time Control Functions ===== -function formatTime(ms) { - if (ms == null || ms < 0) return '--:--'; - const totalSeconds = Math.floor(ms / 1000); - const hours = Math.floor(totalSeconds / 3600); - const minutes = Math.floor((totalSeconds % 3600) / 60); - const seconds = totalSeconds % 60; - - // Show h:mm:ss when >= 1 hour - if (hours > 0) { - return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; - } - - // Show m:ss.t (tenths) when < 10 seconds for urgency - if (totalSeconds < 10) { - const tenths = Math.floor((ms % 1000) / 100); - return `${minutes}:${seconds.toString().padStart(2, '0')}.${tenths}`; - } - - return `${minutes}:${seconds.toString().padStart(2, '0')}`; -} - -function updateTimeControl(tc, turn, gameStatus = 'Ongoing', hasMoves = false) { - if (!tc || (tc.whiteTimeMs === 0 && tc.blackTimeMs === 0)) { - hideTimeControl(); - return; - } - - const turnChanged = previousTurn !== null && previousTurn !== turn; - previousTurn = turn; - currentTurn = turn; - - // Show time control bar - if (timeControlBar) timeControlBar.classList.add('visible'); - - // Always update times from server (server is authoritative) - timeControl = tc; - if (whiteTimeEl) whiteTimeEl.textContent = formatTime(tc.whiteTimeMs); - if (blackTimeEl) blackTimeEl.textContent = formatTime(tc.blackTimeMs); - - // Only run clock if game is ongoing AND at least one move has been made - const shouldRunClock = gameStatus === 'Ongoing' && hasMoves; - - if (shouldRunClock && (turnChanged || !clockInterval)) { - startClock(); - } else if (!shouldRunClock) { - stopClock(); - } - - // Update active state (always update visual indicators) - if (whiteTimerEl) { - whiteTimerEl.classList.toggle('active', turn === 'White' && shouldRunClock); - whiteTimerEl.classList.toggle('low-time', timeControl.whiteTimeMs > 0 && timeControl.whiteTimeMs < 30000); - } - if (blackTimerEl) { - blackTimerEl.classList.toggle('active', turn === 'Black' && shouldRunClock); - blackTimerEl.classList.toggle('low-time', timeControl.blackTimeMs > 0 && timeControl.blackTimeMs < 30000); - } -} - -function hideTimeControl() { - if (timeControlBar) timeControlBar.classList.remove('visible'); - stopClock(); - timeControl = null; - previousTurn = null; // Reset turn tracking when hiding -} - -// ===== Game End Modal ===== -let gameEndShown = false; - -/** - * Determine game result display properties based on status and winner. - */ -function determineGameResult(status, message, isOnline, myColor) { - const isWhiteWinner = message?.includes('White wins') ?? false; - const isBlackWinner = message?.includes('Black wins') ?? false; - - // Draw statuses - const drawStatuses = { - 'Stalemate': { icon: '🤝', title: 'Stalemate' }, - 'FiftyMoveRule': { icon: '🤝', title: 'Draw — 50-Move Rule' }, - 'InsufficientMaterial': { icon: '🤝', title: 'Draw — Insufficient Material' }, - 'ThreefoldRepetition': { icon: '🔄', title: 'Draw — Threefold Repetition' }, - }; - - if (drawStatuses[status]) { - return { resultType: 'draw', ...drawStatuses[status] }; - } - - // Timeout — someone lost on time (not a draw) - if (status === 'Timeout') { - const didIWin = isOnline && myColor - ? (myColor === 'White' && isBlackWinner) || (myColor === 'Black' && isWhiteWinner) - ? false - : (myColor === 'White' && isWhiteWinner) || (myColor === 'Black' && isBlackWinner) - : !message?.includes('Black wins'); - - if (didIWin) { - return { resultType: 'win', icon: '⏱️', title: isOnline ? 'Victory on Time!' : 'You Win on Time!' }; - } - return { resultType: 'loss', icon: '⏱️', title: isOnline ? 'Lost on Time' : 'You Lost on Time' }; - } - - if (status !== 'Checkmate') { - return { resultType: 'draw', icon: '🤝', title: 'Game Over' }; - } - - // Checkmate — determine winner - const didIWin = isOnline && myColor - ? (myColor === 'White' && isWhiteWinner) || (myColor === 'Black' && isBlackWinner) - : isWhiteWinner; - - if (didIWin) { - return { resultType: 'win', icon: '🏆', title: isOnline ? 'Checkmate! Victory!' : 'Checkmate! You Win!' }; - } - - if (isWhiteWinner || isBlackWinner) { - return { resultType: 'loss', icon: '😔', title: isOnline ? 'Checkmate — Defeat' : 'Checkmate — You Lost' }; - } - - return { resultType: 'draw', icon: '🤝', title: 'Game Over' }; -} - -function showGameEndModal(status, message, whiteScore, blackScore, isOnline = false, myColor = null) { - if (gameEndShown || !gameEndModal) return; - gameEndShown = true; - - const { resultType, icon, title } = determineGameResult(status, message, isOnline, myColor); - - // Update modal content - if (gameEndTitle) gameEndTitle.textContent = title; - if (gameEndIcon) gameEndIcon.textContent = icon; - if (gameEndMessage) gameEndMessage.textContent = message || status; - if (finalWhiteScore) finalWhiteScore.textContent = whiteScore; - if (finalBlackScore) finalBlackScore.textContent = blackScore; - - // Update modal class - gameEndModal.className = 'modal-overlay'; - const modalContent = gameEndModal.querySelector('.modal-content'); - if (modalContent) { - modalContent.className = `modal-content game-end-modal result-${resultType}`; - } - - // Show modal - gameEndModal.classList.remove('hidden'); -} - -function hideGameEndModal() { - if (gameEndModal) gameEndModal.classList.add('hidden'); - gameEndShown = false; -} - -function resetGameEndState() { - gameEndShown = false; -} - -function startClock() { - stopClock(); - if (!timeControl) return; - - let lastUpdateTime = Date.now(); - - clockInterval = setInterval(() => { - if (!timeControl) { - stopClock(); - return; - } - - const now = Date.now(); - const deltaMs = now - lastUpdateTime; - lastUpdateTime = now; - - // Update display only (don't modify the stored timeControl object) - // The server will send authoritative time updates - if (currentTurn === 'White') { - const newWhiteTime = Math.max(0, timeControl.whiteTimeMs - deltaMs); - if (whiteTimeEl) whiteTimeEl.textContent = formatTime(newWhiteTime); - if (whiteTimerEl) whiteTimerEl.classList.toggle('low-time', newWhiteTime > 0 && newWhiteTime < 30000); - - // Stop local countdown if time runs out (server will handle the actual timeout) - if (newWhiteTime <= 0) stopClock(); - } else { - const newBlackTime = Math.max(0, timeControl.blackTimeMs - deltaMs); - if (blackTimeEl) blackTimeEl.textContent = formatTime(newBlackTime); - if (blackTimerEl) blackTimerEl.classList.toggle('low-time', newBlackTime > 0 && newBlackTime < 30000); - - // Stop local countdown if time runs out (server will handle the actual timeout) - if (newBlackTime <= 0) stopClock(); - } - }, 100); // Update every 100ms for smoother countdown -} - -function stopClock() { - if (clockInterval) { - clearInterval(clockInterval); - clockInterval = null; - } -} - -function announceMove(move, previousMove) { - if (!move || move === previousMove || !hasInitializedState) return; - pushToast(`Move: ${move}`, 'accent'); -} - -function applyState(state) { - if (!state?.board) { - setMessage('Unexpected response from server.'); - return; - } - - if (opponentRefresh !== null) { - clearTimeout(opponentRefresh); - opponentRefresh = null; - } - - const previousMove = lastMove; - if (state.lastMove) lastMove = state.lastMove; - currentTurn = state.turn || 'White'; - - renderBoard(state.board, false); - if (turnEl) turnEl.textContent = state.turn ?? '—'; - if (statusEl) statusEl.textContent = state.status ?? '—'; - if (selectionEl) selectionEl.textContent = 'Pick a piece'; - syncScores(state); - - // Update time control display - if (state.timeControl) { - const hasMoves = state.moveHistory && state.moveHistory.length > 0; - updateTimeControl(state.timeControl, state.turn, state.status, hasMoves); - } else { - hideTimeControl(); - } - - // Update move history display - if (state.moveHistory) { - moveHistory = state.moveHistory; - renderMoveHistory(); - } - - const move = state.lastMove ? `Last move: ${state.lastMove}` : 'Ready'; - setMessage(`${state.message || 'Synced.'}\n${move}`); - - if (state.opponentPending) { - opponentRefresh = setTimeout(loadState, 3000); - } - - announceMove(state.lastMove, previousMove); - hasInitializedState = true; - - // Show game end modal if game is over - if (state.status !== 'Ongoing') { - stopClock(); - showGameEndModal( - state.status, - state.message, - state.playerScore || 0, - state.opponentScore || 0, - false, - null - ); - } -} - -// ===== Online Multiplayer ===== -async function createRoom() { - setMessage('Creating room…'); - try { - // Get time control from dropdown - let tcMs = 600000, incMs = 0; - if (onlineTimeControl) { - const [time, inc] = onlineTimeControl.value.split('|').map(Number); - tcMs = time; - incMs = inc; - } - - const res = await fetch('/api/online/create', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - timeControlMs: tcMs, - incrementMs: incMs - }) - }); - const data = await res.json(); - - if (data.roomCode && data.playerId) { - roomCode = data.roomCode; - playerId = data.playerId; - playerColor = 'White'; - isInRoom = true; - lastMove = null; - - // Clear previous room's chat messages to ensure proper isolation - clearChat(); - - saveSession(); - showRoomInfo(); - openChatPanel(); - setMessage(data.message || 'Room created!'); - startMultiplayerPolling(); - } else { - setMessage('Failed to create room.'); - } - } catch (err) { - setMessage('Failed to create room: ' + err.message); - } -} - -async function joinRoom(code) { - if (!code || code.length < 4) { - setMessage('Please enter a valid room code.'); - return; - } - - setMessage('Joining room…'); - try { - const res = await fetch(`/api/online/join/${code.toUpperCase()}`, { method: 'POST' }); - const data = await res.json(); - - if (data.playerId && data.roomCode) { - roomCode = data.roomCode; - playerId = data.playerId; - playerColor = data.playerColor || 'Black'; - isInRoom = true; - lastMove = null; - - // Clear previous room's chat messages to ensure proper isolation - clearChat(); - - saveSession(); - showRoomInfo(); - openChatPanel(); - setMessage(data.message || 'Joined!'); - applyOnlineState(data); - startMultiplayerPolling(); - } else if (data.message) { - setMessage(data.message); - } else { - setMessage('Failed to join room.'); - } - } catch (err) { - setMessage('Failed to join room: ' + err.message); - } -} - -async function loadOnlineState() { - if (!roomCode || !playerId) return; - try { - const res = await fetch(`/api/online/state/${roomCode}/${playerId}`); - const state = await res.json(); - applyOnlineState(state); - } catch (err) { - setMessage('Failed to load game state: ' + err.message); - } -} - -async function sendOnlineMove(from, to) { - if (!roomCode || !playerId) return; - try { - const res = await fetch(`/api/online/move/${roomCode}/${playerId}/${from}/${to}`, { method: 'POST' }); - const state = await res.json(); - applyOnlineState(state); - if (selectionEl) selectionEl.textContent = 'Pick a piece'; - } catch (err) { - setMessage('Move failed: ' + err.message); - } -} - -async function resetOnlineGame() { - if (!roomCode || !playerId) return; - resetGameEndState(); // Reset game end modal state - try { - const res = await fetch(`/api/online/reset/${roomCode}/${playerId}`, { method: 'POST' }); - const state = await res.json(); - lastMove = null; - clearMoveHistory(); - applyOnlineState(state); - } catch (err) { - setMessage('Reset failed: ' + err.message); - } -} - -async function leaveRoom() { - if (roomCode && playerId) { - try { - await fetch(`/api/online/leave/${roomCode}/${playerId}`, { method: 'POST' }); - } catch {} - } - exitMultiplayerMode(); - setMessage('Left the room.'); -} - -/** - * Update multiplayer status pill based on game state. - */ -function updateStatusPill(state) { - if (!mpStatusPill) return; - - if (state.waitingForOpponent) { - mpStatusPill.textContent = 'Waiting for opponent...'; - } else if (state.status === 'Ongoing' && state.isYourTurn) { - mpStatusPill.textContent = 'Your turn!'; - } else if (state.status === 'Ongoing') { - mpStatusPill.textContent = "Opponent's turn..."; - } else { - // Game over — show descriptive status - const statusLabels = { - 'Checkmate': '♚ Checkmate', - 'Stalemate': '🤝 Stalemate', - 'FiftyMoveRule': '🤝 Draw — 50-Move Rule', - 'InsufficientMaterial': '🤝 Draw — Insufficient Material', - 'ThreefoldRepetition': '🔄 Draw — Repetition', - 'Timeout': '⏱️ Timeout', - }; - mpStatusPill.textContent = statusLabels[state.status] || state.status; - } -} - -/** - * Update UI elements based on online state. - */ -function updateOnlineUI(state) { - const disabled = !state.isYourTurn && state.status === 'Ongoing'; - if (state.board?.length > 0) { - renderBoard(state.board, disabled); - } - - if (turnEl) turnEl.textContent = state.turn ?? '—'; - if (statusEl) statusEl.textContent = state.status ?? '—'; - if (selectionEl) selectionEl.textContent = state.isYourTurn ? 'Your turn' : 'Waiting…'; - syncScores(state); - - if (state.moveHistory) { - moveHistory = state.moveHistory; - renderMoveHistory(); - } - - if (state.timeControl) { - const hasMoves = state.moveHistory && state.moveHistory.length > 0; - updateTimeControl(state.timeControl, state.turn, state.status, hasMoves); - } else { - hideTimeControl(); - } -} - -function applyOnlineState(state) { - if (!state) { - setMessage('Unexpected response from server.'); - return; - } - - if (opponentRefresh !== null) { - clearTimeout(opponentRefresh); - opponentRefresh = null; - } - - const previousMove = lastMove; - if (state.lastMove) lastMove = state.lastMove; - - updateOnlineUI(state); - - // Handle opponent leaving - if (state.opponentLeft) { - if (mpStatusPill) mpStatusPill.textContent = 'Opponent left'; - pushToast('Your opponent has left the game', 'secondary'); - setMessage('Opponent left the room. You win!'); - return; - } - - updateStatusPill(state); - - const move = state.lastMove ? `Last move: ${state.lastMove}` : ''; - setMessage(`${state.message || 'Synced.'}\n${move}`); - - if (state.status === 'Ongoing') { - opponentRefresh = setTimeout(loadOnlineState, 1000); - } else { - stopClock(); - showGameEndModal( - state.status, - state.message, - state.playerScore || 0, - state.opponentScore || 0, - true, - playerColor - ); - } - - announceMove(state.lastMove, previousMove); - hasInitializedState = true; -} - -function startMultiplayerPolling() { - if (opponentRefresh !== null) { - clearTimeout(opponentRefresh); - } - loadOnlineState(); -} - -// ===== UI State ===== -function showRoomInfo() { - if (lobbyOptions) lobbyOptions.classList.add('hidden'); - if (roomInfo) roomInfo.classList.remove('hidden'); - if (roomCodeDisplay) roomCodeDisplay.textContent = roomCode || '------'; - - if (playerColorDisplay) { - if (playerColor === 'White') { - playerColorDisplay.innerHTML = '♔ White'; - playerColorDisplay.className = 'player-color-badge white'; - } else { - playerColorDisplay.innerHTML = '♚ Black'; - playerColorDisplay.className = 'player-color-badge black'; - } - } -} - -function showLobbyOptions() { - if (lobbyOptions) lobbyOptions.classList.remove('hidden'); - if (roomInfo) roomInfo.classList.add('hidden'); -} - -function setGameMode(mode) { - // If already in the requested mode, do nothing - if (gameMode === mode) { - return; - } - - // Always clear any pending timers first to prevent cross-mode interference - if (opponentRefresh !== null) { - clearTimeout(opponentRefresh); - opponentRefresh = null; - } - stopChatPolling(); - - // Clear selection and valid moves to prevent stale state - selection = null; - activeValidMoves = []; - if (validMoveTimer) { - clearTimeout(validMoveTimer); - validMoveTimer = null; - } - - gameMode = mode; - document.body.classList.remove('mode-single', 'mode-multi'); - document.body.classList.add(mode === 'single' ? 'mode-single' : 'mode-multi'); - - singlePlayerBtn?.classList.toggle('active', mode === 'single'); - multiplayerBtn?.classList.toggle('active', mode === 'multi'); - - if (mode === 'single') { - localStorage.removeItem('chess_session'); - - // Switch to single player mode but keep the online session active - // Only the "Leave Room" button will actually exit the room - lastMove = null; - closeChatPanelFn(); - closeOnlinePanelFn(); - loadState(); - } else { - // When switching to multiplayer mode - lastMove = null; - if (isInRoom) { - // If already in a room, show room info and resume - showRoomInfo(); - openOnlinePanel(); - openChatPanel(); // Restart chat polling when switching back to multiplayer - startMultiplayerPolling(); - loadOnlineState(); - } else { - // Not in a room, show lobby options - showLobbyOptions(); - openOnlinePanel(); - // Render empty board while waiting for room - renderBoard(['rnbqkbnr', 'pppppppp', '........', '........', '........', '........', 'PPPPPPPP', 'RNBQKBNR'], true); - } - } -} - -function exitMultiplayerMode() { - roomCode = null; - playerId = null; - playerColor = null; - isInRoom = false; - lastMove = null; - localStorage.removeItem('chess_session'); - - if (opponentRefresh !== null) { - clearTimeout(opponentRefresh); - opponentRefresh = null; - } - - stopChatPolling(); - clearChat(); - showLobbyOptions(); - renderBoard(['rnbqkbnr', 'pppppppp', '........', '........', '........', '........', 'PPPPPPPP', 'RNBQKBNR'], true); -} - -// ===== Panel Controls ===== -function openOnlinePanel() { - onlinePanel?.classList.add('open'); - // Don't show backdrop in online mode - let panels coexist with board -} - -function closeOnlinePanelFn() { - onlinePanel?.classList.remove('open'); -} - -function openChatPanel() { - chatPanel?.classList.add('open'); - // Don't show backdrop in online mode - let panels coexist with board - resetChatBadge(); - loadChatMessages(); - startChatPolling(); -} - -function closeChatPanelFn() { - chatPanel?.classList.remove('open'); -} - -function openMoveHistoryPanel() { - moveHistoryPanel?.classList.add('open'); -} - -function closeMoveHistoryPanelFn() { - moveHistoryPanel?.classList.remove('open'); -} - -function toggleInfoPopover() { - infoPopover?.classList.toggle('open'); -} - -function closeAllPanels() { - closeOnlinePanelFn(); - closeChatPanelFn(); - closeMoveHistoryPanelFn(); - infoPopover?.classList.remove('open'); - hideTimeControlModal(); -} - -// ===== Time Control Modal ===== -function showTimeControlModal() { - timeControlModal?.classList.remove('hidden'); -} - -function hideTimeControlModal() { - timeControlModal?.classList.add('hidden'); -} - -// ===== Chat ===== -async function sendChatMessage(message) { - if (!roomCode || !playerId || !message?.trim()) return; - - if (chatSendBtn) chatSendBtn.disabled = true; - - try { - const res = await fetch(`/api/chat/send/${roomCode}/${playerId}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message: message.trim() }) - }); - const data = await res.json(); - - if (data.success) { - if (chatInput) chatInput.value = ''; - await loadChatMessages(); - } else { - setMessage('Chat error: ' + (data.error || 'Failed')); - } - } catch { - setMessage('Chat error: Could not send'); - } finally { - if (chatSendBtn) chatSendBtn.disabled = false; - chatInput?.focus(); - } -} - -async function loadChatMessages() { - if (!roomCode || !playerId) return; - try { - // Add cache-busting parameter to prevent stale responses - const timestamp = Date.now(); - const res = await fetch(`/api/chat/history/${roomCode}/${playerId}?limit=100&_=${timestamp}`); - const data = await res.json(); - if (data.success && data.messages) { - displayChatMessages(data.messages); - if (data.messages.length > 0) { - lastChatTimestamp = Math.max(...data.messages.map(m => m.timestamp)); - } - } - } catch (err) { - console.error('Error loading chat:', err); - } -} - -async function pollNewChatMessages() { - if (!roomCode || !playerId) return; - try { - // Add cache-busting parameter to prevent stale responses - const timestamp = Date.now(); - const res = await fetch(`/api/chat/recent/${roomCode}/${playerId}/${lastChatTimestamp || 0}?_=${timestamp}`); - const data = await res.json(); - if (data.success && data.messages?.length > 0) { - appendChatMessages(data.messages, { notify: true }); - lastChatTimestamp = Math.max(...data.messages.map(m => m.timestamp)); - } - } catch (err) { - console.error('Error polling chat:', err); - } -} - -function displayChatMessages(messages) { - if (!chatMessages) return; - chatMessages.innerHTML = ''; - if (!messages?.length) { - chatMessages.innerHTML = '
No messages yet
'; - return; - } - messages.forEach(msg => { - chatMessages.appendChild(createChatMessageElement(msg)); - }); - scrollChatToBottom(); -} - -function appendChatMessages(messages, { notify = false } = {}) { - if (!messages?.length || !chatMessages) return; - - const emptyEl = chatMessages.querySelector('.chat-empty'); - if (emptyEl) emptyEl.remove(); - - messages.forEach(msg => { - chatMessages.appendChild(createChatMessageElement(msg)); - const isOwn = msg.playerId === playerId; - if (notify && !isOwn && !chatPanel?.classList.contains('open')) { - incrementChatBadge(); - pushToast(`Chat from ${msg.playerColor}`, 'secondary'); - } - }); - scrollChatToBottom(); -} - -function createChatMessageElement(msg) { - const div = document.createElement('div'); - const isOwn = msg.playerId === playerId; - div.className = `chat-message ${msg.playerColor.toLowerCase()}${isOwn ? ' own' : ''}`; - - // Timestamp is now always in epoch milliseconds from server - const time = new Date(msg.timestamp); - const timeStr = time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); - - div.innerHTML = ` -
- ${isOwn ? 'You' : msg.playerColor} - ${timeStr} -
-
${escapeHtml(msg.message)}
- `; - return div; -} - -function escapeHtml(text) { - const div = document.createElement('div'); - div.textContent = text; - return div.innerHTML; -} - -function scrollChatToBottom() { - if (chatMessages) chatMessages.scrollTop = chatMessages.scrollHeight; -} - -function clearChat() { - if (chatMessages) chatMessages.innerHTML = '
No messages yet
'; - if (chatInput) chatInput.value = ''; - lastChatTimestamp = 0; - resetChatBadge(); -} - -function incrementChatBadge() { - unreadChatCount++; - if (chatBadge) { - chatBadge.textContent = unreadChatCount; - chatBadge.classList.add('visible'); - } -} - -function resetChatBadge() { - unreadChatCount = 0; - if (chatBadge) { - chatBadge.textContent = '0'; - chatBadge.classList.remove('visible'); - } -} - -function startChatPolling() { - stopChatPolling(); - // Poll immediately, then set up interval - pollNewChatMessages(); - chatPollInterval = setInterval(pollNewChatMessages, 2000); -} - -function stopChatPolling() { - if (chatPollInterval) { - clearInterval(chatPollInterval); - chatPollInterval = null; - } -} - -// ===== Move History ===== -const pieceSymbolMap = { - 'K': '♔', 'Q': '♕', 'R': '♖', 'B': '♗', 'N': '♘', 'P': '♙', - 'k': '♚', 'q': '♛', 'r': '♜', 'b': '♝', 'n': '♞', 'p': '♟' -}; - -/** - * Get maximum move number from a list of moves. - */ -function getMaxMoveNumber(moves) { - if (moves.length === 0) return 0; - return Math.max(...moves.map(m => m.moveNumber)); -} - -/** - * Build move history table HTML. - */ -function buildMoveHistoryTable(whiteMoves, blackMoves, maxMoveNum) { - const rows = []; - for (let i = 1; i <= maxMoveNum; i++) { - const whiteMove = whiteMoves.find(m => m.moveNumber === i); - const blackMove = blackMoves.find(m => m.moveNumber === i); - rows.push(` - ${i}. - ${formatMoveEntry(whiteMove)} - ${formatMoveEntry(blackMove)} - `); - } - return ` - - ${rows.join('')} -
#♔ White♚ Black
`; -} - -function renderMoveHistory() { - if (!moveHistoryContainer) return; - - if (!moveHistory || moveHistory.length === 0) { - moveHistoryContainer.innerHTML = '
No moves yet. Start playing!
'; - return; - } - - const whiteMoves = moveHistory.filter(m => m.color === 'White'); - const blackMoves = moveHistory.filter(m => m.color === 'Black'); - const maxMoveNum = Math.max(getMaxMoveNumber(whiteMoves), getMaxMoveNumber(blackMoves)); - - moveHistoryContainer.innerHTML = buildMoveHistoryTable(whiteMoves, blackMoves, maxMoveNum); - moveHistoryContainer.scrollTop = moveHistoryContainer.scrollHeight; -} - -/** - * Build chess notation from move object. - */ -function buildMoveNotation(move) { - const piece = move.piece?.toUpperCase() || ''; - const pieceSymbol = piece && piece !== 'P' ? piece : ''; - const capture = move.capturedPiece ? 'x' : ''; - const to = move.toSquare || ''; - const promo = move.promotion ? `=${move.promotion.toUpperCase()}` : ''; - let check = ''; - if (move.isCheckmate) check = '#'; - else if (move.isCheck) check = '+'; - return `${pieceSymbol}${capture}${to}${promo}${check}`; -} - -/** - * Get CSS class for move type styling. - */ -function getMoveClassName(move) { - if (move.isCheckmate) return 'checkmate'; - if (move.isCheck) return 'check'; - if (move.capturedPiece) return 'capture'; - if (move.isCastle) return 'castle'; - return ''; -} - -function formatMoveEntry(move) { - if (!move) return '—'; - const notation = move.notation || buildMoveNotation(move); - const className = getMoveClassName(move); - return `${notation}`; -} - -function clearMoveHistory() { - moveHistory = []; - if (moveHistoryContainer) { - moveHistoryContainer.innerHTML = '
No moves yet. Start playing!
'; - } -} - -// ===== Restore Session ===== -function startMultiplayerUI(session) { - gameMode = 'multi'; - document.body.classList.remove('mode-single'); - document.body.classList.add('mode-multi'); - multiplayerBtn?.classList.add('active'); - singlePlayerBtn?.classList.remove('active'); - - if (session) { - roomCode = session.roomCode; - playerId = session.playerId; - playerColor = session.playerColor; - isInRoom = true; - } - - showRoomInfo(); - openChatPanel(); - startMultiplayerPolling(); -} - -// ===== Event Listeners ===== -resetBtn?.addEventListener('click', () => { - if (gameMode === 'single') { - showTimeControlModal(); - } else { - resetGame(); - } -}); -refreshBtn?.addEventListener('click', () => { - if (gameMode === 'multi' && isInRoom) { - loadOnlineState(); - } else { - loadState(); - } -}); - -singlePlayerBtn?.addEventListener('click', () => setGameMode('single')); -multiplayerBtn?.addEventListener('click', () => setGameMode('multi')); - -createRoomBtn?.addEventListener('click', createRoom); -joinRoomBtn?.addEventListener('click', () => joinRoom(roomCodeInput?.value)); -roomCodeInput?.addEventListener('keypress', (e) => { - if (e.key === 'Enter') joinRoom(roomCodeInput.value); -}); -leaveRoomBtn?.addEventListener('click', leaveRoom); - -closeOnlinePanel?.addEventListener('click', closeOnlinePanelFn); -closeChatPanel?.addEventListener('click', closeChatPanelFn); -closeMoveHistoryPanel?.addEventListener('click', closeMoveHistoryPanelFn); -chatToggleBtn?.addEventListener('click', () => { - if (chatPanel?.classList.contains('open')) { - closeChatPanelFn(); - } else { - openChatPanel(); - } -}); -moveHistoryToggleBtn?.addEventListener('click', () => { - if (moveHistoryPanel?.classList.contains('open')) { - closeMoveHistoryPanelFn(); - } else { - openMoveHistoryPanel(); - } -}); - -chatSendBtn?.addEventListener('click', () => { - const msg = chatInput?.value?.trim(); - if (msg) sendChatMessage(msg); -}); -chatInput?.addEventListener('keypress', (e) => { - if (e.key === 'Enter') { - const msg = chatInput.value?.trim(); - if (msg) sendChatMessage(msg); - } -}); - -infoToggle?.addEventListener('click', toggleInfoPopover); - -// Time control modal handlers -closeTimeControlModal?.addEventListener('click', hideTimeControlModal); -startWithTimeControl?.addEventListener('click', () => { - hideTimeControlModal(); - resetGame(); -}); -timeControlOptions?.forEach(option => { - option.addEventListener('click', () => { - // Update selection UI - timeControlOptions.forEach(o => o.classList.remove('selected')); - option.classList.add('selected'); - // Update state - selectedTimeControlMs = Number.parseInt(option.dataset.time) || 0; - selectedIncrementMs = Number.parseInt(option.dataset.increment) || 0; - }); -}); - -backdrop?.addEventListener('click', closeAllPanels); - -// Close modal when clicking outside modal content -timeControlModal?.addEventListener('click', (e) => { - if (e.target === timeControlModal) { - hideTimeControlModal(); - } -}); - -// Game end modal handlers -closeGameEndModal?.addEventListener('click', hideGameEndModal); -playAgainBtn?.addEventListener('click', () => { - hideGameEndModal(); - if (gameMode === 'multi' && isInRoom) { - resetOnlineGame(); - } else { - resetGame(); - } -}); -gameEndModal?.addEventListener('click', (e) => { - if (e.target === gameEndModal) { - hideGameEndModal(); - } -}); - -// Close modal on Escape key -document.addEventListener('keydown', (e) => { - if (e.key === 'Escape') { - hideTimeControlModal(); - hideGameEndModal(); - } -}); - -// Close popover when clicking outside -document.addEventListener('click', (e) => { - if (!infoPopover?.contains(e.target) && !infoToggle?.contains(e.target)) { - infoPopover?.classList.remove('open'); - } -}); - -// ===== Initialize ===== -async function initializeApp() { - const savedSession = loadSession(); - if (savedSession) { - startMultiplayerUI(savedSession); - } else { - await loadState(); - } -} - -applyIOSSafariSymbolFallback(); -initializeApp(); diff --git a/chess-game/app/webapp/public/static/styles.css b/chess-game/app/webapp/public/static/styles.css deleted file mode 100644 index c2a606f..0000000 --- a/chess-game/app/webapp/public/static/styles.css +++ /dev/null @@ -1,1534 +0,0 @@ -/* ===== CSS Variables ===== */ -:root { - --bg: #0a0e17; - --surface: rgba(255, 255, 255, 0.03); - --surface-hover: rgba(255, 255, 255, 0.06); - --border: rgba(255, 255, 255, 0.08); - --border-active: rgba(255, 255, 255, 0.2); - --accent: #e3b341; - --accent-glow: rgba(227, 179, 65, 0.25); - --accent-secondary: #37b2ff; - --accent-secondary-glow: rgba(55, 178, 255, 0.25); - --muted: #6b7a94; - --light: #f0f4f8; - --dark-square: #1a2535; - --light-square: #2a3a50; - --selection: #5eb5f7; - --valid-move: #4ade80; - --capture: #f87171; - --last-move: rgba(227, 179, 65, 0.3); - --danger: #ef4444; - --success: #22c55e; - --radius-sm: 8px; - --radius-md: 12px; - --radius-lg: 18px; - --radius-xl: 24px; -} - -/* ===== Reset & Base ===== */ -*, *::before, *::after { - box-sizing: border-box; - margin: 0; - padding: 0; -} - -html, body { - height: 100%; - overflow: hidden; -} - -body { - background: var(--bg); - color: var(--light); - font-family: "Space Grotesk", system-ui, sans-serif; - display: flex; - flex-direction: column; - align-items: center; -} - -/* ===== Mode Tabs ===== */ -.mode-tabs { - position: fixed; - top: 16px; - left: 50%; - transform: translateX(-50%); - display: flex; - gap: 4px; - background: var(--surface); - border: 1px solid var(--border); - border-radius: 999px; - padding: 4px; - z-index: 100; - -webkit-backdrop-filter: blur(12px); - backdrop-filter: blur(12px); -} - -.mode-tab { - display: flex; - align-items: center; - gap: 6px; - padding: 10px 20px; - border: none; - border-radius: 999px; - background: transparent; - color: var(--muted); - font-family: inherit; - font-size: 14px; - font-weight: 600; - cursor: pointer; - transition: all 0.2s ease; -} - -.mode-tab:hover { - color: var(--light); - background: var(--surface-hover); -} - -.mode-tab.active { - background: var(--accent); - color: #1a1205; - box-shadow: 0 4px 16px var(--accent-glow); -} - -.mode-tab.active[data-mode="multi"] { - background: var(--accent-secondary); - box-shadow: 0 4px 16px var(--accent-secondary-glow); -} - -.tab-icon { - font-size: 16px; -} - -/* ===== Game Container ===== */ -.game-container { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - min-height: 100vh; - padding: 80px 20px 100px; - width: 100%; - max-width: 100vw; - overflow: hidden; -} - -/* ===== Status Bar ===== */ -.status-bar { - display: flex; - align-items: center; - gap: 12px; - margin-bottom: 16px; - color: var(--muted); - font-size: 14px; -} - -.status-item { - display: flex; - align-items: center; - gap: 8px; -} - -.status-dot { - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--accent); - box-shadow: 0 0 8px var(--accent-glow); - animation: pulse-dot 2s ease-in-out infinite; -} - -@keyframes pulse-dot { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.5; } -} - -.status-divider { - opacity: 0.3; -} - -/* ===== Time Control ===== */ -/* ===== Chess Clock Display ===== */ -.time-control-bar { - display: none; - justify-content: center; - align-items: stretch; - padding: 0; - margin-bottom: 12px; - perspective: 600px; -} - -.time-control-bar.visible { - display: flex; -} - -.timer { - display: flex; - align-items: center; - gap: 12px; - padding: 14px 28px; - min-width: 160px; - justify-content: center; - position: relative; - transition: all 0.3s ease; -} - -/* White side - left half of chess clock */ -.white-timer { - background: linear-gradient(145deg, #2a2a2e 0%, #1a1a1e 100%); - border-radius: 14px 0 0 14px; - border: 2px solid rgba(255, 255, 255, 0.12); - border-right: 1px solid rgba(255, 255, 255, 0.06); -} - -/* Black side - right half of chess clock */ -.black-timer { - background: linear-gradient(145deg, #1a1a1e 0%, #0e0e12 100%); - border-radius: 0 14px 14px 0; - border: 2px solid rgba(255, 255, 255, 0.12); - border-left: 1px solid rgba(255, 255, 255, 0.06); -} - -/* Clock body styling - shared housing */ -.time-control-bar::before { - content: ''; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: 4px; - height: 36px; - background: rgba(255, 255, 255, 0.06); - border-radius: 2px; - z-index: 1; - pointer-events: none; -} - -.timer.active { - background: linear-gradient(145deg, #1c2a1a 0%, #0f1a0d 100%); - border-color: var(--success); - box-shadow: - 0 0 20px rgba(34, 197, 94, 0.15), - inset 0 1px 0 rgba(255, 255, 255, 0.05); -} - -.timer.active .timer-value { - color: #4ade80 !important; - text-shadow: 0 0 12px rgba(74, 222, 128, 0.4); -} - -/* Active indicator flag */ -.timer.active::after { - content: ''; - position: absolute; - top: 6px; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--success); - box-shadow: 0 0 8px rgba(34, 197, 94, 0.6); - animation: clock-pulse 1.5s ease-in-out infinite; -} - -.white-timer.active::after { - right: 10px; -} - -.black-timer.active::after { - left: 10px; -} - -.timer.low-time { - background: linear-gradient(145deg, #2a1a1a 0%, #1a0d0d 100%) !important; - border-color: #ef4444 !important; - box-shadow: - 0 0 20px rgba(239, 68, 68, 0.2), - inset 0 1px 0 rgba(255, 255, 255, 0.05); - animation: pulse-warning 1s ease-in-out infinite; -} - -.timer.low-time .timer-value { - color: #f87171 !important; - text-shadow: 0 0 12px rgba(248, 113, 113, 0.5); - animation: time-blink 0.8s ease-in-out infinite; -} - -.timer.low-time::after { - background: #ef4444 !important; - box-shadow: 0 0 8px rgba(239, 68, 68, 0.6) !important; -} - -@keyframes pulse-warning { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.85; } -} - -@keyframes time-blink { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.5; } -} - -@keyframes clock-pulse { - 0%, 100% { opacity: 1; transform: scale(1); } - 50% { opacity: 0.5; transform: scale(0.85); } -} - -.timer-label { - font-size: 22px; - filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4)); -} - -.timer-value { - font-size: 28px; - font-weight: 700; - font-family: 'Monaco', 'Consolas', 'Courier New', monospace; - min-width: 80px; - text-align: center; - letter-spacing: 2px; - font-variant-numeric: tabular-nums; -} - -.white-timer .timer-value { - color: rgba(255, 255, 255, 0.9); -} - -.black-timer .timer-value { - color: rgba(200, 200, 210, 0.9); -} - -/* ===== Board ===== */ -.board-wrapper { - position: relative; - padding: 12px; - background: linear-gradient(145deg, rgba(255,255,255,0.04), transparent); - border-radius: var(--radius-xl); - border: 1px solid var(--border); -} - -.board { - display: grid; - grid-template-columns: repeat(8, 1fr); - width: min(calc(100vw - 48px), calc(100vh - 260px), 600px); - aspect-ratio: 1; - border-radius: var(--radius-lg); - overflow: hidden; - box-shadow: 0 24px 80px rgba(0, 0, 0, 0.5); -} - -.square { - aspect-ratio: 1; - border: none; - font-size: clamp(24px, 5vmin, 44px); - font-family: 'Apple Symbols', 'Segoe UI Symbol', 'Noto Sans Symbols 2', 'Arial Unicode MS', serif; - font-variant-emoji: text; - color: var(--light); - display: grid; - place-items: center; - cursor: pointer; - position: relative; - transition: transform 0.1s ease, filter 0.1s ease; - text-shadow: 1px 2px 4px rgba(0,0,0,0.4); -} - -.ios-safari .square { - font-family: 'Apple Symbols', 'Arial Unicode MS', serif; - font-variant-emoji: text; -} - -.square.dark { background: var(--dark-square); } -.square.light { background: var(--light-square); } - -.square:hover:not(.disabled) { - filter: brightness(1.15); - transform: scale(1.02); - z-index: 1; -} - -.square.selected { - background: rgba(94, 181, 247, 0.4) !important; - box-shadow: inset 0 0 0 3px var(--selection); -} - -.square.last-move-from, -.square.last-move-to { - background: var(--last-move) !important; -} - -.square.valid-move::after { - content: ''; - width: 28%; - height: 28%; - border-radius: 50%; - background: var(--valid-move); - box-shadow: 0 0 12px var(--valid-move); - position: absolute; - opacity: 0.85; - animation: pulse-move 1.8s ease-in-out infinite; -} - -.square.valid-capture::before { - content: ''; - position: absolute; - inset: 6px; - border-radius: 50%; - border: 4px solid var(--capture); - box-shadow: 0 0 16px rgba(248, 113, 113, 0.5); - animation: pulse-capture 1.8s ease-in-out infinite; -} - -@keyframes pulse-move { - 0%, 100% { transform: scale(1); opacity: 0.7; } - 50% { transform: scale(1.15); opacity: 1; } -} - -@keyframes pulse-capture { - 0%, 100% { transform: scale(1); opacity: 0.6; } - 50% { transform: scale(1.05); opacity: 1; } -} - -.board.disabled .square { - cursor: not-allowed; -} - -/* ===== Toolbar ===== */ -.toolbar { - position: fixed; - bottom: 20px; - left: 50%; - transform: translateX(-50%); - display: flex; - align-items: center; - gap: 8px; - background: rgba(15, 20, 30, 0.9); - -webkit-backdrop-filter: blur(16px); - backdrop-filter: blur(16px); - border: 1px solid var(--border); - border-radius: 999px; - padding: 8px 12px; - z-index: 100; -} - -.toolbar-group { - display: flex; - align-items: center; - gap: 4px; -} - -.toolbar-group.scores { - padding: 0 8px; - border-left: 1px solid var(--border); - border-right: 1px solid var(--border); -} - -.tool-btn { - display: flex; - align-items: center; - gap: 6px; - padding: 10px 14px; - border: none; - border-radius: 999px; - background: transparent; - color: var(--light); - font-family: inherit; - font-size: 13px; - font-weight: 600; - cursor: pointer; - transition: background 0.15s ease; - position: relative; -} - -.tool-btn:hover { - background: var(--surface-hover); -} - -.tool-icon { - font-size: 16px; -} - -.tool-btn .badge { - position: absolute; - top: 4px; - right: 4px; - min-width: 16px; - height: 16px; - border-radius: 999px; - background: var(--accent-secondary); - color: #0a0e17; - font-size: 10px; - font-weight: 700; - display: none; - align-items: center; - justify-content: center; -} - -.tool-btn .badge.visible { - display: flex; -} - -.score-display { - display: flex; - align-items: center; - gap: 6px; - padding: 6px 10px; - font-size: 13px; -} - -.score-label { - color: var(--muted); -} - -.score-value { - font-weight: 700; - color: var(--accent); -} - -/* ===== Slide Panels ===== */ -.slide-panel { - position: fixed; - top: 0; - right: 0; - width: min(360px, 90vw); - height: 100vh; - background: rgba(12, 16, 24, 0.98); - -webkit-backdrop-filter: blur(20px); - backdrop-filter: blur(20px); - border-left: 1px solid var(--border); - transform: translateX(100%); - transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); - z-index: 200; - display: flex; - flex-direction: column; -} - -.slide-panel.open { - transform: translateX(0); -} - -/* Left-side panel variant */ -.slide-panel.left { - right: auto; - left: 0; - border-left: none; - border-right: 1px solid var(--border); - transform: translateX(-100%); -} - -.slide-panel.left.open { - transform: translateX(0); -} - -.panel-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 20px; - border-bottom: 1px solid var(--border); -} - -.panel-header h2 { - font-size: 18px; - font-weight: 700; -} - -.close-btn { - width: 36px; - height: 36px; - border: none; - border-radius: 50%; - background: var(--surface); - color: var(--light); - font-size: 20px; - cursor: pointer; - transition: background 0.15s ease; -} - -.close-btn:hover { - background: var(--surface-hover); -} - -.panel-body { - flex: 1; - padding: 20px; - overflow-y: auto; -} - -.panel-hint { - color: var(--muted); - font-size: 14px; - margin-bottom: 20px; - text-align: center; -} - -/* ===== Buttons ===== */ -.btn-primary { - padding: 14px 24px; - border: none; - border-radius: var(--radius-md); - background: var(--accent-secondary); - color: #0a0e17; - font-family: inherit; - font-size: 14px; - font-weight: 700; - cursor: pointer; - transition: transform 0.15s ease, box-shadow 0.15s ease; - box-shadow: 0 6px 20px var(--accent-secondary-glow); -} - -.btn-primary:hover { - transform: translateY(-2px); - box-shadow: 0 8px 24px var(--accent-secondary-glow); -} - -.btn-secondary { - padding: 12px 20px; - border: 1px solid var(--border); - border-radius: var(--radius-md); - background: var(--surface); - color: var(--light); - font-family: inherit; - font-size: 14px; - font-weight: 600; - cursor: pointer; - transition: background 0.15s ease, border-color 0.15s ease; -} - -.btn-secondary:hover { - background: var(--surface-hover); - border-color: var(--border-active); -} - -.btn-danger { - padding: 14px 24px; - border: none; - border-radius: var(--radius-md); - background: var(--danger); - color: white; - font-family: inherit; - font-size: 14px; - font-weight: 700; - cursor: pointer; - transition: transform 0.15s ease; -} - -.btn-danger:hover { - transform: translateY(-1px); -} - -.full-width { - width: 100%; -} - -/* ===== Inputs ===== */ -.input-group { - display: flex; - gap: 8px; -} - -.text-input { - flex: 1; - padding: 12px 16px; - border: 1px solid var(--border); - border-radius: var(--radius-md); - background: var(--surface); - color: var(--light); - font-family: inherit; - font-size: 14px; - letter-spacing: 2px; - text-transform: uppercase; - transition: border-color 0.15s ease; -} - -.text-input:focus { - outline: none; - border-color: var(--accent-secondary); -} - -.text-input::placeholder { - letter-spacing: normal; - text-transform: none; - color: var(--muted); -} - -/* ===== Divider ===== */ -.divider { - display: flex; - align-items: center; - gap: 12px; - margin: 20px 0; - color: var(--muted); - font-size: 12px; -} - -.divider::before, -.divider::after { - content: ''; - flex: 1; - height: 1px; - background: var(--border); -} - -/* ===== Room Info ===== */ -.room-code-box { - text-align: center; - padding: 24px; - background: linear-gradient(135deg, var(--accent-secondary-glow), transparent); - border: 2px dashed var(--accent-secondary); - border-radius: var(--radius-lg); - margin-bottom: 20px; -} - -.room-code-label { - display: block; - color: var(--muted); - font-size: 11px; - text-transform: uppercase; - letter-spacing: 1px; - margin-bottom: 8px; -} - -.room-code { - display: block; - font-size: 32px; - font-weight: 700; - letter-spacing: 6px; - color: var(--accent-secondary); -} - -.room-code-hint { - display: block; - color: var(--muted); - font-size: 12px; - margin-top: 8px; -} - -.player-info { - display: flex; - align-items: center; - justify-content: space-between; - padding: 16px; - background: var(--surface); - border-radius: var(--radius-md); - margin-bottom: 16px; -} - -.player-label { - color: var(--muted); - font-size: 13px; -} - -.player-color-badge { - display: flex; - align-items: center; - gap: 8px; - padding: 8px 14px; - border-radius: var(--radius-sm); - font-weight: 600; - font-size: 14px; -} - -.player-color-badge.white { - background: rgba(255, 255, 255, 0.15); -} - -.player-color-badge.black { - background: rgba(0, 0, 0, 0.4); -} - -.game-status-box { - padding: 16px; - background: var(--surface); - border-radius: var(--radius-md); - margin-bottom: 20px; - text-align: center; -} - -.status-indicator { - display: inline-flex; - align-items: center; - gap: 8px; - color: var(--muted); - font-size: 14px; -} - -.status-indicator::before { - content: ''; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--accent-secondary); - animation: pulse-dot 1.5s ease-in-out infinite; -} - -/* ===== Modern Chat Design ===== */ -.chat-drawer { - display: flex; - flex-direction: column; - background: linear-gradient(180deg, rgba(15, 20, 35, 0.98) 0%, rgba(10, 14, 23, 0.99) 100%); -} - -.chat-body { - flex: 1; - display: flex; - flex-direction: column; - overflow: hidden; -} - -.chat-messages { - flex: 1; - padding: 20px; - overflow-y: auto; - display: flex; - flex-direction: column; - gap: 12px; - background: linear-gradient(180deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.2) 100%); -} - -.chat-messages::-webkit-scrollbar { - width: 6px; -} - -.chat-messages::-webkit-scrollbar-track { - background: rgba(0, 0, 0, 0.2); - border-radius: 3px; -} - -.chat-messages::-webkit-scrollbar-thumb { - background: var(--accent-secondary); - border-radius: 3px; - opacity: 0.5; -} - -.chat-empty { - flex: 1; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - color: var(--muted); - font-size: 14px; - text-align: center; - padding: 40px; - gap: 12px; -} - -.chat-empty::before { - content: "💬"; - font-size: 48px; - opacity: 0.5; - filter: grayscale(0.5); -} - -.chat-message { - padding: 12px 16px; - border-radius: 16px; - max-width: 85%; - position: relative; - animation: messageSlideIn 0.3s ease-out; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); - transition: transform 0.2s ease, box-shadow 0.2s ease; -} - -.chat-message:hover { - transform: translateY(-1px); - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25); -} - -@keyframes messageSlideIn { - from { - opacity: 0; - transform: translateY(10px); - } - to { - opacity: 1; - transform: translateY(0); - } -} - -.chat-message.white { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.12) 0%, rgba(255, 255, 255, 0.08) 100%); - border: 1px solid rgba(255, 255, 255, 0.15); - border-radius: 16px 16px 16px 4px; - align-self: flex-start; -} - -.chat-message.black { - background: linear-gradient(135deg, rgba(60, 60, 70, 0.5) 0%, rgba(40, 40, 50, 0.6) 100%); - border: 1px solid rgba(100, 100, 120, 0.2); - border-radius: 16px 16px 16px 4px; - align-self: flex-start; -} - -.chat-message.own { - background: linear-gradient(135deg, var(--accent-secondary) 0%, rgba(55, 178, 255, 0.85) 100%); - border: none; - border-radius: 16px 16px 4px 16px; - align-self: flex-end; - color: #0a0e17; -} - -.chat-message.own .chat-sender, -.chat-message.own .chat-timestamp, -.chat-message.own .chat-text { - color: #0a0e17; -} - -.chat-message-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 6px; - gap: 12px; -} - -.chat-sender { - font-weight: 700; - font-size: 11px; - text-transform: uppercase; - letter-spacing: 0.5px; - color: var(--accent); -} - -.chat-message.white .chat-sender { - color: rgba(255, 255, 255, 0.9); -} - -.chat-message.black .chat-sender { - color: rgba(180, 180, 200, 0.9); -} - -.chat-timestamp { - font-size: 10px; - color: var(--muted); - opacity: 0.7; -} - -.chat-text { - font-size: 14px; - line-height: 1.5; - word-break: break-word; -} - -.chat-input-row { - display: flex; - gap: 10px; - padding: 16px 20px; - border-top: 1px solid rgba(255, 255, 255, 0.08); - background: linear-gradient(180deg, rgba(20, 25, 40, 0.95) 0%, rgba(15, 20, 30, 0.98) 100%); - -webkit-backdrop-filter: blur(10px); - backdrop-filter: blur(10px); -} - -.chat-input { - flex: 1; - padding: 14px 18px; - border: 1px solid rgba(255, 255, 255, 0.1); - border-radius: 24px; - background: rgba(0, 0, 0, 0.3); - color: var(--light); - font-family: inherit; - font-size: 14px; - transition: all 0.2s ease; -} - -.chat-input::placeholder { - color: var(--muted); - opacity: 0.6; -} - -.chat-input:focus { - outline: none; - border-color: var(--accent-secondary); - background: rgba(0, 0, 0, 0.4); - box-shadow: 0 0 0 3px rgba(55, 178, 255, 0.15); -} - -.chat-send { - padding: 14px 24px; - border: none; - border-radius: 24px; - background: linear-gradient(135deg, var(--accent-secondary) 0%, #2da8e6 100%); - color: #0a0e17; - font-family: inherit; - font-size: 14px; - font-weight: 700; - cursor: pointer; - transition: all 0.2s ease; - box-shadow: 0 2px 8px rgba(55, 178, 255, 0.3); -} - -.chat-send:hover { - transform: translateY(-2px); - box-shadow: 0 4px 16px rgba(55, 178, 255, 0.4); - background: linear-gradient(135deg, #4ac4ff 0%, var(--accent-secondary) 100%); -} - -.chat-send:active { - transform: translateY(0); - box-shadow: 0 2px 8px rgba(55, 178, 255, 0.3); -} - -.chat-send:disabled { - opacity: 0.4; - cursor: not-allowed; - transform: none; - box-shadow: none; - background: rgba(100, 100, 120, 0.5); -} - -/* ===== Toast Container ===== */ - -/* ===== Info Popover ===== */ -.popover { - position: fixed; - bottom: 90px; - right: 50%; - transform: translateX(calc(50% + 120px)); - width: 280px; - background: rgba(12, 16, 24, 0.98); - -webkit-backdrop-filter: blur(16px); - backdrop-filter: blur(16px); - border: 1px solid var(--border); - border-radius: var(--radius-lg); - padding: 16px; - opacity: 0; - visibility: hidden; - transition: opacity 0.2s ease, visibility 0.2s ease, transform 0.2s ease; - z-index: 150; -} - -.popover.open { - opacity: 1; - visibility: visible; -} - -.popover-arrow { - position: absolute; - bottom: -8px; - left: 50%; - transform: translateX(-50%) rotate(45deg); - width: 16px; - height: 16px; - background: rgba(12, 16, 24, 0.98); - border-right: 1px solid var(--border); - border-bottom: 1px solid var(--border); -} - -.info-row { - margin-bottom: 12px; -} - -.info-row:last-child { - margin-bottom: 0; -} - -.info-label { - display: block; - color: var(--muted); - font-size: 11px; - text-transform: uppercase; - letter-spacing: 0.5px; - margin-bottom: 4px; -} - -.info-value { - font-size: 14px; - font-weight: 600; -} - -.log-box { - padding: 10px; - background: rgba(0, 0, 0, 0.3); - border-radius: var(--radius-sm); - font-size: 12px; - line-height: 1.5; - max-height: 80px; - overflow-y: auto; - white-space: pre-wrap; - color: var(--muted); -} - -.scores-detail { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 10px; -} - -.score-card { - padding: 12px; - background: var(--surface); - border-radius: var(--radius-sm); - text-align: center; -} - -.card-label { - display: block; - color: var(--muted); - font-size: 11px; - margin-bottom: 4px; -} - -.card-value { - font-size: 20px; - font-weight: 700; - color: var(--accent); -} - -/* ===== Backdrop ===== */ -.backdrop { - position: fixed; - inset: 0; - background: rgba(0, 0, 0, 0.6); - opacity: 0; - visibility: hidden; - transition: opacity 0.3s ease, visibility 0.3s ease; - z-index: 150; - /* Disabled in online mode to allow board and panels to coexist */ - pointer-events: none; -} - -.backdrop.visible { - opacity: 0; - visibility: hidden; -} - -/* ===== Toast ===== */ -.toast-container { - position: fixed; - top: 80px; - right: 20px; - display: flex; - flex-direction: column; - gap: 10px; - z-index: 300; - pointer-events: none; -} - -.toast { - min-width: 220px; - max-width: 300px; - padding: 14px 18px; - background: rgba(12, 16, 24, 0.95); - -webkit-backdrop-filter: blur(12px); - backdrop-filter: blur(12px); - color: var(--light); - border-radius: var(--radius-md); - border: 1px solid var(--border); - font-size: 13px; - opacity: 0; - transform: translateX(20px); - transition: opacity 0.25s ease, transform 0.25s ease; - pointer-events: auto; -} - -.toast.show { - opacity: 1; - transform: translateX(0); -} - -.toast.success { border-color: rgba(34, 197, 94, 0.5); } -.toast.accent { border-color: var(--accent-glow); } -.toast.secondary { border-color: var(--accent-secondary-glow); } - -/* ===== Mode Visibility ===== */ -body.mode-single .single-player-only { display: flex; } -body.mode-single .multiplayer-only { display: none !important; } -body.mode-multi .single-player-only { display: none !important; } -body.mode-multi .multiplayer-only { display: flex; } - -.hidden { - display: none !important; -} - -/* ===== Scrollbar ===== */ -::-webkit-scrollbar { - width: 6px; -} - -::-webkit-scrollbar-track { - background: transparent; -} - -::-webkit-scrollbar-thumb { - background: rgba(255, 255, 255, 0.15); - border-radius: 3px; -} - -::-webkit-scrollbar-thumb:hover { - background: rgba(255, 255, 255, 0.25); -} - -/* ===== Move History Panel ===== */ -.move-history-drawer .panel-body { - padding: 0; -} - -.move-history-container { - height: 100%; - overflow-y: auto; - padding: 16px; -} - -.move-history-empty { - color: var(--muted); - text-align: center; - padding: 40px 20px; - font-style: italic; -} - -.move-history-table { - width: 100%; - border-collapse: collapse; - font-size: 14px; -} - -.move-history-table thead th { - position: sticky; - top: 0; - background: rgba(12, 16, 24, 0.98); - padding: 12px 8px; - text-align: left; - font-weight: 600; - color: var(--muted); - border-bottom: 1px solid var(--border); - z-index: 1; -} - -.move-history-table thead th:first-child { - width: 40px; - text-align: center; -} - -.move-history-table tbody tr { - border-bottom: 1px solid rgba(255, 255, 255, 0.04); - transition: background 0.15s ease; -} - -.move-history-table tbody tr:hover { - background: var(--surface-hover); -} - -.move-history-table tbody tr:last-child { - background: rgba(227, 179, 65, 0.08); - border-bottom: none; -} - -.move-history-table td { - padding: 10px 8px; - vertical-align: middle; -} - -.move-history-table td.move-number { - color: var(--muted); - font-weight: 600; - text-align: center; - font-size: 12px; -} - -.move-history-table td.white-move { - color: rgba(255, 255, 255, 0.95); -} - -.move-history-table td.black-move { - color: rgba(180, 180, 180, 0.9); -} - -.move-notation { - font-family: 'Monaco', 'Consolas', monospace; - padding: 2px 6px; - border-radius: 4px; - background: rgba(255, 255, 255, 0.05); -} - -.move-notation.capture { - background: rgba(248, 113, 113, 0.15); - color: var(--capture); -} - -.move-notation.check { - background: rgba(251, 191, 36, 0.15); - color: var(--accent); -} - -.move-notation.checkmate { - background: rgba(34, 197, 94, 0.15); - color: var(--success); - font-weight: 700; -} - -.move-notation.castle { - background: rgba(55, 178, 255, 0.15); - color: var(--accent-secondary); -} - -/* ===== Responsive ===== */ -@media (max-width: 640px) { - .mode-tabs { - top: 12px; - } - - .mode-tab { - padding: 8px 14px; - } - - .tab-label { - display: none; - } - - .game-container { - padding: 70px 12px 90px; - } - - .toolbar { - padding: 6px 10px; - gap: 4px; - } - - .tool-btn { - padding: 8px 10px; - } - - .tool-text { - display: none; - } - - .toolbar-group.scores { - padding: 0 6px; - } - - .score-display { - padding: 4px 6px; - font-size: 12px; - } - - .slide-panel { - width: 100vw; - } - - .slide-panel.left { - width: 100vw; - } - - .popover { - right: 10px; - left: 10px; - transform: none; - width: auto; - } -} - -/* ===== Time Control Modal ===== */ -.modal-overlay { - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: rgba(0, 0, 0, 0.7); - display: flex; - align-items: center; - justify-content: center; - z-index: 1500; - -webkit-backdrop-filter: blur(4px); - backdrop-filter: blur(4px); -} - -.modal-overlay.hidden { - display: none; -} - -.modal-content { - background: rgba(15, 20, 30, 0.98); - -webkit-backdrop-filter: blur(20px); - backdrop-filter: blur(20px); - border-radius: var(--radius-xl); - border: 1px solid var(--border); - width: min(420px, calc(100vw - 40px)); - max-height: calc(100vh - 80px); - overflow: auto; - box-shadow: 0 24px 80px rgba(0, 0, 0, 0.5); - color: var(--light); -} - -.modal-header { - display: flex; - justify-content: space-between; - align-items: center; - padding: 20px 24px; - border-bottom: 1px solid var(--border); - color: var(--light); -} - -.modal-header h2 { - font-size: 18px; - font-weight: 700; - margin: 0; - color: var(--light); -} - -.modal-body { - padding: 24px; -} - -.modal-hint { - color: var(--muted); - font-size: 14px; - margin: 0 0 20px 0; - text-align: center; -} - -.modal-footer { - padding: 16px 24px 24px; -} - -/* Time Control Options Grid */ -.time-control-options { - display: grid; - grid-template-columns: repeat(2, 1fr); - gap: 12px; -} - -.time-control-options > :first-child { - grid-column: 1 / -1; -} - -.time-control-option { - display: flex; - flex-direction: column; - align-items: center; - gap: 4px; - padding: 16px 12px; - background: rgba(255, 255, 255, 0.03); - border: 2px solid var(--border); - border-radius: var(--radius-md); - cursor: pointer; - transition: all 0.2s ease; - color: var(--light); -} - -.time-control-option:hover { - border-color: var(--accent); - background: rgba(251, 191, 36, 0.05); -} - -.time-control-option.selected { - border-color: var(--accent); - background: rgba(251, 191, 36, 0.15); -} - -.tc-name { - font-size: 16px; - font-weight: 600; - color: var(--light); -} - -.tc-desc { - font-size: 13px; - color: var(--muted); -} - -/* Time Control Selector for Online Panel */ -.time-control-selector { - display: flex; - flex-direction: column; - gap: 8px; - margin-bottom: 16px; -} - -.tc-label { - font-size: 13px; - font-weight: 500; - color: var(--muted); -} - -.tc-select { - padding: 12px 14px; - background: rgba(255, 255, 255, 0.05); - border: 1px solid var(--border); - border-radius: var(--radius-md); - color: var(--light); - font-size: 14px; - font-family: inherit; - cursor: pointer; -} - -.tc-select:focus { - outline: none; - border-color: var(--accent); -} - -.tc-select option { - background: #1a2535; - color: var(--light); -} - -/* ===== Game End Modal ===== */ -.game-end-modal { - text-align: center; -} - -.game-end-modal .modal-header { - justify-content: center; - border-bottom: none; - padding-bottom: 0; -} - -.game-end-modal .modal-header h2 { - font-size: 24px; - color: var(--light); -} - -.game-end-icon { - font-size: 64px; - margin: 8px 0 16px; - animation: bounce 0.6s ease infinite alternate; -} - -@keyframes bounce { - from { transform: translateY(0); } - to { transform: translateY(-8px); } -} - -.game-end-message { - font-size: 18px; - font-weight: 600; - color: var(--light); - margin: 0 0 24px; -} - -.game-end-scores { - display: flex; - justify-content: center; - gap: 32px; - padding: 16px; - background: rgba(255, 255, 255, 0.03); - border-radius: var(--radius-md); - margin-bottom: 8px; -} - -.final-score { - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; -} - -.score-side { - font-size: 14px; - color: var(--muted); -} - -.score-final { - font-size: 28px; - font-weight: 700; - color: var(--accent); -} - -.game-end-modal .modal-footer { - display: flex; - flex-direction: column; - gap: 8px; -} - -/* Win/Loss/Draw variants */ -.game-end-modal.result-win .game-end-icon { color: #4ade80; } -.game-end-modal.result-loss .game-end-icon { color: #f87171; } -.game-end-modal.result-draw .game-end-icon { color: var(--accent); } diff --git a/chess-game/app/webapp/src/App.jsx b/chess-game/app/webapp/src/App.jsx new file mode 100644 index 0000000..01cb9ee --- /dev/null +++ b/chess-game/app/webapp/src/App.jsx @@ -0,0 +1,257 @@ +import { lazy, Suspense, useEffect, useState } from 'react'; +import Play from './components/Play.jsx'; +import Replay from './components/Replay.jsx'; +import Room from './components/Room.jsx'; +import Puzzle from './components/Puzzle.jsx'; +import { Skeleton, usePersistentState } from './components/ui.jsx'; +import { START_FEN, useGame } from './lib/analyse.js'; +import { usePlay } from './lib/play.js'; +import { useOnlineGame } from './lib/online.js'; +import { holdEngine } from './lib/engine.js'; +import { getArchives, getDailyPuzzle, getGamesFromArchive, getPlayer } from './api.js'; + +// The charts (and d3 beneath them) and the guide load after the board, so play starts at once. +const MetricsPanel = lazy(() => import('./components/MetricsPanel.jsx').then((m) => ({ default: m.MetricsPanel }))); +const Guide = lazy(() => import('./components/Guide.jsx')); + +function PanelSkeleton() { + return ( +
+ + + + +
+ ); +} + +const describe = (g) => + `${g.white.username} vs ${g.black.username} · ${g.time_class} · ${g.white.result}/${g.black.result}`; + +const TITLES = { play: 'Play', room: 'Room', review: 'Review', guide: 'Guide' }; + +/** The theme lives on as a class; index.html applies the saved one before first paint. */ +function useTheme() { + const [theme, setTheme] = usePersistentState('theme', 'dark'); + useEffect(() => { + document.documentElement.classList.toggle('dark', theme === 'dark'); + }, [theme]); + return [theme, () => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))]; +} + +export default function App() { + const [view, setView] = usePersistentState('view', 'play'); + const [insightsOpen, setInsightsOpen] = usePersistentState('insights-open', true); + const [theme, toggleTheme] = useTheme(); + + // A link to a friend's room (?room=CODE) lands here on the Room view directly. + const [joinCode] = useState(() => new URLSearchParams(window.location.search).get('room')); + useEffect(() => { + if (joinCode) setView('room'); + }, [joinCode, setView]); + const online = useOnlineGame(); + + // Playing against the engine + const play = usePlay(); + const [viewing, setViewing] = useState(null); + const liveIndex = Math.max(0, play.frames.positions.length - 1); + useEffect(() => setViewing(null), [play.state?.moveHistory?.length]); + + // Leave the engine to the computer while it is choosing its move; see holdEngine. + useEffect(() => holdEngine(play.thinking), [play.thinking]); + + // Reviewing games from chess.com + const [username, setUsername] = useState(''); + const [status, setStatus] = useState(''); + const [profile, setProfile] = useState(null); + const [games, setGames] = useState([]); + const [selected, setSelected] = useState(null); + const [source, setSource] = useState({ fen: START_FEN, title: 'Starting position' }); + const [puzzle, setPuzzle] = useState(null); + const [ply, setPly] = useState(0); + const reviewed = useGame(source); + useEffect(() => setPly(0), [source]); + + async function run(label, fn) { + setStatus(label); + try { + await fn(); + setStatus(''); + } catch (e) { + setStatus(e.message); + } + } + + const loadPlayer = (e) => { + e.preventDefault(); + const name = username.trim(); + if (!name) return; + run('loading…', async () => { + const [p, archives] = await Promise.all([getPlayer(name), getArchives(name)]); + const latest = archives.archives?.at(-1); + setProfile(p); + setGames(latest ? (await getGamesFromArchive(name, latest)).reverse() : []); + setSelected(null); + }); + }; + + const pick = (g) => { + setSelected(g); + setPuzzle(null); + setSource({ + pgn: g.pgn, + title: describe(g), + flipped: g.black.username.toLowerCase() === profile.username.toLowerCase(), + names: { w: g.white.username, b: g.black.username }, + }); + }; + + const loadPuzzle = () => + run('loading…', async () => { + const p = await getDailyPuzzle(); + setSelected(null); + setSource({ fen: START_FEN, title: 'Starting position' }); + setPuzzle(p); + }); + + const playing = view === 'play'; + const panel = playing + ? { + mode: 'play', + positions: play.frames.positions, + moves: play.frames.moves, + current: viewing ?? liveIndex, + onSeek: (k) => setViewing(k >= liveIndex ? null : k), + } + : { + mode: 'review', + positions: reviewed.positions, + moves: reviewed.moves, + current: Math.min(ply, Math.max(0, reviewed.positions.length - 1)), + names: source.names, + onSeek: setPly, + }; + + const navTo = (target) => ( + + ); + + return ( +
+
+
+ {!playing && ( + + )} +
+
+

{TITLES[view]}

+
+ +
+ + {view === 'review' && ( +
+
+ setUsername(e.target.value)} + placeholder="chess.com username" + aria-label="chess.com username" + /> + +
+ + {games.length > 0 && ( + + )} + {status && {status}} +
+ )} + + {view === 'guide' ? ( +
+ }> + setView('play')} /> + +
+ ) : view === 'room' ? ( +
+ +
+ ) : ( +
+
+ {playing ? ( + setViewing(k === null || k >= liveIndex ? null : k)} /> + ) : puzzle ? ( + setPuzzle(null)} /> + ) : ( + + )} + {!insightsOpen && ( + + )} +
+ {insightsOpen && ( +
+
+ }> + setInsightsOpen(false)} onGuide={() => setView('guide')} /> + +
+
+ )} +
+ )} + +
+ ); +} diff --git a/chess-game/app/webapp/src/api.js b/chess-game/app/webapp/src/api.js new file mode 100644 index 0000000..e22e896 --- /dev/null +++ b/chess-game/app/webapp/src/api.js @@ -0,0 +1,86 @@ +// Client for the XTC backend. Two groups of endpoints: +// /api/chesscom/... → the chess.com Published-Data proxy (see ChessComApi.x) +// /api/engine/... → the Stockfish Online proxy (see EngineApi.x), which is also the +// engine the computer opponent plays by +// +// Every @WebService here is @HttpsRequired. In dev, `/api` is relative so Vite's proxy (which +// already targets the HTTPS backend) handles it. In the production build, the page can be +// loaded over plain http (e.g. someone types the bare host), and a relative fetch would silently +// inherit that scheme and get rejected with 403 by the backend - so force https explicitly. +const API_BASE = import.meta.env.DEV ? '/api' : `https://${location.host}/api`; + +async function get(path, params) { + const query = params ? `?${new URLSearchParams(params)}` : ''; + const res = await fetch(`${API_BASE}/${path}${query}`); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.message || `Request failed (${res.status})`); + return body; +} + +async function post(path, body) { + const res = await fetch(`${API_BASE}/${path}`, { + method: 'POST', + headers: body ? { 'Content-Type': 'application/json' } : undefined, + body: body ? JSON.stringify(body) : undefined, + }); + const reply = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(reply.message || `Request failed (${res.status})`); + return reply; +} + +// ----- playing a game against the computer (see ChessApi.x) ----- + +const session = (id) => encodeURIComponent(id); +const square = (name) => encodeURIComponent(name); + +export const getGameState = (id) => get(`state/${session(id)}`); +export const resetGame = (id, timeControlMs = 0, incrementMs = 0) => + post(`reset/${session(id)}`, timeControlMs > 0 ? { timeControlMs, incrementMs } : undefined); +export const playMove = (id, from, to) => post(`move/${session(id)}/${square(from)}/${square(to)}`); +export const getValidMoves = (id, from) => get(`validmoves/${session(id)}/${square(from)}`); + +// ----- reviewing games from chess.com (see ChessComApi.x) ----- + +export const getPlayer = (name) => get(`chesscom/player/${encodeURIComponent(name)}`); +export const getArchives = (name) => get(`chesscom/archives/${encodeURIComponent(name)}`); +export const getDailyPuzzle = () => get('chesscom/puzzle'); + +// archiveUrl looks like https://api.chess.com/pub/player/{name}/games/{yyyy}/{mm} +export async function getGamesFromArchive(name, archiveUrl) { + const [, year, month] = archiveUrl.match(/\/games\/(\d{4})\/(\d{2})$/) ?? []; + if (!year) throw new Error('Unexpected archive URL'); + return (await get(`chesscom/games/${encodeURIComponent(name)}/${year}/${month}`)).games ?? []; +} + + + + +/** + * Engine evaluation of one position, via the server's `/api/engine` proxy (see EngineApi.x). The + * browser never calls Stockfish directly: the upstream URL, user agent and depth limits all live + * server-side, same as the chess.com endpoints above. + * + * `evaluation` is in pawns from White's point of view and is null in a forced mate, where + * `mate` carries the distance to mate for the side to move instead. + */ +export async function analysePosition(fen, depth = 11) { + const body = await get('engine/analyse', { fen, depth }); + if (!body.success) throw new Error(body.message || 'Engine unavailable'); + return body; +} + +// ----- playing online with a friend (see OnlineChessApi.x) ----- + +export const createRoom = (timeControlMs = 0, incrementMs = 0) => + post('online/create', timeControlMs > 0 ? { timeControlMs, incrementMs } : undefined); +export const joinRoom = (roomCode) => post(`online/join/${encodeURIComponent(roomCode)}`); +export const getRoomState = (roomCode, playerId) => + get(`online/state/${encodeURIComponent(roomCode)}/${encodeURIComponent(playerId)}`); +export const playRoomMove = (roomCode, playerId, from, to) => + post(`online/move/${encodeURIComponent(roomCode)}/${encodeURIComponent(playerId)}/${square(from)}/${square(to)}`); +export const resetRoom = (roomCode, playerId) => + post(`online/reset/${encodeURIComponent(roomCode)}/${encodeURIComponent(playerId)}`); +export const leaveRoom = (roomCode, playerId) => + post(`online/leave/${encodeURIComponent(roomCode)}/${encodeURIComponent(playerId)}`); +export const getRoomValidMoves = (roomCode, playerId, from) => + get(`online/validmoves/${encodeURIComponent(roomCode)}/${encodeURIComponent(playerId)}/${square(from)}`); diff --git a/chess-game/app/webapp/src/components/Board.jsx b/chess-game/app/webapp/src/components/Board.jsx new file mode 100644 index 0000000..dbc3963 --- /dev/null +++ b/chess-game/app/webapp/src/components/Board.jsx @@ -0,0 +1,119 @@ +import { useLayoutEffect, useRef } from 'react'; + +// Solid glyphs for both sides; colour and outline tell them apart, which reads far better than +// the hollow outline glyphs at board size. +const GLYPHS = { k: '♚', q: '♛', r: '♜', b: '♝', n: '♞', p: '♟' }; +const FILES = 'abcdefgh'; +const NAMES = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' }; + +/** Strong ease-out: the piece leaves at once and settles softly. */ +const GLIDE = { duration: 240, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' }; + +const reducedMotion = () => + typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + +/** + * Renders an 8x8 matrix of `{ type, color }` cells, rank 8 first. + * + * Read-only by default. With `onSelect` the squares become buttons, and `selected` and `targets` + * show what is picked up and where it can go. + * + * `moveKey` counts the moves played so far. When it goes up by exactly one, the piece that just + * moved glides from its origin square -- so the computer's reply is something you see happen, + * not a piece that has silently teleported. Stepping backwards, jumping, or flipping the board + * repaints at once. + */ +export default function Board({ + board, + flipped = false, + highlight = [], + selected = null, + targets = [], + onSelect = null, + moveKey = null, +}) { + const host = useRef(null); + const previousKey = useRef(moveKey); + + useLayoutEffect(() => { + const prev = previousKey.current; + previousKey.current = moveKey; + if (moveKey === null || prev === null || moveKey !== prev + 1) return; + if (highlight.length < 2 || reducedMotion() || !host.current) return; + + const [from, to] = highlight; + const origin = host.current.querySelector(`[data-square="${from}"]`); + const destination = host.current.querySelector(`[data-square="${to}"]`); + const piece = destination?.querySelector('.piece'); + if (!origin || !piece || typeof piece.animate !== 'function') return; + + const a = origin.getBoundingClientRect(); + const b = destination.getBoundingClientRect(); + const dx = a.left - b.left; + const dy = a.top - b.top; + + destination.classList.add('lifting'); + const glide = piece.animate( + [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'translate(0, 0)' }], + GLIDE + ); + glide.onfinish = glide.oncancel = () => destination.classList.remove('lifting'); + }, [moveKey, highlight]); + + const ranks = flipped ? [...board].reverse() : board; + return ( +
+ {ranks.map((rank, r) => { + const cells = flipped ? [...rank].reverse() : rank; + return cells.map((cell, c) => { + const rowIdx = flipped ? 7 - r : r; + const colIdx = flipped ? 7 - c : c; + const square = FILES[colIdx] + (8 - rowIdx); + const dark = (rowIdx + colIdx) % 2 === 1; + const isTarget = targets.includes(square); + const cls = [ + 'square', + dark ? 'dark' : 'light', + highlight.includes(square) ? 'hl' : '', + square === selected ? 'sel' : '', + ].join(' '); + + const press = onSelect ? () => onSelect(square) : undefined; + const description = cell ? `${cell.color === 'w' ? 'white' : 'black'} ${NAMES[cell.type]}` : 'empty'; + return ( +
{ + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + press(); + } + } + : undefined + } + > + {c === 0 && {square[1]}} + {r === 7 && {square[0]}} + {cell && {GLYPHS[cell.type]}} + {isTarget &&
+ ); + }); + })} +
+ ); +} diff --git a/chess-game/app/webapp/src/components/Guide.jsx b/chess-game/app/webapp/src/components/Guide.jsx new file mode 100644 index 0000000..5b1e2a7 --- /dev/null +++ b/chess-game/app/webapp/src/components/Guide.jsx @@ -0,0 +1,376 @@ +import { FEATURES } from '../lib/model.js'; + +const TOC = [ + { id: 'play', label: 'How to play' }, + { id: 'reading', label: 'Reading the insights' }, + { id: 'position', label: 'This position' }, + { id: 'game', label: 'Your game' }, + { id: 'thinking', label: 'How you think' }, + { id: 'learn', label: 'Learning from a game' }, + { id: 'model', label: 'The model, in full' }, + { id: 'sources', label: 'Where the numbers come from' }, +]; + +/** One metric: what it is, how it is worked out, how to read it, and what it is good for. */ +function MetricDoc({ name, what, formula, read, helps }) { + return ( +
+

{name}

+

{what}

+ {formula &&

{formula}

} +
+
+
Reading it
+
{read}
+
+
+
Why it helps
+
{helps}
+
+
+
+ ); +} + +export default function Guide({ onPlay }) { + return ( +
+
+
+

Play the engine. Then see how you think.

+

+ Chess Playground pits you against Stockfish and, while you play, measures two + things: how good each move was, and how you arrived at it. This page explains every + number on the screen and how to turn them into better chess. +

+ +
+
+ +
+ + +
+
+

How to play

+
    +
  1. + You are White. Click one of your pieces. Dots mark the squares it + can reach; a ring marks a piece it can capture. +
  2. +
  3. + Click a dot to move. The piece moves at once. The engine — Stockfish, + through the server — takes about three seconds to think, then its piece glides into + place. +
  4. +
  5. + Pick a clock under the board: none, 5 minutes, or 10 minutes plus 5 + seconds a move. Starting a new game resets the board. +
  6. +
  7. + Look back any time. Click a move on the scoresheet, or any bar or + point in a chart, and the board shows that position. Back to the game returns + you to play; the engine waits. +
  8. +
  9. + Just want to play? The arrow at the top of the insights hides them + and gives the board the whole screen. +
  10. +
+

+ Review mode loads anyone’s recent games from chess.com by username — + or the daily puzzle — and shows the same insights for both players. +

+
+ +
+

Reading the insights

+

+ The panel beside the board is split into sections you can fold away. Every number is + live: the engine evaluates one position every second and a half — that is as fast as + the free service allows — starting with the one on the board, then sketching the rest + of the game end to end and filling in the gaps. Each position is asked about once and + remembered, so a new move costs one request, not the whole game again. +

+

+ While a value is still on its way you will see a soft placeholder rather than a zero. + The Live pill at the top says when everything is up to date; clicking it + pauses the engine. +

+
+ +
+

This position

+

About the position on the board right now, before the next move.

+ + + + + + + +
+ +
+

Your game

+

How well each move was played, judged by the engine.

+ + + + + + + + +
+ +
+

How you think

+

+ A mathematical model of your choices: not whether a move was good, but how predictable + it was and what that says about how you choose. +

+ + + + + + + +
+ +
+

Learning from a game

+
    +
  1. + Play a full game. Don’t look at the numbers while you play — fold the + insights away with the arrow if they distract you. +
  2. +
  3. + Find the turning points. Open Every move and sort by{' '} + Win lost. The top two or three rows are the game. +
  4. +
  5. + Go back to the position before each one. Click the row. Before reading + anything, choose the move you would play now. +
  6. +
  7. + Compare. The evaluation card shows what Stockfish wanted. The + choice here shows what the model expected and where your move ranked. If the + engine’s move was not in the model’s top few either, it was hard; if it was, you missed + something you would normally see. +
  8. +
  9. + Name the pattern. A high-surprise, high-cost move is usually a tactic + you didn’t calculate. A low-surprise, high-cost move is a natural-looking mistake — the + kind worth memorising. +
  10. +
  11. + Watch the trends. Accuracy and decisiveness move slowly. Compare across + games, not moves. +
  12. +
  13. + Learn from others. In Review, load a strong player’s games and + look at their profile: how decisive they are, how few options they really weigh, and + where in their games the complexity peaks. +
  14. +
+
+ +
+

The model, in full

+

+ The thinking model runs in your browser. It values a position with seven simple + features, then assumes you pick moves the way a person under time pressure does: usually + the best-looking one, sometimes another, in proportion to how good each looks. +

+
+

V(p) = Σᵢ wᵢ · φᵢ(p) — the value of a position, from the mover’s side

+

P(m | p) = e^(β·V(p∘m)) / Σₘ′ e^(β·V(p∘m′)) — a softmax policy over the legal moves

+

β̂ = argmax_β Σₜ log P(mₜ | pₜ) — fitted to the moves actually played

+

H(p) = −Σ P log₂ P · S(m) = −log₂ P(m) · options = 2^(mean S)

+
+

+ The log-likelihood is concave in β, so a simple search finds the single best fit. A + neat consequence: at that fit, your mean surprise equals your mean uncertainty exactly — + setting the derivative to zero forces the expected and actual values to balance. The + charts therefore show the move-by-move gap between the two, which is where the + information is. +

+ + + + + + + + + + + + {FEATURES.map((f) => ( + + + + + + + ))} + +
The seven features and their weights
φFeaturewMeasured as
{f.symbol}{f.label}{f.w} + {f.note} ({f.unit}) +
+

+ Model fit, at the bottom of the insights, regresses the engine’s + evaluation on the model’s value across the game. r² near 1 means the model tracks the + engine closely; the slope says how far apart their scales are. It will never be perfect: + the model sees one move ahead, Stockfish many. That gap is the point — it is a model of a + person, not a search. +

+
+ +
+

Where the numbers come from

+
    +
  • + The engine’s moves and evaluations come from Stockfish Online, through + this server’s /api/engine proxy. Nothing chooses the computer’s moves + locally. +
  • +
  • + The thinking model runs entirely in your browser. +
  • +
  • + Win chance and accuracy use the formulas Lichess publishes, so they + compare with what you see there. +
  • +
  • + Games to review come from chess.com’s public API, through the server’s{' '} + /api/chesscom proxy. +
  • +
  • + Evaluations are remembered in your browser, so returning to a game is + instant and the shared engine is not asked twice. +
  • +
+
+
+
+
+ ); +} diff --git a/chess-game/app/webapp/src/components/MetricsPanel.jsx b/chess-game/app/webapp/src/components/MetricsPanel.jsx new file mode 100644 index 0000000..32c82d4 --- /dev/null +++ b/chess-game/app/webapp/src/components/MetricsPanel.jsx @@ -0,0 +1,394 @@ +import { useMemo, useState } from 'react'; +import { useLocalPolicy } from '../lib/analyse.js'; +import { leastSquares, useEngineEvaluations } from '../lib/engine.js'; +import { describeEvaluation, moveRows, sideSummary, winChance } from '../lib/insights.js'; +import { + CalibrationChart, + COLORS, + ComplexityChart, + EvalChart, + fmt, + PolicyChart, + pct, + sideColor, + signed, + ThinkingChart, + WinLostChart, +} from './charts.jsx'; +import { MovesTable } from './MovesTable.jsx'; +import { ChartCard, Empty, Metric, OutcomeBar, Progress, Section, Segmented, Thinking } from './ui.jsx'; + +const SIDE = { w: 'White', b: 'Black' }; + +/** The win chance split between the sides, as a thin pill bar: White in gold, Black in blue. */ +function WinBar({ pawns }) { + const white = Number.isFinite(pawns) ? Math.round(winChance(pawns)) : 50; + return ( +
+ +
+ ); +} + +/** + * One side's game on a card, the way the reference ranks its agents: the name and how many + * moves were judged, the accuracy as the big number, the split of good moves and mistakes as a + * thin bar with its counts, then a row of averages under a rule. + */ +function SideCard({ name, color, summary }) { + const good = Math.max(0, summary.judged - summary.inaccuracies - summary.mistakes - summary.blunders); + const waiting = summary.judged === 0; + return ( +
+
+ + + {summary.judged} of {summary.moves} judged +
+
+ + {waiting ? '—' : `${Math.round(summary.accuracy)}%`} + + accuracy +
+ +
+ acpl {waiting ? '—' : Math.round(summary.acpl)} + engine {waiting ? '—' : pct(summary.engineMatch, 0)} + worst {summary.worst ? summary.worst.san : '—'} +
+
+ ); +} + +function EngineStatus({ engine, onToggle, enabled }) { + if (!enabled) { + return ( + + ); + } + if (engine.unavailable) { + return ( + + Engine offline + + ); + } + if (engine.running) { + return ( + + ); + } + return ( + + ); +} + +/** + * Everything the right-hand pane shows about a game, built from one shape: the positions, the + * moves between them, and which position is on the board. Play and Review both feed it, so the + * same numbers mean the same thing in both. + */ +export function MetricsPanel({ mode, positions, moves, current, names, onSeek, onCollapse, onGuide }) { + const playing = mode === 'play'; + const [depth, setDepth] = useState(11); + const [engineOn, setEngineOn] = useState(true); + const [chosenSide, setChosenSide] = useState('w'); + const side = playing ? 'w' : chosenSide; + + const policy = useLocalPolicy(positions, moves); + const engine = useEngineEvaluations(positions, { depth, enabled: engineOn, current }); + + const rows = useMemo(() => moveRows(moves, policy.decisions, engine.points), [moves, policy.decisions, engine.points]); + const mine = useMemo(() => rows.filter((r) => r.color === side), [rows, side]); + const summary = useMemo(() => sideSummary(rows, side, policy.players?.[side]), [rows, side, policy.players]); + const whiteSummary = useMemo(() => sideSummary(rows, 'w', policy.players?.w), [rows, policy.players]); + const blackSummary = useMemo(() => sideSummary(rows, 'b', policy.players?.b), [rows, policy.players]); + + const here = engine.points[current] ?? null; + const decision = policy.decisions[current] ?? null; + const playedHere = moves[current] ?? null; + + const candidates = useMemo(() => { + if (!decision?.probs) return []; + const list = decision.candidates.map((c, i) => ({ ...c, p: decision.probs[i], played: i === decision.playedIndex })); + const top = list.slice(0, 8); + const played = list.find((c) => c.played); + if (played && !top.includes(played)) top[top.length - 1] = played; + return top; + }, [decision]); + + const pairs = useMemo( + () => + moves + .map((m, k) => { + const d = policy.decisions[k]; + const after = engine.points[k + 1]?.pawns; + if (!d || d.vPlayed === null || !Number.isFinite(after)) return null; + return [m.color === 'w' ? d.vPlayed : -d.vPlayed, after]; + }) + .filter(Boolean), + [moves, policy.decisions, engine.points] + ); + const fit = useMemo(() => leastSquares(pairs), [pairs]); + + const who = playing ? 'You' : names?.[side] ?? SIDE[side]; + const evaluating = engineOn && !here && !engine.unavailable; + const hasMoves = moves.length > 0; + + return ( +
+
+
+

Insights

+ setEngineOn((on) => !on)} /> +
+
+ + +
+
+ + {engine.running && ( + + )} + +
+
+
+ Engine evaluation + {evaluating ? ( + + + + ) : ( + + {here ? signed(here.pawns, 2) : '—'} + {here && pawns} + + )} + + {here ? describeEvaluation(here.pawns, here.mate) : engine.unavailable ? 'Engine offline' : ' '} + {here?.best && <> · Stockfish would play {here.best}} + + +
+ + + + +
+
+ +
+ ) + } + > + {!hasMoves ? ( + {playing ? 'Make your first move — the game charts start building from there.' : 'No moves in this position.'} + ) : ( + <> +
+ + +
+ + + + + + + {summary.judged ? ( + + ) : ( + Waiting on the engine… + )} + + + )} +
+ + {hasMoves && ( +
+ +
+ )} + +
+ {!hasMoves || summary.beta === null ? ( + {playing ? 'Your thinking profile appears once there are a few of your moves to fit it to.' : 'The thinking profile appears once there are a few moves to fit it to.'} + ) : ( + <> +
+ + + + +
+ + + + + + + + + + )} +
+ +
+ {candidates.length ? ( + + + + ) : ( + {decision ? 'No legal moves — the game is over.' : 'Scoring the position…'} + )} +
+ + {hasMoves && ( +
+ {fit ? ( + <> +
+ + + +
+ + + + + ) : ( + Appears once the engine has evaluated a few positions. + )} +
+ )} + +
+ +
+
+ ); +} diff --git a/chess-game/app/webapp/src/components/MovesTable.jsx b/chess-game/app/webapp/src/components/MovesTable.jsx new file mode 100644 index 0000000..2426740 --- /dev/null +++ b/chess-game/app/webapp/src/components/MovesTable.jsx @@ -0,0 +1,139 @@ +import { useMemo, useState } from 'react'; +import { + createColumnHelper, + createSortedRowModel, + rowSortingFeature, + sortFn_alphanumeric, + sortFn_basic, + tableFeatures, + useTable, +} from '@tanstack/react-table'; +import { SEVERITY } from '../lib/insights.js'; +import { fmt, pct } from './charts.jsx'; + +const features = tableFeatures({ + rowSortingFeature, + sortedRowModel: createSortedRowModel(), + sortFns: { basic: sortFn_basic, alphanumeric: sortFn_alphanumeric }, +}); + +const helper = createColumnHelper(); + +// Engine-dependent cells are undefined until evaluated, so they sort after the known values. +const known = (v) => (v === null || v === undefined || Number.isNaN(v) ? undefined : v); + +const columns = helper.columns([ + helper.accessor('ply', { + header: 'Move', + sortFn: 'basic', + cell: (info) => info.row.original.label, + }), + helper.accessor((r) => known(r.accuracy), { + id: 'accuracy', + header: 'Accuracy', + sortFn: 'basic', + sortUndefined: 'last', + cell: (info) => (info.getValue() === undefined ? '…' : `${fmt(info.getValue(), 0)}%`), + }), + helper.accessor((r) => known(r.winLost), { + id: 'winLost', + header: 'Win lost', + sortFn: 'basic', + sortUndefined: 'last', + cell: (info) => (info.getValue() === undefined ? '…' : `${fmt(info.getValue(), 1)}`), + }), + helper.accessor((r) => r.severity ?? '', { + id: 'severity', + header: 'Verdict', + sortFn: 'alphanumeric', + cell: (info) => { + const s = SEVERITY.find((x) => x.key === info.getValue()); + return s ? {s.label} : ''; + }, + }), + helper.accessor((r) => r.engineBest ?? '', { + id: 'engine', + header: 'Engine', + sortFn: 'alphanumeric', + cell: (info) => { + const r = info.row.original; + if (!r.engineBest) return '…'; + return r.matched ? ✓ same : {r.engineBest}; + }, + }), + helper.accessor((r) => known(r.surprisal), { + id: 'surprisal', + header: 'Surprise', + sortFn: 'basic', + sortUndefined: 'last', + cell: (info) => (info.getValue() === undefined ? '…' : `${fmt(info.getValue(), 2)} b`), + }), + helper.accessor((r) => known(r.pPlayed), { + id: 'pPlayed', + header: 'Model P', + sortFn: 'basic', + sortUndefined: 'last', + cell: (info) => (info.getValue() === undefined ? '…' : pct(info.getValue(), 1)), + }), +]); + +/** + * Every move of one side, sortable. Sorting by win chance lost is the quickest way to find the + * moves worth studying; clicking a row puts that position on the board. + */ +export function MovesTable({ rows, current, onSeek }) { + const [sorting, setSorting] = useState([{ id: 'ply', desc: false }]); + const data = useMemo(() => rows, [rows]); + + const table = useTable({ + features, + columns, + data, + state: { sorting }, + onSortingChange: setSorting, + }); + + return ( +
+
Move history · {rows.length} {rows.length === 1 ? 'move' : 'moves'}
+ + + {table.getHeaderGroups().map((group) => ( + + {group.headers.map((header) => { + const sorted = header.column.getIsSorted(); + return ( + + ); + })} + + ))} + + + {table.getRowModel().rows.map((row) => ( + onSeek?.(row.original.ply)} + > + {row.getAllCells().map((cell) => ( + + ))} + + ))} + +
+ +
+ +
+
+ ); +} diff --git a/chess-game/app/webapp/src/components/Play.jsx b/chess-game/app/webapp/src/components/Play.jsx new file mode 100644 index 0000000..be43d45 --- /dev/null +++ b/chess-game/app/webapp/src/components/Play.jsx @@ -0,0 +1,270 @@ +import { useEffect, useRef, useState } from 'react'; +import { Chess } from 'chess.js'; +import Board from './Board.jsx'; +import { moveSquares, toMatrix } from '../lib/play.js'; +import { Segmented, Skeleton, Thinking } from './ui.jsx'; + +const TIME_CONTROLS = [ + { label: 'No clock', ms: 0, inc: 0 }, + { label: '5 + 0', ms: 5 * 60_000, inc: 0 }, + { label: '10 + 5', ms: 10 * 60_000, inc: 5_000 }, +]; +const TIME_OPTIONS = TIME_CONTROLS.map((t) => ({ value: t.label, label: t.label })); + +/** Why a game ended, read off the status word the server sends. */ +const END_REASON = { + Checkmate: 'Checkmate', + Stalemate: 'Stalemate — draw', + FiftyMoveRule: 'Fifty-move rule — draw', + InsufficientMaterial: 'Insufficient material — draw', + ThreefoldRepetition: 'Threefold repetition — draw', + Timeout: 'Time out', +}; + +function isInCheck(fen) { + try { + return new Chess(fen).inCheck(); + } catch { + return false; + } +} + +const clock = (ms) => { + if (!Number.isFinite(ms)) return '—'; + const total = Math.max(0, Math.round(ms / 1000)); + return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; +}; + +/** The moves so far as a scoresheet. Any move can be clicked to look at that position. */ +function Scoresheet({ moves, viewing, onView }) { + if (!moves.length) return null; + const rows = []; + for (let i = 0; i < moves.length; i += 2) rows.push(i); + return ( +
    + {rows.map((i) => ( +
  1. + {i / 2 + 1}. + {[i, i + 1].map((k) => + moves[k] ? ( + + ) : ( + + ) + )} +
  2. + ))} +
+ ); +} + +function PlaySkeleton() { + return ( +
+
+ +
+
+ +
+
+ ); +} + +/** A prominent, non-blocking alert for "Check!" -- urgent enough to notice, not a dialog that + * stops play. */ +function CheckAlert({ onYou }) { + return ( +

+

+ ); +} + +/** New game + time control, tucked behind one button instead of sitting in the main flow. */ +function GameMenu({ options, value, onChange, onNewGame, busy }) { + const ref = useRef(null); + return ( +
+ + Game + + +
+ + +
+
+ ); +} + +/** The game-state alert: checkmate, stalemate, draw or timeout, with a way to play again. */ +function GameOverModal({ status, message, onRestart, onDismiss, restarting }) { + const title = END_REASON[status] ?? 'Game over'; + return ( +
+
e.stopPropagation()} + > +

{title}

+

{message}

+
+ + {TIME_CONTROLS.map((t) => ( + + ))} +
+
+
+ ); +} + +export default function Play({ play, viewing, onView }) { + const { state, frames, selected, targets, error, thinking, playable, touch, restart, restarting } = play; + + const [dismissed, setDismissed] = useState(false); + const [nextLabel, setNextLabel] = useState(TIME_CONTROLS[0].label); + const lastStatus = useRef(state?.status); + useEffect(() => { + if (state?.status !== lastStatus.current) setDismissed(false); + lastStatus.current = state?.status; + }, [state?.status]); + + if (!state) return error ?

{error}

: ; + + const live = viewing === null; + const shown = live ? null : frames.positions[viewing]; + const tc = state.timeControl; + const over = state.status !== 'Ongoing'; + const inCheck = live && !over && isInCheck(state.fen); + + const status = over + ? state.message + : thinking + ? 'The engine is thinking' + : playable + ? 'Your move' + : 'Waiting'; + + return ( +
+ {over && !dismissed && ( + { + setDismissed(true); + restart(ms, inc); + }} + onDismiss={() => setDismissed(true)} + restarting={restarting} + /> + )} + +
+

+

+
+ {tc && ( +
+ + Engine {clock(tc.blackTimeMs)} + + + You {clock(tc.whiteTimeMs)} + +
+ )} + { + const t = TIME_CONTROLS.find((tc) => tc.label === nextLabel) ?? TIME_CONTROLS[0]; + restart(t.ms, t.inc); + }} + /> +
+
+ + {inCheck && } + +
+ + {!live && ( +
+ Viewing the position after move {Math.ceil(viewing / 2)} + +
+ )} +
+ + {error &&

{error}

} + +

+ {live + ? playable + ? 'Click a piece, then a highlighted square.' + : over + ? 'Game over — start another from the Game menu above.' + : 'Hold on while the engine replies.' + : 'Click any move to look back; the game waits for you.'} +

+ + + +
+ + {state.playerScore > 0 && <>You +{state.playerScore}} + {state.playerScore > 0 && state.opponentScore > 0 && ' · '} + {state.opponentScore > 0 && <>Engine +{state.opponentScore}} + +
+
+ ); +} diff --git a/chess-game/app/webapp/src/components/Puzzle.jsx b/chess-game/app/webapp/src/components/Puzzle.jsx new file mode 100644 index 0000000..9269911 --- /dev/null +++ b/chess-game/app/webapp/src/components/Puzzle.jsx @@ -0,0 +1,127 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Chess } from 'chess.js'; +import Board from './Board.jsx'; +import { puzzleSolution } from '../lib/analyse.js'; + +/** How long the opponent's reply waits before it plays, so it reads as a reply and not a jump. */ +const REPLY_DELAY_MS = 500; +/** How long the wrong-move shake stays on screen before the attempt is cleared. */ +const WRONG_FLASH_MS = 450; + +/** Replays the solution up to `ply` from `fen`, for the board shown and the targets offered. */ +function frameAt(fen, solution, ply) { + const game = new Chess(fen); + for (let i = 0; i < ply; i++) { + game.move({ from: solution[i].from, to: solution[i].to, promotion: solution[i].promotion ?? undefined }); + } + return { board: game.board(), fen: game.fen(), lastMove: ply > 0 ? solution[ply - 1] : null }; +} + +/** One daily puzzle, played out move by move: the user attempts the solving side's moves, the + * other side's replies play themselves, and a wrong attempt is rejected on the spot. */ +export default function Puzzle({ puzzle, onExit }) { + const solution = useMemo(() => puzzleSolution(puzzle.fen, puzzle.pgn), [puzzle.fen, puzzle.pgn]); + const flipped = puzzle.fen.split(' ')[1] === 'b'; + + const [ply, setPly] = useState(0); + const [selected, setSelected] = useState(null); + const [wrong, setWrong] = useState(false); + useEffect(() => { + setPly(0); + setSelected(null); + setWrong(false); + }, [puzzle.fen, puzzle.pgn]); + + const solved = solution.length > 0 && ply >= solution.length; + const solverTurn = ply % 2 === 0; + + // The side being replied to plays itself, the same way the computer's move lands in + // single-player: a short pause, then the next ply. + useEffect(() => { + if (solved || solverTurn) return; + const t = setTimeout(() => setPly((p) => p + 1), REPLY_DELAY_MS); + return () => clearTimeout(t); + }, [ply, solved, solverTurn]); + + const frame = useMemo(() => frameAt(puzzle.fen, solution, ply), [puzzle.fen, solution, ply]); + + const targets = useMemo(() => { + if (!selected) return []; + try { + return new Chess(frame.fen).moves({ square: selected, verbose: true }).map((m) => m.to); + } catch { + return []; + } + }, [selected, frame.fen]); + + const wrongTimer = useRef(0); + const attempt = (from, to) => { + const expected = solution[ply]; + if (expected && expected.from === from && expected.to === to) { + setPly((p) => p + 1); + setSelected(null); + setWrong(false); + return; + } + setSelected(null); + setWrong(true); + clearTimeout(wrongTimer.current); + wrongTimer.current = setTimeout(() => setWrong(false), WRONG_FLASH_MS); + }; + + const touch = (square) => { + if (!solverTurn || solved) return; + if (selected === square) { + setSelected(null); + return; + } + if (selected && targets.includes(square)) { + attempt(selected, square); + return; + } + setSelected(square); + }; + + if (solution.length === 0) { + return ( +
+

Couldn't read this puzzle's solution.

+ +
+ ); + } + + const status = solved + ? 'Solved!' + : wrong + ? 'Not quite — try again.' + : solverTurn + ? `Find the best move for ${puzzle.fen.includes(' w ') ? 'White' : 'Black'}.` + : "Opponent's move…"; + + return ( +
+

{puzzle.title}

+

+

+
+ rank.map((p) => (p ? { type: p.type, color: p.color } : null)))} + highlight={frame.lastMove ? [frame.lastMove.from, frame.lastMove.to] : []} + selected={selected} + targets={targets} + onSelect={solverTurn && !solved ? touch : null} + flipped={flipped} + moveKey={ply} + /> +
+ {solved && ( + + )} +
+ ); +} diff --git a/chess-game/app/webapp/src/components/Replay.jsx b/chess-game/app/webapp/src/components/Replay.jsx new file mode 100644 index 0000000..822e150 --- /dev/null +++ b/chess-game/app/webapp/src/components/Replay.jsx @@ -0,0 +1,42 @@ +import Board from './Board.jsx'; + +/** Steps through the frames of a game, or shows a single position. */ +export default function Replay({ positions, moves, title, flipped, ply, setPly, error }) { + if (error) return

Could not read the game: {error}

; + if (!positions.length) return null; + + const idx = Math.min(ply, positions.length - 1); + const pos = positions[idx]; + + return ( +
+ {title &&

{title}

} +
+ +
+ {moves.length > 0 && ( + <> +
+ + + + {idx} / {moves.length} + + + +
+
    + {moves.map((m, i) => ( +
  1. + +
  2. + ))} +
+ + )} +
+ ); +} diff --git a/chess-game/app/webapp/src/components/Room.jsx b/chess-game/app/webapp/src/components/Room.jsx new file mode 100644 index 0000000..dcec688 --- /dev/null +++ b/chess-game/app/webapp/src/components/Room.jsx @@ -0,0 +1,245 @@ +import { useEffect, useRef, useState } from 'react'; +import Board from './Board.jsx'; +import { moveSquares, toMatrix } from '../lib/play.js'; +import { Segmented, Skeleton, Thinking } from './ui.jsx'; + +const TIME_CONTROLS = [ + { label: 'No clock', ms: 0, inc: 0 }, + { label: '5 + 0', ms: 5 * 60_000, inc: 0 }, + { label: '10 + 5', ms: 10 * 60_000, inc: 5_000 }, +]; +const TIME_OPTIONS = TIME_CONTROLS.map((t) => ({ value: t.label, label: t.label })); + +const END_REASON = { + Checkmate: 'Checkmate', + Stalemate: 'Stalemate — draw', + FiftyMoveRule: 'Fifty-move rule — draw', + InsufficientMaterial: 'Insufficient material — draw', + ThreefoldRepetition: 'Threefold repetition — draw', + Timeout: 'Time out', +}; + +const clock = (ms) => { + if (!Number.isFinite(ms)) return '—'; + const total = Math.max(0, Math.round(ms / 1000)); + return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; +}; + +const inviteUrl = (roomCode) => `${location.origin}${location.pathname}?room=${roomCode}`; + +/** The room code and a link a friend can click straight into the seat across the board. */ +function InviteCard({ roomCode }) { + const [copied, setCopied] = useState(false); + const timer = useRef(0); + + const copy = async () => { + try { + await navigator.clipboard.writeText(inviteUrl(roomCode)); + setCopied(true); + clearTimeout(timer.current); + timer.current = setTimeout(() => setCopied(false), 1800); + } catch { + // Clipboard permission denied or unavailable: the code itself is still visible to copy. + } + }; + + return ( +
+ Room code + {roomCode} + +

Anyone with this link joins straight into the seat across from you.

+
+ ); +} + +function RoomSkeleton() { + return ( +
+ +
+ +
+
+ ); +} + +/** Create a room or join one by code -- the entry point when this browser has no seat yet. */ +function RoomEntry({ joinCode, create, creating, join, joining, error }) { + const [code, setCode] = useState(joinCode ?? ''); + const [label, setLabel] = useState(TIME_CONTROLS[0].label); + + useEffect(() => { + if (joinCode) setCode(joinCode); + }, [joinCode]); + + const submitJoin = (e) => { + e.preventDefault(); + if (code.trim()) join(code); + }; + + return ( +
+
+
+

Start a room

+

Play a friend over the board. You play White; whoever joins your room plays Black.

+ + +
+ +
+

Join a room

+

Have a code or a link from a friend? Enter it here.

+
+ setCode(e.target.value.toUpperCase())} + placeholder="ROOM CODE" + aria-label="Room code" + maxLength={6} + /> + +
+
+
+ {error &&

{error}

} +
+ ); +} + +export default function Room({ online, joinCode }) { + const { + room, state, frames, loading, error, playable, + selected, targets, touch, create, creating, join, joining, + leave, leaving, restart, restarting, + } = online; + + const attempted = useRef(false); + useEffect(() => { + if (joinCode && !room && !attempted.current) { + attempted.current = true; + join(joinCode); + } + }, [joinCode, room, join]); + + if (!room) { + return ( + + ); + } + + if (loading || !state) return ; + + if (state.waitingForOpponent) { + return ( +
+ + +
+ ); + } + + const over = state.status !== 'Ongoing'; + const youAreWhite = state.playerColor === 'White'; + const tc = state.timeControl; + + const status = state.opponentLeft + ? 'Your opponent left the game.' + : over + ? state.message + : playable + ? 'Your move' + : state.message || 'Waiting for your opponent'; + + return ( +
+
+

+

+
+ {tc && ( +
+ + Opponent {clock(youAreWhite ? tc.blackTimeMs : tc.whiteTimeMs)} + + + You {clock(youAreWhite ? tc.whiteTimeMs : tc.blackTimeMs)} + +
+ )} + +
+
+ +
+ Room {state.roomCode} +
+ +
+ +
+ + {error &&

{error}

} + +

+ {state.opponentLeft + ? 'Start a new room to play again.' + : playable + ? 'Click a piece, then a highlighted square.' + : over + ? END_REASON[state.status] ?? 'Game over.' + : 'Hold on for your opponent’s move.'} +

+ + {over && !state.opponentLeft && ( + + )} + +
+ + {state.playerScore > 0 && <>You +{state.playerScore}} + {state.playerScore > 0 && state.opponentScore > 0 && ' · '} + {state.opponentScore > 0 && <>Opponent +{state.opponentScore}} + +
+
+ ); +} diff --git a/chess-game/app/webapp/src/components/charts.jsx b/chess-game/app/webapp/src/components/charts.jsx new file mode 100644 index 0000000..56ac541 --- /dev/null +++ b/chess-game/app/webapp/src/components/charts.jsx @@ -0,0 +1,466 @@ +import { useMemo } from 'react'; +import { + barX, + barY, + defineChart, + differenceY, + dot, + linearRegressionY, + lineY, + ruleX, + ruleY, + text, +} from '@tanstack/charts'; +import { crosshair } from '@tanstack/charts/crosshair'; +import { motion } from '@tanstack/charts/motion'; +import { Chart } from '@tanstack/charts/react/core'; +import { scaleBand } from '@tanstack/charts/scales/band'; +import { scaleLinear } from '@tanstack/charts/scales/linear'; +import { tooltip } from '@tanstack/charts/tooltip'; +import { SEVERITY } from '../lib/insights.js'; + +// Every paint is a CSS variable, so the charts follow the light/dark toggle without being +// rebuilt. The two series hues follow the sides: gold for White (you, when playing), blue for +// Black (the engine). Validated per theme (adjacent CVD ΔE ≥ 23, normal-vision ΔE ≥ 24, ≥ 3:1 +// against the surface); the values live in index.css. +export const COLORS = { + white: 'var(--series-w)', + black: 'var(--series-b)', + ink: 'var(--ink)', + ink2: 'var(--ink-2)', + muted: 'var(--muted)', + grid: 'var(--grid)', + axis: 'var(--line)', +}; + +/** The series colour for a side: 'w' or 'b'. */ +export const sideColor = (color) => (color === 'b' ? COLORS.black : COLORS.white); + +const THEME = { + foreground: COLORS.muted, + muted: COLORS.muted, + grid: COLORS.grid, + background: 'transparent', + palette: [COLORS.white, COLORS.black], +}; + +/** + * Critically damped: settles without overshoot in about 0.35s. Stiffness and damping come from + * that response time, k = (2π / 0.35)² and c = 2√k. Springs are interruptible -- a chart that + * updates mid-animation carries its velocity into the new target instead of restarting -- which + * is what live data needs. Reduced-motion users get the final frame. + */ +const SPRING = { type: 'spring', stiffness: 322, damping: 35.9, mass: 1 }; + +export const fmt = (n, d = 1) => (Number.isFinite(n) ? n.toFixed(d) : '—'); +export const signed = (n, d = 1) => (Number.isFinite(n) ? `${n > 0 ? '+' : ''}${n.toFixed(d)}` : '—'); +export const pct = (n, d = 0) => (Number.isFinite(n) ? `${(n * 100).toFixed(d)}%` : '—'); + +const moveOfPly = (ply) => Math.max(1, Math.ceil(ply / 2)); + +/** Ply positions for x-axis ticks: whole moves, spaced to about six labels. */ +function moveTicks(lastPly) { + const moves = Math.max(1, Math.floor(lastPly / 2)); + const step = Math.max(1, Math.ceil(moves / 6)); + const ticks = []; + for (let m = step; m <= moves; m += step) ticks.push(m * 2); + return ticks.length ? ticks : [Math.min(2, lastPly)]; +} + +/** Every chart goes through here: one spring renderer per chart, shared sizing and labelling. */ +export function ChartView({ definition, height = 200, label, description, onSelect }) { + const renderer = useMemo(() => motion({ transition: SPRING }), []); + return ( + + ); +} + +const tip = (content) => ({ use: tooltip, className: 'chart-tip', content }); + +// ------------------------------------------------------------------------- evaluation + +/** + * The engine's evaluation across the game. Polarity is the story, so the fill is diverging -- + * blue where White stands better, red where Black does -- and the two lobes meet at the exact + * crossing rather than at the nearest sample. + */ +export function EvalChart({ points, current, onSeek, height = 210 }) { + const definition = useMemo(() => { + const rows = points.map((p, ply) => ({ ply, pawns: p?.pawns ?? null })); + const last = Math.max(1, rows.length - 1); + const peak = rows.reduce((m, r) => (r.pawns === null ? m : Math.max(m, Math.abs(r.pawns))), 0); + const span = Math.max(1.5, Math.min(12, Math.ceil(peak))); + + return defineChart({ + marks: [ + differenceY(rows, { + x: 'ply', + y1: 0, + y2: 'pawns', + positiveFill: COLORS.white, + negativeFill: COLORS.black, + fillOpacity: 0.2, + stroke: COLORS.ink, + strokeWidth: 1.75, + comparisonStroke: COLORS.axis, + comparisonStrokeWidth: 1, + }), + ruleX([Math.min(current, last)], { stroke: COLORS.ink, strokeOpacity: 0.35 }), + crosshair({ x: true, y: false }), + ], + scales: { + x: { + scale: scaleLinear().domain([0, last]), + // One tick per few full moves, on White's plies, so no move number appears twice. + axis: { line: false, ticks: { size: 0, values: moveTicks(last), format: (v) => String(v / 2) } }, + }, + y: { + scale: scaleLinear().domain([-span, span]), + grid: true, + axis: { line: false, ticks: { size: 0, count: 5, format: (v) => (v === 0 ? '0' : signed(v, span >= 4 ? 0 : 1)) } }, + }, + }, + theme: THEME, + focus: 'group-x', + maxFocusDistance: Number.POSITIVE_INFINITY, + tooltip: tip((group) => { + const line = group.find((p) => p.markId.endsWith(':primary')) ?? group[0]; + const pawns = line?.datum?.pawns; + const ply = line?.datum?.ply ?? 0; + return { + title: ply === 0 ? 'Start' : `After move ${moveOfPly(ply)}${ply % 2 ? '' : '…'}`, + rows: [ + { + label: 'Evaluation', + value: Number.isFinite(pawns) ? `${signed(pawns, 2)} pawns` : 'not evaluated yet', + color: pawns < 0 ? COLORS.black : COLORS.white, + }, + ], + }; + }), + }); + }, [points, current]); + + return ( + Number.isInteger(point?.datum?.ply) && onSeek?.(point.datum.ply)} + /> + ); +} + +// ------------------------------------------------------------------------- cost of each move + +/** + * Win chance thrown away by each move, with the three thresholds that name a bad one drawn as + * reference lines -- labelled, so the meaning never rests on colour. + */ +export function WinLostChart({ rows, current, onSeek, height = 190 }) { + const definition = useMemo(() => { + const judged = rows.filter((r) => r.winLost !== null); + const lastMove = Math.max(1, ...rows.map((r) => r.moveNo)); + const top = Math.max(36, Math.ceil((Math.max(0, ...judged.map((r) => r.winLost)) + 4) / 5) * 5); + const thresholds = SEVERITY.map((s) => ({ value: s.min, label: s.label })); + + return defineChart({ + marks: [ + ruleY(thresholds, { y: 'value', stroke: COLORS.axis, strokeOpacity: 1 }), + text(thresholds, { + x: () => 0.5, + y: 'value', + text: 'label', + anchor: 'start', + dx: 4, + dy: -5, + fontSize: 10, + fill: COLORS.muted, + }), + barY(judged, { + x: 'moveNo', + y: 'winLost', + fill: (r) => (r.ply === current ? COLORS.ink : sideColor(r.color)), + radius: 4, + maxThickness: 8, + }), + ], + scales: { + x: { + scale: scaleLinear().domain([0.5, lastMove + 0.5]), + axis: { line: false, ticks: { size: 0, count: 6, format: (v) => (Number.isInteger(v) ? String(v) : '') } }, + }, + y: { + scale: scaleLinear().domain([0, top]), + grid: true, + axis: { line: false, ticks: { size: 0, count: 4, format: (v) => `${v}%` } }, + }, + }, + theme: THEME, + focus: 'nearest-x', + tooltip: tip(([point]) => { + const r = point?.datum; + if (!r) return { rows: [] }; + return { + title: r.label, + rows: [ + { label: 'Win chance lost', value: `${fmt(r.winLost, 1)} pts`, color: sideColor(r.color) }, + { label: 'Pawns lost', value: fmt(r.pawnsLost, 2) }, + { label: 'Accuracy', value: `${fmt(r.accuracy, 0)}%` }, + ...(r.severity ? [{ label: 'Verdict', value: SEVERITY.find((s) => s.key === r.severity).label }] : []), + ...(r.engineBest && !r.matched ? [{ label: 'Engine preferred', value: r.engineBest }] : []), + ], + }; + }), + }); + }, [rows, current]); + + return ( + Number.isInteger(point?.datum?.ply) && onSeek?.(point.datum.ply)} + /> + ); +} + +// ------------------------------------------------------------------------- surprise and entropy + +/** + * How open each choice was (entropy, the line) against how unexpected the move played was + * (surprise, the bars). Both are bits, so they honestly share one axis. + */ +export function ThinkingChart({ rows, current, onSeek, height = 190 }) { + const definition = useMemo(() => { + const scored = rows.filter((r) => r.surprisal !== null); + const lastMove = Math.max(1, ...rows.map((r) => r.moveNo)); + const top = Math.max(4, Math.ceil(Math.max(0, ...scored.map((r) => Math.max(r.surprisal, r.entropy))))); + + return defineChart({ + marks: [ + barY(scored, { + id: 'surprise', + x: 'moveNo', + y: 'surprisal', + fill: (r) => (r.ply === current ? COLORS.ink : sideColor(r.color)), + radius: 4, + maxThickness: 8, + }), + lineY(scored, { id: 'entropy', x: 'moveNo', y: 'entropy', stroke: COLORS.ink, strokeWidth: 1.75 }), + crosshair({ x: true, y: false }), + ], + scales: { + x: { + scale: scaleLinear().domain([0.5, lastMove + 0.5]), + axis: { line: false, ticks: { size: 0, count: 6, format: (v) => (Number.isInteger(v) ? String(v) : '') } }, + }, + y: { + scale: scaleLinear().domain([0, top]), + grid: true, + axis: { line: false, ticks: { size: 0, count: 4, format: (v) => `${v} b` } }, + }, + }, + theme: THEME, + focus: 'group-x', + maxFocusDistance: Number.POSITIVE_INFINITY, + tooltip: tip((group) => { + const r = group[0]?.datum; + if (!r) return { rows: [] }; + return { + title: r.label, + rows: [ + { label: 'Surprise', value: `${fmt(r.surprisal, 2)} bits`, color: sideColor(r.color) }, + { label: 'Entropy', value: `${fmt(r.entropy, 2)} bits`, color: COLORS.ink }, + { label: 'Model rank', value: r.rank ? `${r.rank} of ${r.branching}` : '—' }, + { label: 'Model probability', value: pct(r.pPlayed, 1) }, + ], + }; + }), + }); + }, [rows, current]); + + return ( + Number.isInteger(point?.datum?.ply) && onSeek?.(point.datum.ply)} + /> + ); +} + +// ------------------------------------------------------------------------- complexity + +/** How many legal moves each side had to choose from, move by move: where the game got sharp. */ +export function ComplexityChart({ decisions, height = 170 }) { + const definition = useMemo(() => { + const rows = decisions + .map((d, ply) => (d ? { ply, moveNo: moveOfPly(ply + 1), side: d.color === 'w' ? 'White' : 'Black', options: d.branching } : null)) + .filter(Boolean); + const last = Math.max(1, ...rows.map((r) => r.moveNo)); + + return defineChart({ + marks: [ + lineY(rows, { + x: 'moveNo', + y: 'options', + z: 'side', + stroke: (r) => (r.side === 'White' ? COLORS.white : COLORS.black), + strokeWidth: 1.75, + }), + crosshair({ x: true, y: false }), + ], + scales: { + x: { + scale: scaleLinear().domain([1, Math.max(2, last)]), + axis: { line: false, ticks: { size: 0, count: 6, format: (v) => (Number.isInteger(v) ? String(v) : '') } }, + }, + y: { scale: scaleLinear, nice: true, grid: true, axis: { line: false, ticks: { size: 0, count: 4 } } }, + }, + theme: THEME, + focus: 'group-x', + maxFocusDistance: Number.POSITIVE_INFINITY, + tooltip: tip((group) => ({ + title: `Move ${group[0]?.datum?.moveNo ?? ''}`, + rows: group.map((p) => ({ + label: `${p.datum.side} to move`, + value: `${p.datum.options} options`, + color: p.datum.side === 'White' ? COLORS.white : COLORS.black, + })), + })), + }); + }, [decisions]); + + return ( + + ); +} + +// ------------------------------------------------------------------------- the choice now + +/** The policy's probability for each candidate move, best first, with the move played marked. */ +export function PolicyChart({ rows, height, accent = COLORS.white }) { + const definition = useMemo(() => { + const peak = Math.max(0.01, ...rows.map((r) => r.p)); + return defineChart({ + marks: [ + barX(rows, { + id: 'track', + y: 'san', + x: () => peak * 1.22, + fill: COLORS.axis, + fillOpacity: 0.35, + radius: 4, + maxThickness: 8, + }), + barX(rows, { + id: 'probability', + y: 'san', + x: 'p', + fill: (r) => (r.played ? accent : COLORS.ink), + radius: 4, + maxThickness: 8, + }), + text(rows, { + y: 'san', + x: 'p', + text: (r) => `${(r.p * 100).toFixed(1)}%`, + anchor: 'start', + dx: 6, + fontSize: 11, + fill: COLORS.ink2, + }), + ], + scales: { + x: { scale: scaleLinear().domain([0, peak * 1.22]), axis: false }, + y: { scale: () => scaleBand().padding(0.3), axis: { line: false, ticks: { size: 0 } } }, + }, + theme: THEME, + focus: 'nearest-y', + tooltip: tip(([point]) => { + const r = point?.datum; + if (!r) return { rows: [] }; + return { + title: r.played ? `${r.san} · played` : r.san, + rows: [ + { label: 'Probability', value: pct(r.p, 1), color: r.played ? accent : COLORS.muted }, + { label: 'Model value', value: `${signed(r.v, 2)} pawns` }, + ], + }; + }), + }); + }, [rows, accent]); + + return ( + + ); +} + +// ------------------------------------------------------------------------- calibration + +/** The local model's value against the engine's, position by position, with the fitted line. */ +export function CalibrationChart({ pairs, height = 210 }) { + const definition = useMemo(() => { + const rows = pairs.map(([model, engine], i) => ({ i, model, engine })); + const clamp = (v) => Math.max(-8, Math.min(8, v)); + const clamped = rows.map((r) => ({ ...r, model: clamp(r.model), engine: clamp(r.engine) })); + return defineChart({ + marks: [ + ruleX([0], { stroke: COLORS.axis, strokeOpacity: 1 }), + ruleY([0], { stroke: COLORS.axis, strokeOpacity: 1 }), + linearRegressionY(clamped, { + x: 'model', + y: 'engine', + stroke: COLORS.ink, + strokeWidth: 1.5, + fill: COLORS.ink, + fillOpacity: 0.06, + }), + dot(clamped, { x: 'model', y: 'engine', r: 3.5, fill: COLORS.black, fillOpacity: 0.7 }), + ], + scales: { + x: { scale: scaleLinear, nice: true, axis: { line: false, label: 'Model (pawns)', ticks: { size: 0, count: 5 } } }, + y: { scale: scaleLinear, nice: true, grid: true, axis: { line: false, label: 'Engine (pawns)', ticks: { size: 0, count: 5 } } }, + }, + theme: THEME, + tooltip: tip(([point]) => ({ + title: 'Position', + rows: [ + { label: 'Model', value: `${signed(point?.datum?.model, 2)} pawns`, color: COLORS.black }, + { label: 'Engine', value: `${signed(point?.datum?.engine, 2)} pawns` }, + ], + })), + }); + }, [pairs]); + + return ( + + ); +} diff --git a/chess-game/app/webapp/src/components/ui.jsx b/chess-game/app/webapp/src/components/ui.jsx new file mode 100644 index 0000000..d6cc92d --- /dev/null +++ b/chess-game/app/webapp/src/components/ui.jsx @@ -0,0 +1,231 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; + +/** State that survives a reload. Falls back to plain state where storage is unavailable. */ +export function usePersistentState(key, initial) { + const [value, setValue] = useState(() => { + try { + const stored = localStorage.getItem(key); + return stored === null ? initial : JSON.parse(stored); + } catch { + return initial; + } + }); + const set = useCallback( + (next) => { + setValue((current) => { + const resolved = typeof next === 'function' ? next(current) : next; + try { + localStorage.setItem(key, JSON.stringify(resolved)); + } catch { + // Private window or storage blocked: the choice lasts for this visit only. + } + return resolved; + }); + }, + [key] + ); + return [value, set]; +} + +/** + * A segmented control whose highlight slides to the chosen option. The pill moves by transform + * and follows the option's measured width, so it lands exactly on the label at any font size. + */ +export function Segmented({ options, value, onChange, label, size = 'md' }) { + const host = useRef(null); + const buttons = useRef({}); + const [pill, setPill] = useState(null); + + const measure = useCallback(() => { + const el = buttons.current[value]; + if (el) setPill({ x: el.offsetLeft, width: el.offsetWidth }); + }, [value]); + + useLayoutEffect(measure, [measure, options]); + useEffect(() => { + if (!host.current) return; + const ro = new ResizeObserver(measure); + ro.observe(host.current); + return () => ro.disconnect(); + }, [measure]); + + return ( +
+ {pill && ( +
+ ); +} + +function Chevron() { + return ( + + ); +} + +/** + * A section that folds away. The body collapses by animating its grid row from 1fr to 0fr: no + * measured heights, no layout thrash, and a CSS transition, so opening and closing in quick + * succession reverses smoothly instead of restarting. Whether it is open is remembered. + */ +export function Section({ id, title, meta, defaultOpen = true, actions, children }) { + const [open, setOpen] = usePersistentState(`section:${id}`, defaultOpen); + const bodyId = `section-${id}`; + return ( +
+
+ + {actions &&
{actions}
} +
+
+
{children}
+
+
+ ); +} + +export function Skeleton({ width = '100%', height = '1em', radius = 6 }) { + return