Microchess
Self-contained PHP 8.2+ application. Set the document root to this web/ directory. No Composer, Node, build step or files outside this directory are required in production.
Run locally
From the repository root:
php -S 127.0.0.1:8080 -t web web/router.php
Open http://127.0.0.1:8080. You are automatically signed in as test_user_1. Account → Switch to test_user_2 switches accounts. Use a second browser profile or private window for two independent sessions. Test accounts are created on first use, with no fabricated friends or games.
Autologin works with PHP's development server, Apache and PHP-FPM. It requires both a loopback client IP and a localhost/loopback Host header; public domains do not enable test accounts. A previous OAuth session on localhost is replaced with test_user_1; a selected test account remains selected. Do not expose the local development site through a public proxy.
Production
Requirements: PHP 8.2+, PDO SQLite, cURL, writable web/data/, and HTTPS. All application writes (database, SQLite WAL/SHM, sessions and application error log) remain under web/data/. Session contents, games, move histories, invitations, friendships and results are stored in SQLite. The app does not write to a system temporary or session directory.
On the first page request, the app creates web/data/config.php with empty base_url, client_id and client_secret fields if the file does not exist. Existing files are never overwritten. This file is ignored by Git and excluded from deployment with the rest of data/. Fill it in on each server, for example:
<?php
return [
'base_url' => 'https://your-chess-domain.example',
'client_id' => 'your-registered-domain.example',
'client_secret' => 'your-client-secret',
];
Environment equivalents: MICROCHESS_BASE_URL, MICROCHESS_CLIENT_ID, MICROCHESS_CLIENT_SECRET. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash.
Register your client domain and /callback.php (or /subdirectory/callback.php) in the auth service admin. Integration follows the service's integration guide: state validation, server-side code exchange, /api/me validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after 24 hours of inactivity (sliding on activity). OAuth itself requires the real registered client credentials to test.
Apache: enable AllowOverride All for this directory so the included .htaccess files deny access to data/, lib/ and tests/, and disable directory listings. Nginx does not read .htaccess; add equivalent deny rules before your PHP location and adjust the prefix if mounted in a subdirectory:
location ~* ^/(data|lib|tests)(/|$) { deny all; }
location ~ /\. { deny all; }
location ~* ^/(README\.md|router\.php)$ { deny all; }
Use a normal PHP-FPM configuration that only executes existing PHP files. Verify that /data/microchess.sqlite, /data/config.php and /lib/bootstrap.php return 403 before putting real data in the app. Only the PHP user should have filesystem write access to data/.
Deploy this directory's contents. Preserve the entire production data/ directory: exclude data/ itself and all descendants from upload and deletion, including config.php, .htaccess, the database and WAL files. The included CI script creates data/ and installs its .htaccess separately before mirroring; do the same when deploying manually. Never upload your development database or tests/artifacts/. The root .gitlab-ci.yml runs PHP syntax, chess/API tests, JavaScript syntax checks and an isolated FTP deployment test before deploying master. Deployments are serialized with a production resource group. FTP credentials are passed to lftp through its password environment variable; FTP TLS certificate verification is disabled for this hosting account, as configured by the owner.
SQLite supports a single application instance with concurrent requests; writes use BEGIN IMMEDIATE, game versions reject stale actions, and invitation acceptance is atomic. Keep the database on local persistent storage. Use SQLite's backup API for live backups; copying just the .sqlite file while WAL is active can miss transactions.
Game behavior
Initial position, viewed from White:
5 k n b r
4 p . . .
3 . . . .
2 . . . P
1 R B N K
a b c d
White moves first. Pawns move one square, never double-step; there is no castling or en passant. Promotion is mandatory to queen, rook, bishop or knight. The server generates legal moves and checks king safety. Checkmate and stalemate are evaluated after every move. Standard insufficient material positions (bare kings, lone bishop/knight, only bishops on one square color) draw automatically. Threefold repetition and the 50-move rule can be claimed from the game menu, including using an intended legal move; fivefold repetition and 75 moves are automatic, with checkmate taking precedence. A draw can also be offered or the game resigned from your turn's menu.
The top grid includes your moves, incoming challenges and finished games that still need Rematch or Exit. After you request a rematch, that tile moves to the lower grid while you wait. Opponent-turn games and sent challenges are noninteractive in the lower grid. Boards orient toward your color. Polling updates the other player every 2.5 seconds while the tab is visible. No clocks or timeouts are applied to games.
A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect.
Click an opponent's name above a game to open the same rivalry statistics shown from the friends list. Non-friends can send a friend request; incoming requests appear below the friends list with Accept/Reject controls. Requests persist across sessions, and only the recipient can accept or reject them. Acceptance adds both players to each other's friends lists. Duplicate requests do not create extra entries; accepting a friend invitation link also clears any pending request between those players. Pending requests are included in data exports.
Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. Account → Export my data (JSON) exports the user's profile, relationships, invitations, games and historical results.
Ratings and matchmaking
Existing and new accounts start at 1200 Elo. Results completed after this update use Elo with K=32 (win 1, draw 0.5, loss 0), rounded to whole points with equal and opposite changes. Past results are preserved without retroactive rating changes. All completed games count, including friend challenges, match links and rematches. Stopped unfinished games do not count. Ratings and a per-result ledger are written in the same transaction as the result; rematches reuse a tile but get their own result and rating change. Ratings appear in the account summary, friends list and opponent headers, and rating history is included in data exports.
New game → Challenge a random player adds one persistent search per account, with cancellation and retry after expiry. Searches last 24 hours, including while offline. Joining immediately checks the entire pool; authenticated state requests otherwise trigger a transactionally throttled check at most once per minute. There is no background worker. Each player's allowed difference starts at 100, grows by 50 per elapsed minute and stops at 500. Both players must allow the difference. The oldest search selects its closest eligible opponent (ties prefer older searches), then processing continues through the remaining pool. Pairing creates one active game with random colors and consumes both entries atomically. Expired entries cannot match and display a retry option. A match does not create a friendship.
The integration tests exercise rating updates, rematches, duplicate results, concurrent joins, cancellation, expiry, widening, the maximum difference and whole-pool matching. Browser tests cover joining from below the invite link, persistence after reload, cancellation, automatic game appearance and visible ratings.
Avatars
Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 91 selected avatars: 67 fairy pieces and 24 colored standard pieces. Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The user_avatars table is created automatically, preserving existing accounts and game data.
Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in avatar credits and assets/avatars/catalog.json. There are no runtime requests to Wikimedia.
Checks
From the repository root:
find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
php web/tests/chess.php
php web/tests/feedback.php
python3 web/tests/startup.py
python3 web/tests/integration.py
node --check web/assets/app.js
Engine tests cover movement, pins, king safety, promotions, endings, draw thresholds and deterministic random games. API tests start an isolated copy under web/tests/artifacts/, covering two sessions, CSRF, invitations, bilateral friendship, turn enforcement, stale actions, rematches, statistics, export and protected paths. They run four PHP workers, verify concurrent link acceptance, remove the isolated copy afterwards and never touch the real database.
Optional real-browser tests (requires Node.js):
npm install --prefix web/tests/artifacts --no-audit --no-fund playwright
PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" web/tests/artifacts/node_modules/.bin/playwright install chromium
PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" node web/tests/browser.mjs
These cover click, mouse drag, touch drag, promotion, rematch, friendships, desktop and mobile layouts. Screenshots are written under web/tests/artifacts/; the application copy and its database are discarded.
Piece credits
Unmodified Chess_{piece}{l|d}t45.svg images by Cburnett, downloaded from Wikimedia Commons, used under Creative Commons Attribution-ShareAlike 3.0. See asset credits for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows Green Chess.
Inactive games and final positions
Ended games retain the final board and move highlights, with a transparent result bar that becomes readable on hover or keyboard focus. Touch devices show readable controls immediately. After seven days without game activity, either player can confirm removal of both tiles. Existing result history is retained; stopping an unfinished game awards no result. Activity tracking begins at deployment for existing games because earlier move timestamps were not stored.
Move feedback
Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:
php -S 127.0.0.1:8080 -t web web/router.php
After your successfully submitted move, the game tile briefly pulses blue for a clear estimated gain or red for a likely material loss / mating threat. Quiet positions, small differences, drawn endings and inconclusive analysis get no pulse. There is no yellow “perfect move” verdict. The pulse lasts 1.8 seconds during the existing three-second tile pause, appears only to the player who made the move, and does not replay on polling, selection or reload. Reduced-motion users get a temporary static indication.
The bar under the opponent’s name compares remaining material, with White always on the left and Black on the right. Values are pawn 1, knight/bishop 3, rook 5 and queen 9; kings do not contribute. Each color occupies its share of the combined value (e.g. White 10 vs Black 5 gives White two thirds). Bare kings give a neutral 50/50 bar. Captures and promotions update the ratio with a 650 ms transition, including on opponent polling updates; reduced-motion users see the new value immediately. This calculation only counts the twenty board squares in the browser and performs no chess search. Hover or focus the bar for the material totals.
lib/MoveFeedback.php compares material before the move with a short tactical evaluation after it. It considers the opponent's best reply, your response, and up to two additional plies of captures/promotions; checks may extend the search by up to two further evasions. All moves use the same legal move generation, promotion and king-safety rules as the game. Checkmate, stalemate, insufficient material, automatic draws and available draw claims are handled. Claimable positions receive no move-only grade.
Values are pawn 100, knight/bishop 300, rook 500 and queen 900. A change of at least 100 triggers a pulse; visible mating lines also trigger a pulse. Captures are followed through likely recaptures so an equal exchange is not rewarded halfway through. This is a material/tactics estimate, not a best-move ranking, perfect-play verdict or distance-to-mate calculation. It can miss deeper sacrifices, positional improvements and distant threats, and may flag a loss that was already unavoidable.
Analysis runs after the game transaction and session writes finish, with a 200 ms / 8,000-node budget. It never rolls back a saved move. If the budget expires or a check remains unresolved at the search limit, it returns no grade. The compute limit is checked between nodes; operating-system scheduling and network latency are outside it. The API reports the grade, reason, node count and elapsed milliseconds in the move response for local inspection. Polling performs no analysis and transmits no position evaluations.
Previous offline solver code is removed. Any existing .tablebase/ work files and web/lib/tablebase/ data remain untouched and ignored by Git; the app no longer uses them.
Checks:
php web/tests/chess.php
php web/tests/feedback.php
python3 web/tests/integration.py
node web/tests/browser.mjs
The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy.
Saved games
Games newly entering Your turn go to the end of the queue; the ordering survives reloads. The account summary’s hourglass opens finished games, newest first, showing opponent, outcome and end date. Both players retain access after exiting a tile or starting a rematch. Replay uses the same board orientation and tile styling, with jump-to-start, step back, play/pause, step forward and jump-to-end controls. Play/Pause advances every 500 ms. Closing the dialog stops playback. A saved result animates once per player/browser toward the hourglass; reduced-motion preferences suppress motion.
Replays store the initial position plus two binary bytes per ply, including promotions, separately from permanent result/rating statistics. Saved games have no retention limit and are not automatically deleted based on age. Existing finished tiles can be imported when their original color and complete history are still available. Older rematches whose color was overwritten cannot be reconstructed reliably and are not imported. Data exports include available replay positions. No scheduled worker is required.
The replay footer’s chain icon copies a permanent link with an unguessable token. Anyone with that link can view and play back that one game, signed in or not. Shared links open a standalone replay page containing only the tile and playback/share controls, with no modal, close button or surrounding application interface, plus a Microchess link back to the home page. Replay headers identify White and Black with their king icons; transport buttons use jump-to-start, rewind, play/pause, fast-forward and jump-to-end icons with accessible labels. Public replay responses include player names and game positions, not account IDs or private history. Invalid tokens return 404.
Source
| 1 | # Microchess |
| 2 | |
| 3 | Self-contained PHP 8.2+ application. Set the document root to this `web/` directory. No Composer, Node, build step or files outside this directory are required in production. |
| 4 | |
| 5 | ## Run locally |
| 6 | |
| 7 | From the repository root: |
| 8 | |
| 9 | ```sh |
| 10 | php -S 127.0.0.1:8080 -t web web/router.php |
| 11 | ``` |
| 12 | |
| 13 | Open http://127.0.0.1:8080. You are automatically signed in as `test_user_1`. **Account → Switch to test_user_2** switches accounts. Use a second browser profile or private window for two independent sessions. Test accounts are created on first use, with no fabricated friends or games. |
| 14 | |
| 15 | Autologin works with PHP's development server, Apache and PHP-FPM. It requires both a loopback client IP and a localhost/loopback Host header; public domains do not enable test accounts. A previous OAuth session on localhost is replaced with `test_user_1`; a selected test account remains selected. Do not expose the local development site through a public proxy. |
| 16 | |
| 17 | ## Production |
| 18 | |
| 19 | Requirements: PHP 8.2+, PDO SQLite, cURL, writable `web/data/`, and HTTPS. All application writes (database, SQLite WAL/SHM, sessions and application error log) remain under `web/data/`. Session contents, games, move histories, invitations, friendships and results are stored in SQLite. The app does not write to a system temporary or session directory. |
| 20 | |
| 21 | On the first page request, the app creates `web/data/config.php` with empty `base_url`, `client_id` and `client_secret` fields if the file does not exist. Existing files are never overwritten. This file is ignored by Git and excluded from deployment with the rest of `data/`. Fill it in on each server, for example: |
| 22 | |
| 23 | ```php |
| 24 | <?php |
| 25 | return [ |
| 26 | 'base_url' => 'https://your-chess-domain.example', |
| 27 | 'client_id' => 'your-registered-domain.example', |
| 28 | 'client_secret' => 'your-client-secret', |
| 29 | ]; |
| 30 | ``` |
| 31 | |
| 32 | Environment equivalents: `MICROCHESS_BASE_URL`, `MICROCHESS_CLIENT_ID`, `MICROCHESS_CLIENT_SECRET`. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash. |
| 33 | |
| 34 | Register your client domain and `/callback.php` (or `/subdirectory/callback.php`) in the [auth service admin](https://auth.timfalken.com/admin). Integration follows the service's [integration guide](https://auth.timfalken.com/help): state validation, server-side code exchange, `/api/me` validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after 24 hours of inactivity (sliding on activity). OAuth itself requires the real registered client credentials to test. |
| 35 | |
| 36 | Apache: enable `AllowOverride All` for this directory so the included `.htaccess` files deny access to `data/`, `lib/` and `tests/`, and disable directory listings. Nginx does not read `.htaccess`; add equivalent deny rules **before** your PHP location and adjust the prefix if mounted in a subdirectory: |
| 37 | |
| 38 | ```nginx |
| 39 | location ~* ^/(data|lib|tests)(/|$) { deny all; } |
| 40 | location ~ /\. { deny all; } |
| 41 | location ~* ^/(README\.md|router\.php)$ { deny all; } |
| 42 | ``` |
| 43 | |
| 44 | Use a normal PHP-FPM configuration that only executes existing PHP files. Verify that `/data/microchess.sqlite`, `/data/config.php` and `/lib/bootstrap.php` return 403 before putting real data in the app. Only the PHP user should have filesystem write access to `data/`. |
| 45 | |
| 46 | Deploy this directory's contents. Preserve the entire production `data/` directory: exclude `data/` itself and all descendants from upload **and deletion**, including `config.php`, `.htaccess`, the database and WAL files. The included CI script creates `data/` and installs its `.htaccess` separately before mirroring; do the same when deploying manually. Never upload your development database or `tests/artifacts/`. The root `.gitlab-ci.yml` runs PHP syntax, chess/API tests, JavaScript syntax checks and an isolated FTP deployment test before deploying `master`. Deployments are serialized with a production resource group. FTP credentials are passed to lftp through its password environment variable; FTP TLS certificate verification is disabled for this hosting account, as configured by the owner. |
| 47 | |
| 48 | SQLite supports a single application instance with concurrent requests; writes use `BEGIN IMMEDIATE`, game versions reject stale actions, and invitation acceptance is atomic. Keep the database on local persistent storage. Use SQLite's backup API for live backups; copying just the `.sqlite` file while WAL is active can miss transactions. |
| 49 | |
| 50 | ## Game behavior |
| 51 | |
| 52 | Initial position, viewed from White: |
| 53 | |
| 54 | ```text |
| 55 | 5 k n b r |
| 56 | 4 p . . . |
| 57 | 3 . . . . |
| 58 | 2 . . . P |
| 59 | 1 R B N K |
| 60 | a b c d |
| 61 | ``` |
| 62 | |
| 63 | White moves first. Pawns move one square, never double-step; there is no castling or en passant. Promotion is mandatory to queen, rook, bishop or knight. The server generates legal moves and checks king safety. Checkmate and stalemate are evaluated after every move. Standard insufficient material positions (bare kings, lone bishop/knight, only bishops on one square color) draw automatically. Threefold repetition and the 50-move rule can be claimed from the game menu, including using an intended legal move; fivefold repetition and 75 moves are automatic, with checkmate taking precedence. A draw can also be offered or the game resigned from your turn's menu. |
| 64 | |
| 65 | The top grid includes your moves, incoming challenges and finished games that still need Rematch or Exit. After you request a rematch, that tile moves to the lower grid while you wait. Opponent-turn games and sent challenges are noninteractive in the lower grid. Boards orient toward your color. Polling updates the other player every 2.5 seconds while the tab is visible. No clocks or timeouts are applied to games. |
| 66 | |
| 67 | A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect. |
| 68 | |
| 69 | Click an opponent's name above a game to open the same rivalry statistics shown from the friends list. Non-friends can send a friend request; incoming requests appear below the friends list with Accept/Reject controls. Requests persist across sessions, and only the recipient can accept or reject them. Acceptance adds both players to each other's friends lists. Duplicate requests do not create extra entries; accepting a friend invitation link also clears any pending request between those players. Pending requests are included in data exports. |
| 70 | |
| 71 | Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. **Account → Export my data (JSON)** exports the user's profile, relationships, invitations, games and historical results. |
| 72 | |
| 73 | ## Ratings and matchmaking |
| 74 | |
| 75 | Existing and new accounts start at 1200 Elo. Results completed after this update use Elo with K=32 (win 1, draw 0.5, loss 0), rounded to whole points with equal and opposite changes. Past results are preserved without retroactive rating changes. All completed games count, including friend challenges, match links and rematches. Stopped unfinished games do not count. Ratings and a per-result ledger are written in the same transaction as the result; rematches reuse a tile but get their own result and rating change. Ratings appear in the account summary, friends list and opponent headers, and rating history is included in data exports. |
| 76 | |
| 77 | **New game → Challenge a random player** adds one persistent search per account, with cancellation and retry after expiry. Searches last 24 hours, including while offline. Joining immediately checks the entire pool; authenticated state requests otherwise trigger a transactionally throttled check at most once per minute. There is no background worker. Each player's allowed difference starts at 100, grows by 50 per elapsed minute and stops at 500. Both players must allow the difference. The oldest search selects its closest eligible opponent (ties prefer older searches), then processing continues through the remaining pool. Pairing creates one active game with random colors and consumes both entries atomically. Expired entries cannot match and display a retry option. A match does not create a friendship. |
| 78 | |
| 79 | The integration tests exercise rating updates, rematches, duplicate results, concurrent joins, cancellation, expiry, widening, the maximum difference and whole-pool matching. Browser tests cover joining from below the invite link, persistence after reload, cancellation, automatic game appearance and visible ratings. |
| 80 | |
| 81 | ## Avatars |
| 82 | |
| 83 | Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 91 selected avatars: 67 fairy pieces and 24 colored standard pieces. Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data. |
| 84 | |
| 85 | Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in [avatar credits](assets/avatars/CREDITS.md) and `assets/avatars/catalog.json`. There are no runtime requests to Wikimedia. |
| 86 | |
| 87 | ## Checks |
| 88 | |
| 89 | From the repository root: |
| 90 | |
| 91 | ```sh |
| 92 | find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l |
| 93 | php web/tests/chess.php |
| 94 | php web/tests/feedback.php |
| 95 | python3 web/tests/startup.py |
| 96 | python3 web/tests/integration.py |
| 97 | node --check web/assets/app.js |
| 98 | ``` |
| 99 | |
| 100 | Engine tests cover movement, pins, king safety, promotions, endings, draw thresholds and deterministic random games. API tests start an isolated copy under `web/tests/artifacts/`, covering two sessions, CSRF, invitations, bilateral friendship, turn enforcement, stale actions, rematches, statistics, export and protected paths. They run four PHP workers, verify concurrent link acceptance, remove the isolated copy afterwards and never touch the real database. |
| 101 | |
| 102 | Optional real-browser tests (requires Node.js): |
| 103 | |
| 104 | ```sh |
| 105 | npm install --prefix web/tests/artifacts --no-audit --no-fund playwright |
| 106 | PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" web/tests/artifacts/node_modules/.bin/playwright install chromium |
| 107 | PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" node web/tests/browser.mjs |
| 108 | ``` |
| 109 | |
| 110 | These cover click, mouse drag, touch drag, promotion, rematch, friendships, desktop and mobile layouts. Screenshots are written under `web/tests/artifacts/`; the application copy and its database are discarded. |
| 111 | |
| 112 | ## Piece credits |
| 113 | |
| 114 | Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces), used under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/). See [asset credits](assets/pieces/CREDITS.md) for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows [Green Chess](https://greenchess.net/rules.php?v=microchess). |
| 115 | |
| 116 | ## Inactive games and final positions |
| 117 | |
| 118 | Ended games retain the final board and move highlights, with a transparent result bar that becomes readable on hover or keyboard focus. Touch devices show readable controls immediately. After seven days without game activity, either player can confirm removal of both tiles. Existing result history is retained; stopping an unfinished game awards no result. Activity tracking begins at deployment for existing games because earlier move timestamps were not stored. |
| 119 | |
| 120 | ## Move feedback |
| 121 | |
| 122 | Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed: |
| 123 | |
| 124 | ```sh |
| 125 | php -S 127.0.0.1:8080 -t web web/router.php |
| 126 | ``` |
| 127 | |
| 128 | After your successfully submitted move, the game tile briefly pulses blue for a clear estimated gain or red for a likely material loss / mating threat. Quiet positions, small differences, drawn endings and inconclusive analysis get no pulse. There is no yellow “perfect move” verdict. The pulse lasts 1.8 seconds during the existing three-second tile pause, appears only to the player who made the move, and does not replay on polling, selection or reload. Reduced-motion users get a temporary static indication. |
| 129 | |
| 130 | The bar under the opponent’s name compares remaining material, with White always on the left and Black on the right. Values are pawn 1, knight/bishop 3, rook 5 and queen 9; kings do not contribute. Each color occupies its share of the combined value (e.g. White 10 vs Black 5 gives White two thirds). Bare kings give a neutral 50/50 bar. Captures and promotions update the ratio with a 650 ms transition, including on opponent polling updates; reduced-motion users see the new value immediately. This calculation only counts the twenty board squares in the browser and performs no chess search. Hover or focus the bar for the material totals. |
| 131 | |
| 132 | `lib/MoveFeedback.php` compares material before the move with a short tactical evaluation after it. It considers the opponent's best reply, your response, and up to two additional plies of captures/promotions; checks may extend the search by up to two further evasions. All moves use the same legal move generation, promotion and king-safety rules as the game. Checkmate, stalemate, insufficient material, automatic draws and available draw claims are handled. Claimable positions receive no move-only grade. |
| 133 | |
| 134 | Values are pawn 100, knight/bishop 300, rook 500 and queen 900. A change of at least 100 triggers a pulse; visible mating lines also trigger a pulse. Captures are followed through likely recaptures so an equal exchange is not rewarded halfway through. This is a material/tactics estimate, not a best-move ranking, perfect-play verdict or distance-to-mate calculation. It can miss deeper sacrifices, positional improvements and distant threats, and may flag a loss that was already unavoidable. |
| 135 | |
| 136 | Analysis runs after the game transaction and session writes finish, with a 200 ms / 8,000-node budget. It never rolls back a saved move. If the budget expires or a check remains unresolved at the search limit, it returns no grade. The compute limit is checked between nodes; operating-system scheduling and network latency are outside it. The API reports the grade, reason, node count and elapsed milliseconds in the move response for local inspection. Polling performs no analysis and transmits no position evaluations. |
| 137 | |
| 138 | Previous offline solver code is removed. Any existing `.tablebase/` work files and `web/lib/tablebase/` data remain untouched and ignored by Git; the app no longer uses them. |
| 139 | |
| 140 | Checks: |
| 141 | |
| 142 | ```sh |
| 143 | php web/tests/chess.php |
| 144 | php web/tests/feedback.php |
| 145 | python3 web/tests/integration.py |
| 146 | node web/tests/browser.mjs |
| 147 | ``` |
| 148 | |
| 149 | The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy. |
| 150 | |
| 151 | ## Saved games |
| 152 | |
| 153 | Games newly entering Your turn go to the end of the queue; the ordering survives reloads. The account summary’s hourglass opens finished games, newest first, showing opponent, outcome and end date. Both players retain access after exiting a tile or starting a rematch. Replay uses the same board orientation and tile styling, with jump-to-start, step back, play/pause, step forward and jump-to-end controls. Play/Pause advances every 500 ms. Closing the dialog stops playback. A saved result animates once per player/browser toward the hourglass; reduced-motion preferences suppress motion. |
| 154 | |
| 155 | Replays store the initial position plus two binary bytes per ply, including promotions, separately from permanent result/rating statistics. Saved games have no retention limit and are not automatically deleted based on age. Existing finished tiles can be imported when their original color and complete history are still available. Older rematches whose color was overwritten cannot be reconstructed reliably and are not imported. Data exports include available replay positions. No scheduled worker is required. |
| 156 | |
| 157 | The replay footer’s chain icon copies a permanent link with an unguessable token. Anyone with that link can view and play back that one game, signed in or not. Shared links open a standalone replay page containing only the tile and playback/share controls, with no modal, close button or surrounding application interface, plus a Microchess link back to the home page. Replay headers identify White and Black with their king icons; transport buttons use jump-to-start, rewind, play/pause, fast-forward and jump-to-end icons with accessible labels. Public replay responses include player names and game positions, not account IDs or private history. Invalid tokens return 404. |