BlueGit

projects-timfalken-com microchess

feat: scaffold Synhex hex tactics on the Microchess lobby shell

Replace chess rules/UI with a Frozen Synapse-style hex match: 17×14
odd-r grid, simultaneous plan/lock, server sim, and Play playback.
Central tunables live in lib/game-config.php. Production FTP deploy is
disabled until a Synhex host exists.

Co-authored-by: tim <tim@timfalken.com>

timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa

Authored 2026-09-16 · 2 months ago

Hash
24f20754dcf237a933b1fa81bc9703610396743f
Parent
ebdc158d
27 files changed +2039 −917
.gitlab-ci.yml +3 −3
@@ -12,9 +12,8 @@ php_tests:
12 12 script:
13 13 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
14 14 - php -r 'foreach (["pdo_sqlite", "curl", "mbstring", "openssl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
15 - php web/tests/chess.php
15 - php web/tests/synhex.php
16 16 - php web/tests/colors.php
17 - php web/tests/feedback.php
18 17 - php web/tests/push.php
19 18 - python3 web/tests/startup.py
20 19 - python3 web/tests/integration.py
@@ -39,6 +38,7 @@ deploy_tests:
39 38 script:
40 39 - python3 ci/test_deploy.py
41 40
41 # Production FTP deploy is disabled until a Synhex host exists.
42 42 ftp_upload:
43 43 stage: deploy
44 44 image: debian:bookworm-slim
@@ -46,7 +46,7 @@ ftp_upload:
46 46 environment:
47 47 name: production
48 48 rules:
49 - if: '$CI_COMMIT_BRANCH == "master"'
49 - when: never
50 50 before_script:
51 51 - apt-get update -qq
52 52 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
@@ -12,9 +12,8 @@ php_tests:
12 script:
12 script:
13 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
13 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
14 - php -r 'foreach (["pdo_sqlite", "curl", "mbstring", "openssl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
14 - php -r 'foreach (["pdo_sqlite", "curl", "mbstring", "openssl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
15 - php web/tests/chess.php
15 - php web/tests/synhex.php
16 - php web/tests/colors.php
16 - php web/tests/colors.php
17 - php web/tests/feedback.php
18 - php web/tests/push.php
17 - php web/tests/push.php
19 - python3 web/tests/startup.py
18 - python3 web/tests/startup.py
20 - python3 web/tests/integration.py
19 - python3 web/tests/integration.py
@@ -39,6 +38,7 @@ deploy_tests:
39 script:
38 script:
40 - python3 ci/test_deploy.py
39 - python3 ci/test_deploy.py
41
40
41# Production FTP deploy is disabled until a Synhex host exists.
42ftp_upload:
42ftp_upload:
43 stage: deploy
43 stage: deploy
44 image: debian:bookworm-slim
44 image: debian:bookworm-slim
@@ -46,7 +46,7 @@ ftp_upload:
46 environment:
46 environment:
47 name: production
47 name: production
48 rules:
48 rules:
49 - if: '$CI_COMMIT_BRANCH == "master"'
49 - when: never
50 before_script:
50 before_script:
51 - apt-get update -qq
51 - apt-get update -qq
52 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
52 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
README.md +10 −10
@@ -1,22 +1,24 @@
1 # Microchess
1 # Synhex
2 2
3 A 4 × 5 chess app with friends, invitation links, rematches, personal avatars and SQLite storage.
3 A simultaneous-turn hex tactics game (Frozen Synapse–inspired) with friends, invitation links, rematches, personal avatars and SQLite storage. Seeded from Microchess's match/lobby shell.
4 4
5 The complete production application is in [`web/`](web/). Files outside that folder are for repository tooling and CI only. Start locally:
5 The complete application is in [`web/`](web/). Files outside that folder are for repository tooling and CI only. Start locally:
6 6
7 7 ```sh
8 8 php -S 127.0.0.1:8080 -t web web/router.php
9 9 ```
10 10
11 Localhost automatically uses a test account, including when served through Apache. See [`web/README.md`](web/README.md) for setup, OAuth configuration, rules and tests.
11 Localhost automatically uses a test account. See [`web/README.md`](web/README.md) for setup, OAuth (`auth.timfalken.com`), rules and tests.
12 12
13 Move feedback runs locally in PHP after each submitted move, with no generated position database. See [move feedback](web/README.md#move-feedback).
13 Game balance knobs (accuracy, weapons, walk range, grid size, walls, vision) live in one file: [`web/lib/game-config.php`](web/lib/game-config.php). OAuth secrets stay in the generated, gitignored `web/data/config.php`.
14
15 This branch is the seed for a future GitLab project `Timfa/synhex`. **Production FTP deploy is disabled** until that host exists.
14 16
15 17 ## GitLab CI/CD
16 18
17 The default branch is `master`. `.gitlab-ci.yml` runs PHP/chess/API tests, JavaScript checks and a real FTP fixture test. Only after all checks pass does it deploy `web/` using [`ci/deploy.py`](ci/deploy.py). Production deployments cannot run concurrently.
19 The default branch is `master`. `.gitlab-ci.yml` runs PHP/hex/API tests, JavaScript checks and a real FTP fixture test. The `ftp_upload` deploy job is set to `when: never` so pipelines never upload. Re-enable it when production exists.
18 20
19 Required CI variables:
21 Required CI variables (unused until deploy is turned back on):
20 22
21 23 | Variable | Value |
22 24 | --- | --- |
@@ -25,9 +27,7 @@ Required CI variables:
25 27 | `timftppassword` | Password; configure as masked/protected in GitLab |
26 28 | `projectftp` | Existing remote application directory, relative to the FTP login root or absolute |
27 29
28 The mirror preserves the entire production `data/` directory, including configuration, database, WAL, sessions and backups. Its access-denying `.htaccess` is installed separately. Test artifacts, the development router and the application README are excluded from upload. Obsolete application files outside these exclusions are removed.
29
30 FTP TLS certificate verification is disabled for this hosting account, as configured by the owner. First-time SFTP host keys use SSH's `accept-new` policy; changed keys fail. The remote directory must already exist. Configure OAuth separately in the generated `data/config.php` on production: local configuration is never committed or uploaded.
30 The mirror preserves the entire production `data/` directory. Test artifacts, the development router and the application README are excluded from upload.
31 31
32 32 The deployment fixture can also run locally with Python 3, `pyftpdlib` and `lftp`:
33 33
@@ -1,22 +1,24 @@
1# Microchess
1# Synhex
2
2
3A 4 × 5 chess app with friends, invitation links, rematches, personal avatars and SQLite storage.
3A simultaneous-turn hex tactics game (Frozen Synapse–inspired) with friends, invitation links, rematches, personal avatars and SQLite storage. Seeded from Microchess's match/lobby shell.
4
4
5The complete production application is in [`web/`](web/). Files outside that folder are for repository tooling and CI only. Start locally:
5The complete application is in [`web/`](web/). Files outside that folder are for repository tooling and CI only. Start locally:
6
6
7```sh
7```sh
8php -S 127.0.0.1:8080 -t web web/router.php
8php -S 127.0.0.1:8080 -t web web/router.php
9```
9```
10
10
11Localhost automatically uses a test account, including when served through Apache. See [`web/README.md`](web/README.md) for setup, OAuth configuration, rules and tests.
11Localhost automatically uses a test account. See [`web/README.md`](web/README.md) for setup, OAuth (`auth.timfalken.com`), rules and tests.
12
12
13Move feedback runs locally in PHP after each submitted move, with no generated position database. See [move feedback](web/README.md#move-feedback).
13Game balance knobs (accuracy, weapons, walk range, grid size, walls, vision) live in one file: [`web/lib/game-config.php`](web/lib/game-config.php). OAuth secrets stay in the generated, gitignored `web/data/config.php`.
14
15This branch is the seed for a future GitLab project `Timfa/synhex`. **Production FTP deploy is disabled** until that host exists.
14
16
15## GitLab CI/CD
17## GitLab CI/CD
16
18
17The default branch is `master`. `.gitlab-ci.yml` runs PHP/chess/API tests, JavaScript checks and a real FTP fixture test. Only after all checks pass does it deploy `web/` using [`ci/deploy.py`](ci/deploy.py). Production deployments cannot run concurrently.
19The default branch is `master`. `.gitlab-ci.yml` runs PHP/hex/API tests, JavaScript checks and a real FTP fixture test. The `ftp_upload` deploy job is set to `when: never` so pipelines never upload. Re-enable it when production exists.
18
20
19Required CI variables:
21Required CI variables (unused until deploy is turned back on):
20
22
21| Variable | Value |
23| Variable | Value |
22| --- | --- |
24| --- | --- |
@@ -25,9 +27,7 @@ Required CI variables:
25| `timftppassword` | Password; configure as masked/protected in GitLab |
27| `timftppassword` | Password; configure as masked/protected in GitLab |
26| `projectftp` | Existing remote application directory, relative to the FTP login root or absolute |
28| `projectftp` | Existing remote application directory, relative to the FTP login root or absolute |
27
29
28The mirror preserves the entire production `data/` directory, including configuration, database, WAL, sessions and backups. Its access-denying `.htaccess` is installed separately. Test artifacts, the development router and the application README are excluded from upload. Obsolete application files outside these exclusions are removed.
30The mirror preserves the entire production `data/` directory. Test artifacts, the development router and the application README are excluded from upload.
29
30FTP TLS certificate verification is disabled for this hosting account, as configured by the owner. First-time SFTP host keys use SSH's `accept-new` policy; changed keys fail. The remote directory must already exist. Configure OAuth separately in the generated `data/config.php` on production: local configuration is never committed or uploaded.
31
31
32The deployment fixture can also run locally with Python 3, `pyftpdlib` and `lftp`:
32The deployment fixture can also run locally with Python 3, `pyftpdlib` and `lftp`:
33
33
ci/test_deploy.py +3 −3
@@ -27,7 +27,7 @@ class DeployTests(unittest.TestCase):
27 27 folder.mkdir()
28 28 (local/'data/.htaccess').write_text('Require all denied\n')
29 29 (local/'data/config.php').write_text('DO NOT UPLOAD LOCAL SECRET')
30 (local/'data/microchess.sqlite').write_text('DO NOT UPLOAD LOCAL DB')
30 (local/'data/synhex.sqlite').write_text('DO NOT UPLOAD LOCAL DB')
31 31 (local/'tests/check.php').write_text('test code')
32 32 (local/'router.php').write_text('dev router')
33 33 (local/'README.md').write_text('readme')
@@ -35,8 +35,8 @@ class DeployTests(unittest.TestCase):
35 35 (local/'.htaccess').write_text('Options -Indexes\n')
36 36 (local/'assets/app.js').write_text('new frontend')
37 37 (target/'obsolete.php').write_text('stale application code')
38 retained={'config.php':'PRODUCTION SECRET','microchess.sqlite':'PRODUCTION DB',
39 'microchess.sqlite-wal':'LIVE WAL','backups/older.sqlite':'BACKUP'}
38 retained={'config.php':'PRODUCTION SECRET','synhex.sqlite':'PRODUCTION DB',
39 'synhex.sqlite-wal':'LIVE WAL','backups/older.sqlite':'BACKUP'}
40 40 for file,data in retained.items():(target/'data'/file).write_text(data)
41 41 authorizer=DummyAuthorizer();authorizer.add_user('fixture-user','fixture-password',str(remote),perm='elradfmwMT')
42 42 class Handler(FTPHandler):
@@ -27,7 +27,7 @@ class DeployTests(unittest.TestCase):
27 folder.mkdir()
27 folder.mkdir()
28 (local/'data/.htaccess').write_text('Require all denied\n')
28 (local/'data/.htaccess').write_text('Require all denied\n')
29 (local/'data/config.php').write_text('DO NOT UPLOAD LOCAL SECRET')
29 (local/'data/config.php').write_text('DO NOT UPLOAD LOCAL SECRET')
30 (local/'data/microchess.sqlite').write_text('DO NOT UPLOAD LOCAL DB')
30 (local/'data/synhex.sqlite').write_text('DO NOT UPLOAD LOCAL DB')
31 (local/'tests/check.php').write_text('test code')
31 (local/'tests/check.php').write_text('test code')
32 (local/'router.php').write_text('dev router')
32 (local/'router.php').write_text('dev router')
33 (local/'README.md').write_text('readme')
33 (local/'README.md').write_text('readme')
@@ -35,8 +35,8 @@ class DeployTests(unittest.TestCase):
35 (local/'.htaccess').write_text('Options -Indexes\n')
35 (local/'.htaccess').write_text('Options -Indexes\n')
36 (local/'assets/app.js').write_text('new frontend')
36 (local/'assets/app.js').write_text('new frontend')
37 (target/'obsolete.php').write_text('stale application code')
37 (target/'obsolete.php').write_text('stale application code')
38 retained={'config.php':'PRODUCTION SECRET','microchess.sqlite':'PRODUCTION DB',
38 retained={'config.php':'PRODUCTION SECRET','synhex.sqlite':'PRODUCTION DB',
39 'microchess.sqlite-wal':'LIVE WAL','backups/older.sqlite':'BACKUP'}
39 'synhex.sqlite-wal':'LIVE WAL','backups/older.sqlite':'BACKUP'}
40 for file,data in retained.items():(target/'data'/file).write_text(data)
40 for file,data in retained.items():(target/'data'/file).write_text(data)
41 authorizer=DummyAuthorizer();authorizer.add_user('fixture-user','fixture-password',str(remote),perm='elradfmwMT')
41 authorizer=DummyAuthorizer();authorizer.add_user('fixture-user','fixture-password',str(remote),perm='elradfmwMT')
42 class Handler(FTPHandler):
42 class Handler(FTPHandler):
web/README.md +36 −121
@@ -1,7 +1,9 @@
1 # Microchess
1 # Synhex
2 2
3 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 4
5 Synhex reuses Microchess's lobby (game tiles, friends, invites, rematches, avatars, custom colours, PWA, SQLite, PHP API, auth via [auth.timfalken.com](https://auth.timfalken.com)) and replaces chess with a hex-grid simultaneous-turn tactics game.
6
5 7 ## Run locally
6 8
7 9 From the repository root:
@@ -10,30 +12,33 @@ From the repository root:
10 12 php -S 127.0.0.1:8080 -t web web/router.php
11 13 ```
12 14
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.
15 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.
14 16
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.
17 Autologin requires a loopback client IP and a localhost Host header. Do not expose the local development site through a public proxy.
16 18
17 19 ## Production
18 20
19 Requirements: PHP 8.2+, PDO SQLite, cURL, mbstring, OpenSSL with elliptic-curve support, 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.
21 Requirements: PHP 8.2+, PDO SQLite, cURL, mbstring, OpenSSL with elliptic-curve support, writable `web/data/`, and HTTPS. All application writes remain under `web/data/`. Session name is `synhex_session`; the database is `data/synhex.sqlite`.
20 22
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:
23 On the first page request, the app creates `web/data/config.php` with empty `base_url`, `client_id` and `client_secret` if the file does not exist. Fill it in on each server:
22 24
23 25 ```php
24 26 <?php
25 27 return [
26 'base_url' => 'https://your-chess-domain.example',
28 'base_url' => 'https://your-synhex-domain.example',
27 29 'client_id' => 'your-registered-domain.example',
28 30 'client_secret' => 'your-client-secret',
31 // Optional: override any key from lib/game-config.php
29 32 ];
30 33 ```
31 34
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.
35 Environment equivalents: `SYNHEX_BASE_URL`, `SYNHEX_CLIENT_ID`, `SYNHEX_CLIENT_SECRET`.
36
37 Register `/callback.php` in the [auth service admin](https://auth.timfalken.com/admin). See the service's [integration guide](https://auth.timfalken.com/help).
33 38
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.
39 **Production FTP deploy is currently off** in `.gitlab-ci.yml` (`ftp_upload` uses `when: never`) until a Synhex host exists. When deploying manually, preserve `data/` (config, database, WAL, push keys). Never upload your development database or `tests/artifacts/`.
35 40
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:
41 Apache: enable `AllowOverride All` so `.htaccess` denies `data/`, `lib/` and `tests/`. Nginx equivalent:
37 42
38 43 ```nginx
39 44 location ~* ^/(data|lib|tests)(/|$) { deny all; }
@@ -41,48 +46,30 @@ location ~ /\. { deny all; }
41 46 location ~* ^/(README\.md|router\.php)$ { deny all; }
42 47 ```
43 48
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 Verify that `/data/synhex.sqlite`, `/data/config.php` and `/lib/bootstrap.php` return 403 before putting real data in the app.
49 50
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 ```
51 ## Game config
62 52
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.
53 All combat/board tunables are in [`lib/game-config.php`](lib/game-config.php):
64 54
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.
55 - Board: **17 columns × 14 rows**, pointy-top, odd-r offset (238 hexes). Axial internally: `q = col - floor(row / 2)`, `r = row`.
56 - Wall density, spawn layout, walk range (5 hexes/act), act duration (3 seconds)
57 - Base accuracy 15% and each accuracy bonus
58 - Weapon rates of fire and shotgun pellet count
59 - Vision cone (forward direction + two adjacent = 120°) and ranges
66 60
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.
61 Same-named keys in `data/config.php` override these defaults on a server without editing the committed file.
68 62
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.
63 ## How a match works
70 64
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.
65 1. Both players **plan at the same time**. Click a unit, click hexes or drag a path. The path end is a hologram; click a waypoint to place it there and drag the hex in front to set facing.
66 2. **Lock plan**. When both have committed, the server simulates the 3-second act (walk, vision cones, raycast shots, friendly fire).
67 3. Each tile shows **Play** to play back the same server timeline. After both have watched, planning starts again.
68 4. If a VIP dies, that player loses.
72 69
73 ## Ratings and matchmaking
70 First-pass planning UX is intentionally simple (click-to-path / drag-path). Full art polish and perfect path-drag are out of scope for this scaffold.
74 71
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 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings store a “Disable custom colours” preference on your account (default off, so custom colours show). 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.
72 Friends, invites, rematches, matchmaking, ratings, avatars, custom colours, notifications and data export behave as in Microchess.
86 73
87 74 ## Checks
88 75
@@ -90,8 +77,8 @@ From the repository root:
90 77
91 78 ```sh
92 79 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
80 php web/tests/synhex.php
81 php web/tests/colors.php
95 82 php web/tests/push.php
96 83 python3 web/tests/startup.py
97 84 python3 web/tests/integration.py
@@ -101,82 +88,10 @@ node --check web/sw.js
101 88 node web/tests/pwa.mjs
102 89 ```
103 90
104 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.
105
106 Optional real-browser tests (requires Node.js):
107
108 ```sh
109 npm install --prefix web/tests/artifacts --no-audit --no-fund playwright
110 PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" web/tests/artifacts/node_modules/.bin/playwright install chromium
111 PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" node web/tests/browser.mjs
112 ```
113
114 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.
115
116 ## Piece credits
117
118 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).
119
120 ## Inactive games and final positions
121
122 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.
123
124 ## Move feedback
125
126 Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:
127
128 ```sh
129 php -S 127.0.0.1:8080 -t web web/router.php
130 ```
131
132 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.
133
134 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.
135
136 `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.
137
138 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.
139
140 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.
141
142 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.
143
144 Checks:
145
146 ```sh
147 php web/tests/chess.php
148 php web/tests/feedback.php
149 python3 web/tests/integration.py
150 node web/tests/browser.mjs
151 ```
152
153 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.
154
155 ## Saved games
156
157 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.
158
159 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.
160
161 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.
162
163
164 ## Notifications and home-screen installation
165
166 **Account → Enable turn notifications** opts this browser/device in. Notifications cover a new turn (including accepted challenges, match links, matchmaking and rematches), incoming challenges and rematch requests. The service worker skips showing an OS notification when any Microchess tab in that browser is already visible; background/hidden tabs and other devices still notify. Enabling on another device adds that device; disabling affects only the current one. Sign-out removes the current browser's server registration. An existing browser subscription is associated with the current account after signing in or switching accounts. There is a limit of ten subscriptions per account.
167
168 Game actions collect notification events inside the game transaction and dispatch only after commit. There is no cronjob, persistent notification queue, polling-based notification scan or background worker. Matchmaking triggered by a state request also dispatches its newly created games. PHP closes the session before sending; with PHP-FPM it finishes the HTTP response first. Other SAPIs may wait for push delivery (two-second connection timeout, five-second request timeout). Delivery failures are logged without endpoints/keys and cannot roll back a move. Expired subscriptions are removed. Failed deliveries are not retried; notifications are best effort. Superseded game versions are skipped before sending, messages expire after one hour, and each game's topic/tag replaces older pending/displayed notifications.
169
170 Web Push uses the bundled `minishlink/web-push` library under `lib/push/vendor/`, with its licenses and Composer lockfile. Production still needs no Composer or build step. To update the bundled dependencies during development, run `composer update --working-dir=web/lib/push --no-dev` and commit the lockfile and vendor changes together. The lockfile targets PHP 8.2. The host must allow outgoing HTTPS to browser push services. Subscription endpoints are restricted to supported Google, Mozilla, Apple and Windows push-service hosts; adding a new provider requires extending that allowlist.
171
172 The first notification setup automatically generates a VAPID keypair in `data/push-keys.json`, protected by a file lock and the existing data-directory access rules. Preserve it along with the database during backups and deployment; replacing it invalidates existing browser subscriptions. Private keys never reach JavaScript. Subscription APIs require authentication and CSRF protection.
173
174 Notification clicks navigate to `./?game=ID`. The regular home screen loads; the game ID survives the sign-in page, OAuth round trip, and expired-session sign-in prompt. Once authenticated games load, the URL parameter is consumed and the corresponding card pulses white/gray three times. Reduced-motion users get a brief static outline. Missing/hidden games show a short message. The service worker reuses an existing app window where possible and never caches pages, API responses or credentials.
175
176 The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. **Add to home screen** uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.
91 `synhex.php` covers hex math, vision, wall/path, simultaneous commit → timeline, deterministic seeds and VIP elimination. Integration tests cover lobby/API plus plan lock, playback and resign.
177 92
178 `php web/tests/push.php` verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.
93 Optional real-browser tests (requires Node.js / Playwright; see previous Microchess README for install). `web/tests/browser.mjs` exercises the lobby plus hex Lock plan / Play.
179 94
180 On first authenticated use, a one-time dialog explains where to enable turn notifications. Its atomic, CSRF-protected claim is stored per account in `notification_intro`, so simultaneous tabs and other devices do not repeat it. The dialog waits for other dialogs to close and never requests browser permission automatically. Existing accounts receive it once after this update as well.
95 ## Deferred
181 96
182 Notification setup failures open a second dialog above Account. Push-service errors include the Brave settings address and setting name, framed as a possible cause, with alternative network advice. Other failures have permission/setup/save guidance. Closing the error leaves Account open and returns focus to its notification button.
97 Perfect path-drag UX, full fog-of-war playback filtering, production FTP host, renaming the GitLab project itself, and visual art beyond existing piece/colour assets.
@@ -1,7 +1,9 @@
1# Microchess
1# Synhex
2
2
3Self-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.
3Self-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
4
5Synhex reuses Microchess's lobby (game tiles, friends, invites, rematches, avatars, custom colours, PWA, SQLite, PHP API, auth via [auth.timfalken.com](https://auth.timfalken.com)) and replaces chess with a hex-grid simultaneous-turn tactics game.
6
5## Run locally
7## Run locally
6
8
7From the repository root:
9From the repository root:
@@ -10,30 +12,33 @@ From the repository root:
10php -S 127.0.0.1:8080 -t web web/router.php
12php -S 127.0.0.1:8080 -t web web/router.php
11```
13```
12
14
13Open 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.
15Open 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.
14
16
15Autologin 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.
17Autologin requires a loopback client IP and a localhost Host header. Do not expose the local development site through a public proxy.
16
18
17## Production
19## Production
18
20
19Requirements: PHP 8.2+, PDO SQLite, cURL, mbstring, OpenSSL with elliptic-curve support, 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.
21Requirements: PHP 8.2+, PDO SQLite, cURL, mbstring, OpenSSL with elliptic-curve support, writable `web/data/`, and HTTPS. All application writes remain under `web/data/`. Session name is `synhex_session`; the database is `data/synhex.sqlite`.
20
22
21On 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:
23On the first page request, the app creates `web/data/config.php` with empty `base_url`, `client_id` and `client_secret` if the file does not exist. Fill it in on each server:
22
24
23```php
25```php
24<?php
26<?php
25return [
27return [
26 'base_url' => 'https://your-chess-domain.example',
28 'base_url' => 'https://your-synhex-domain.example',
27 'client_id' => 'your-registered-domain.example',
29 'client_id' => 'your-registered-domain.example',
28 'client_secret' => 'your-client-secret',
30 'client_secret' => 'your-client-secret',
31 // Optional: override any key from lib/game-config.php
29];
32];
30```
33```
31
34
32Environment 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.
35Environment equivalents: `SYNHEX_BASE_URL`, `SYNHEX_CLIENT_ID`, `SYNHEX_CLIENT_SECRET`.
36
37Register `/callback.php` in the [auth service admin](https://auth.timfalken.com/admin). See the service's [integration guide](https://auth.timfalken.com/help).
33
38
34Register 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.
39**Production FTP deploy is currently off** in `.gitlab-ci.yml` (`ftp_upload` uses `when: never`) until a Synhex host exists. When deploying manually, preserve `data/` (config, database, WAL, push keys). Never upload your development database or `tests/artifacts/`.
35
40
36Apache: 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:
41Apache: enable `AllowOverride All` so `.htaccess` denies `data/`, `lib/` and `tests/`. Nginx equivalent:
37
42
38```nginx
43```nginx
39location ~* ^/(data|lib|tests)(/|$) { deny all; }
44location ~* ^/(data|lib|tests)(/|$) { deny all; }
@@ -41,48 +46,30 @@ location ~ /\. { deny all; }
41location ~* ^/(README\.md|router\.php)$ { deny all; }
46location ~* ^/(README\.md|router\.php)$ { deny all; }
42```
47```
43
48
44Use 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/`.
49Verify that `/data/synhex.sqlite`, `/data/config.php` and `/lib/bootstrap.php` return 403 before putting real data in the app.
45
46Deploy 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
48SQLite 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
50## Game behavior
51## Game config
51
52Initial position, viewed from White:
53
54```text
555 k n b r
564 p . . .
573 . . . .
582 . . . P
591 R B N K
60 a b c d
61```
62
52
63White 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.
53All combat/board tunables are in [`lib/game-config.php`](lib/game-config.php):
64
54
65The 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.
55- Board: **17 columns × 14 rows**, pointy-top, odd-r offset (238 hexes). Axial internally: `q = col - floor(row / 2)`, `r = row`.
56- Wall density, spawn layout, walk range (5 hexes/act), act duration (3 seconds)
57- Base accuracy 15% and each accuracy bonus
58- Weapon rates of fire and shotgun pellet count
59- Vision cone (forward direction + two adjacent = 120°) and ranges
66
60
67A 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.
61Same-named keys in `data/config.php` override these defaults on a server without editing the committed file.
68
62
69Click 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.
63## How a match works
70
64
71Rematches 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.
651. Both players **plan at the same time**. Click a unit, click hexes or drag a path. The path end is a hologram; click a waypoint to place it there and drag the hex in front to set facing.
662. **Lock plan**. When both have committed, the server simulates the 3-second act (walk, vision cones, raycast shots, friendly fire).
673. Each tile shows **Play** to play back the same server timeline. After both have watched, planning starts again.
684. If a VIP dies, that player loses.
72
69
73## Ratings and matchmaking
70First-pass planning UX is intentionally simple (click-to-path / drag-path). Full art polish and perfect path-drag are out of scope for this scaffold.
74
71
75Existing 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.
72Friends, invites, rematches, matchmaking, ratings, avatars, custom colours, notifications and data export behave as in Microchess.
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
79The 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
83Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings store a “Disable custom colours” preference on your account (default off, so custom colours show). The `user_avatars` table is created automatically, preserving existing accounts and game data.
84
85Avatars 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
73
87## Checks
74## Checks
88
75
@@ -90,8 +77,8 @@ From the repository root:
90
77
91```sh
78```sh
92find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
79find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
93php web/tests/chess.php
80php web/tests/synhex.php
94php web/tests/feedback.php
81php web/tests/colors.php
95php web/tests/push.php
82php web/tests/push.php
96python3 web/tests/startup.py
83python3 web/tests/startup.py
97python3 web/tests/integration.py
84python3 web/tests/integration.py
@@ -101,82 +88,10 @@ node --check web/sw.js
101node web/tests/pwa.mjs
88node web/tests/pwa.mjs
102```
89```
103
90
104Engine 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.
91`synhex.php` covers hex math, vision, wall/path, simultaneous commit → timeline, deterministic seeds and VIP elimination. Integration tests cover lobby/API plus plan lock, playback and resign.
105
106Optional real-browser tests (requires Node.js):
107
108```sh
109npm install --prefix web/tests/artifacts --no-audit --no-fund playwright
110PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" web/tests/artifacts/node_modules/.bin/playwright install chromium
111PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" node web/tests/browser.mjs
112```
113
114These 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.
115
116## Piece credits
117
118Unmodified `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).
119
120## Inactive games and final positions
121
122Ended 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.
123
124## Move feedback
125
126Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:
127
128```sh
129php -S 127.0.0.1:8080 -t web web/router.php
130```
131
132After 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.
133
134The 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.
135
136`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.
137
138Values 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.
139
140Analysis 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.
141
142Previous 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.
143
144Checks:
145
146```sh
147php web/tests/chess.php
148php web/tests/feedback.php
149python3 web/tests/integration.py
150node web/tests/browser.mjs
151```
152
153The 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.
154
155## Saved games
156
157Games 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.
158
159Replays 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.
160
161The 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.
162
163
164## Notifications and home-screen installation
165
166**Account → Enable turn notifications** opts this browser/device in. Notifications cover a new turn (including accepted challenges, match links, matchmaking and rematches), incoming challenges and rematch requests. The service worker skips showing an OS notification when any Microchess tab in that browser is already visible; background/hidden tabs and other devices still notify. Enabling on another device adds that device; disabling affects only the current one. Sign-out removes the current browser's server registration. An existing browser subscription is associated with the current account after signing in or switching accounts. There is a limit of ten subscriptions per account.
167
168Game actions collect notification events inside the game transaction and dispatch only after commit. There is no cronjob, persistent notification queue, polling-based notification scan or background worker. Matchmaking triggered by a state request also dispatches its newly created games. PHP closes the session before sending; with PHP-FPM it finishes the HTTP response first. Other SAPIs may wait for push delivery (two-second connection timeout, five-second request timeout). Delivery failures are logged without endpoints/keys and cannot roll back a move. Expired subscriptions are removed. Failed deliveries are not retried; notifications are best effort. Superseded game versions are skipped before sending, messages expire after one hour, and each game's topic/tag replaces older pending/displayed notifications.
169
170Web Push uses the bundled `minishlink/web-push` library under `lib/push/vendor/`, with its licenses and Composer lockfile. Production still needs no Composer or build step. To update the bundled dependencies during development, run `composer update --working-dir=web/lib/push --no-dev` and commit the lockfile and vendor changes together. The lockfile targets PHP 8.2. The host must allow outgoing HTTPS to browser push services. Subscription endpoints are restricted to supported Google, Mozilla, Apple and Windows push-service hosts; adding a new provider requires extending that allowlist.
171
172The first notification setup automatically generates a VAPID keypair in `data/push-keys.json`, protected by a file lock and the existing data-directory access rules. Preserve it along with the database during backups and deployment; replacing it invalidates existing browser subscriptions. Private keys never reach JavaScript. Subscription APIs require authentication and CSRF protection.
173
174Notification clicks navigate to `./?game=ID`. The regular home screen loads; the game ID survives the sign-in page, OAuth round trip, and expired-session sign-in prompt. Once authenticated games load, the URL parameter is consumed and the corresponding card pulses white/gray three times. Reduced-motion users get a brief static outline. Missing/hidden games show a short message. The service worker reuses an existing app window where possible and never caches pages, API responses or credentials.
175
176The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. **Add to home screen** uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.
177
92
178`php web/tests/push.php` verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.
93Optional real-browser tests (requires Node.js / Playwright; see previous Microchess README for install). `web/tests/browser.mjs` exercises the lobby plus hex Lock plan / Play.
179
94
180On first authenticated use, a one-time dialog explains where to enable turn notifications. Its atomic, CSRF-protected claim is stored per account in `notification_intro`, so simultaneous tabs and other devices do not repeat it. The dialog waits for other dialogs to close and never requests browser permission automatically. Existing accounts receive it once after this update as well.
95## Deferred
181
96
182Notification setup failures open a second dialog above Account. Push-service errors include the Brave settings address and setting name, framed as a possible cause, with alternative network advice. Other failures have permission/setup/save guidance. Closing the error leaves Account open and returns focus to its notification button.
97Perfect path-drag UX, full fog-of-war playback filtering, production FTP host, renaming the GitLab project itself, and visual art beyond existing piece/colour assets.
web/api.php +29 −27
@@ -49,7 +49,7 @@ try {
49 49 jsonOut($items);
50 50 }
51 51 if ($action==='export') {
52 header('Content-Disposition: attachment; filename="microchess-data.json"');
52 header('Content-Disposition: attachment; filename="synhex-data.json"');
53 53 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
54 54 'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
55 55 'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
@@ -182,7 +182,7 @@ try {
182 182 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
183 183 else {
184 184 $white=random_int(0,1)?$g['a']:$g['b'];
185 query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
185 query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[$white,json_encode(SynhexMatch::initial()),$g['id']]);
186 186 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
187 187 }
188 188 } elseif ($action==='exit' || $action==='rematch') {
@@ -193,28 +193,32 @@ try {
193 193 if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
194 194 if ($g['rematch_'.$opSide]) {
195 195 $white=$g['white']===$g['a']?$g['b']:$g['a'];
196 query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,piece_skin_white=NULL,piece_skin_black=NULL,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
196 query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,piece_skin_white=NULL,piece_skin_black=NULL,version=version+1 WHERE id=?",[$white,json_encode(SynhexMatch::initial()),$g['id']]);
197 197 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
198 198 }
199 199 else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
200 200 }
201 201 } else {
202 202 if ($g['status']!=='active') throw new DomainException('This game is not active.');
203 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';
204 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
205 if ($action==='move') {
206 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
207 $before=$s;
208 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
209 $feedbackStates=[$before,$s];
210 $r=Chess::result($s);
211 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
212 else query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
213 } elseif ($action==='claim_draw') {
214 $claim=$s;
215 if (isset($in['from'],$in['to'])) $claim=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
216 if (!Chess::claimable($claim)) throw new DomainException('A draw cannot be claimed in this position.');
217 finishGame($g,null,$claim['halfmove']>=100?'50-move rule':'Threefold repetition',$s);
203 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';$cfg=gameConfig();
204 if ($action==='save_plan') {
205 $s=SynhexMatch::saveDraft($s,$color,$in['plan']??[],$cfg);
206 query('UPDATE games SET state=?,version=version+1 WHERE id=?',[json_encode($s),$g['id']]);
207 } elseif ($action==='commit_plan') {
208 $beforePhase=$s['phase']??'';
209 $s=SynhexMatch::commit($s,$color,$in['plan']??[],$cfg);
210 query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
211 if ($beforePhase==='planning' && ($s['phase']??'')==='playback') $GLOBALS['synhex_notify_both']=true;
212 } elseif ($action==='ack_playback') {
213 $s=SynhexMatch::ackPlayback($s,$color);
214 if (($s['phase']??'')==='ended' && !empty($s['result'])) {
215 $winnerColor=$s['result']['winner'];
216 $winner=$winnerColor===null?null:($winnerColor==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a']));
217 finishGame($g,$winner,$s['result']['reason'],$s);
218 } else {
219 query('UPDATE games SET state=?,version=version+1 WHERE id=?',[json_encode($s),$g['id']]);
220 if (($s['phase']??'')==='planning') $GLOBALS['synhex_notify_both']=true;
221 }
218 222 } elseif ($action==='offer_draw') {
219 223 if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
220 224 query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
@@ -225,20 +229,18 @@ try {
225 229 else throw new DomainException('Unknown action.');
226 230 }
227 231 }
228 if (isset($g) && in_array($action,['move','accept','rematch'],true)) {
232 if (isset($g) && in_array($action,['commit_plan','ack_playback','accept','rematch'],true)) {
229 233 $current=query('SELECT * FROM games WHERE id=?',[$g['id']])->fetch();
230 if ($current && $current['status']==='active') pushGame((int)$g['id']);
234 if ($current && $current['status']==='active') {
235 if (!empty($GLOBALS['synhex_notify_both'])) {
236 $st=json_decode($current['state'],true);
237 foreach (SynhexMatch::playersToNotify($current,$st) as $recipient) pushGame((int)$g['id'],'turn',$recipient);
238 } else pushGame((int)$g['id']);
239 }
231 240 elseif ($current && $action==='rematch') pushGame((int)$g['id'],'rematch',$other);
232 241 }
233 242 db()->exec('COMMIT');
234 243 pushAfterCommit();
235 if (isset($feedbackStates)) {
236 // Release game/session writes before optional computation. Analysis can never undo a saved move.
237 session_write_close();
238 $out['feedback']=null;
239 try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
240 catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
241 }
242 244 jsonOut($out);
243 245 } catch (Throwable $e) {
244 246 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
@@ -49,7 +49,7 @@ try {
49 jsonOut($items);
49 jsonOut($items);
50 }
50 }
51 if ($action==='export') {
51 if ($action==='export') {
52 header('Content-Disposition: attachment; filename="microchess-data.json"');
52 header('Content-Disposition: attachment; filename="synhex-data.json"');
53 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
53 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
54 'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
54 'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
55 'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
55 'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
@@ -182,7 +182,7 @@ try {
182 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
182 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
183 else {
183 else {
184 $white=random_int(0,1)?$g['a']:$g['b'];
184 $white=random_int(0,1)?$g['a']:$g['b'];
185 query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
185 query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[$white,json_encode(SynhexMatch::initial()),$g['id']]);
186 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
186 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
187 }
187 }
188 } elseif ($action==='exit' || $action==='rematch') {
188 } elseif ($action==='exit' || $action==='rematch') {
@@ -193,28 +193,32 @@ try {
193 if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
193 if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
194 if ($g['rematch_'.$opSide]) {
194 if ($g['rematch_'.$opSide]) {
195 $white=$g['white']===$g['a']?$g['b']:$g['a'];
195 $white=$g['white']===$g['a']?$g['b']:$g['a'];
196 query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,piece_skin_white=NULL,piece_skin_black=NULL,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
196 query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,piece_skin_white=NULL,piece_skin_black=NULL,version=version+1 WHERE id=?",[$white,json_encode(SynhexMatch::initial()),$g['id']]);
197 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
197 assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
198 }
198 }
199 else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
199 else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
200 }
200 }
201 } else {
201 } else {
202 if ($g['status']!=='active') throw new DomainException('This game is not active.');
202 if ($g['status']!=='active') throw new DomainException('This game is not active.');
203 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';
203 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';$cfg=gameConfig();
204 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
204 if ($action==='save_plan') {
205 if ($action==='move') {
205 $s=SynhexMatch::saveDraft($s,$color,$in['plan']??[],$cfg);
206 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
206 query('UPDATE games SET state=?,version=version+1 WHERE id=?',[json_encode($s),$g['id']]);
207 $before=$s;
207 } elseif ($action==='commit_plan') {
208 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
208 $beforePhase=$s['phase']??'';
209 $feedbackStates=[$before,$s];
209 $s=SynhexMatch::commit($s,$color,$in['plan']??[],$cfg);
210 $r=Chess::result($s);
210 query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
211 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
211 if ($beforePhase==='planning' && ($s['phase']??'')==='playback') $GLOBALS['synhex_notify_both']=true;
212 else query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
212 } elseif ($action==='ack_playback') {
213 } elseif ($action==='claim_draw') {
213 $s=SynhexMatch::ackPlayback($s,$color);
214 $claim=$s;
214 if (($s['phase']??'')==='ended' && !empty($s['result'])) {
215 if (isset($in['from'],$in['to'])) $claim=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
215 $winnerColor=$s['result']['winner'];
216 if (!Chess::claimable($claim)) throw new DomainException('A draw cannot be claimed in this position.');
216 $winner=$winnerColor===null?null:($winnerColor==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a']));
217 finishGame($g,null,$claim['halfmove']>=100?'50-move rule':'Threefold repetition',$s);
217 finishGame($g,$winner,$s['result']['reason'],$s);
218 } else {
219 query('UPDATE games SET state=?,version=version+1 WHERE id=?',[json_encode($s),$g['id']]);
220 if (($s['phase']??'')==='planning') $GLOBALS['synhex_notify_both']=true;
221 }
218 } elseif ($action==='offer_draw') {
222 } elseif ($action==='offer_draw') {
219 if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
223 if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
220 query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
224 query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
@@ -225,20 +229,18 @@ try {
225 else throw new DomainException('Unknown action.');
229 else throw new DomainException('Unknown action.');
226 }
230 }
227 }
231 }
228 if (isset($g) && in_array($action,['move','accept','rematch'],true)) {
232 if (isset($g) && in_array($action,['commit_plan','ack_playback','accept','rematch'],true)) {
229 $current=query('SELECT * FROM games WHERE id=?',[$g['id']])->fetch();
233 $current=query('SELECT * FROM games WHERE id=?',[$g['id']])->fetch();
230 if ($current && $current['status']==='active') pushGame((int)$g['id']);
234 if ($current && $current['status']==='active') {
235 if (!empty($GLOBALS['synhex_notify_both'])) {
236 $st=json_decode($current['state'],true);
237 foreach (SynhexMatch::playersToNotify($current,$st) as $recipient) pushGame((int)$g['id'],'turn',$recipient);
238 } else pushGame((int)$g['id']);
239 }
231 elseif ($current && $action==='rematch') pushGame((int)$g['id'],'rematch',$other);
240 elseif ($current && $action==='rematch') pushGame((int)$g['id'],'rematch',$other);
232 }
241 }
233 db()->exec('COMMIT');
242 db()->exec('COMMIT');
234 pushAfterCommit();
243 pushAfterCommit();
235 if (isset($feedbackStates)) {
236 // Release game/session writes before optional computation. Analysis can never undo a saved move.
237 session_write_close();
238 $out['feedback']=null;
239 try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
240 catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
241 }
242 jsonOut($out);
244 jsonOut($out);
243} catch (Throwable $e) {
245} catch (Throwable $e) {
244 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
246 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
web/assets/app.css +83 −12
@@ -230,7 +230,7 @@ main {
230 230
231 231 .game-grid {
232 232 display: grid;
233 grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
233 grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
234 234 gap: 22px
235 235 }
236 236
@@ -325,17 +325,81 @@ main {
325 325 }
326 326
327 327 .board-wrap {
328 padding: 15px;
328 padding: 10px 12px 8px;
329 329 position: relative
330 330 }
331 331
332 .board {
333 display: grid;
334 grid-template-columns: repeat(4, 1fr);
335 border-radius: 5px;
336 overflow: hidden;
337 aspect-ratio: 4/5;
338 touch-action: pan-y
332 .board,
333 .hex-board {
334 width: 100%;
335 display: block;
336 overflow: visible;
337 touch-action: none;
338 user-select: none
339 }
340
341 .hex-board {
342 max-height: 280px
343 }
344
345 .hex-cell {
346 stroke: #c5cbb8;
347 stroke-width: 0.6;
348 fill: var(--light-square)
349 }
350
351 .hex-cell.odd {
352 fill: var(--dark-square)
353 }
354
355 .hex-cell.wall {
356 fill: #3d4a40;
357 stroke: #2b362f
358 }
359
360 .hex-cell.path {
361 fill: #c9d48a
362 }
363
364 .hex-cell.selected {
365 fill: #d6d98b
366 }
367
368 .hex-cell.legal {
369 fill: #b7c9b0
370 }
371
372 .hex-cell.hologram-hex {
373 stroke: #294d45;
374 stroke-width: 1.4;
375 fill: #d6d98b
376 }
377
378 .hex-unit {
379 pointer-events: none
380 }
381
382 .hex-unit.hologram {
383 opacity: .42
384 }
385
386 .hex-facing {
387 fill: #294d45;
388 pointer-events: none
389 }
390
391 .hex-shot {
392 stroke: #c62828;
393 stroke-width: 1.1;
394 fill: none;
395 opacity: .85
396 }
397
398 .hex-label {
399 font-size: 5px;
400 font-weight: 700;
401 fill: #24352d;
402 pointer-events: none
339 403 }
340 404
341 405 .square {
@@ -438,9 +502,15 @@ main {
438 502 font-size: 11px
439 503 }
440 504
441 .card-footer .turn-label {
442 color: var(--green);
443 font-weight: 600
505 .card-footer .footer-actions {
506 display: flex;
507 align-items: center;
508 gap: 8px
509 }
510
511 .card-footer .primary {
512 font-size: 11px;
513 padding: 5px 10px
444 514 }
445 515
446 516 .text-button {
@@ -456,6 +526,7 @@ main {
456 526 margin-top: 34px
457 527 }
458 528
529 .waiting .hex-board,
459 530 .waiting .board {
460 531 filter: saturate(.62)
461 532 }
@@ -230,7 +230,7 @@ main {
230
230
231.game-grid {
231.game-grid {
232 display: grid;
232 display: grid;
233 grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
233 grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
234 gap: 22px
234 gap: 22px
235}
235}
236
236
@@ -325,17 +325,81 @@ main {
325}
325}
326
326
327.board-wrap {
327.board-wrap {
328 padding: 15px;
328 padding: 10px 12px 8px;
329 position: relative
329 position: relative
330}
330}
331
331
332.board {
332.board,
333 display: grid;
333.hex-board {
334 grid-template-columns: repeat(4, 1fr);
334 width: 100%;
335 border-radius: 5px;
335 display: block;
336 overflow: hidden;
336 overflow: visible;
337 aspect-ratio: 4/5;
337 touch-action: none;
338 touch-action: pan-y
338 user-select: none
339}
340
341.hex-board {
342 max-height: 280px
343}
344
345.hex-cell {
346 stroke: #c5cbb8;
347 stroke-width: 0.6;
348 fill: var(--light-square)
349}
350
351.hex-cell.odd {
352 fill: var(--dark-square)
353}
354
355.hex-cell.wall {
356 fill: #3d4a40;
357 stroke: #2b362f
358}
359
360.hex-cell.path {
361 fill: #c9d48a
362}
363
364.hex-cell.selected {
365 fill: #d6d98b
366}
367
368.hex-cell.legal {
369 fill: #b7c9b0
370}
371
372.hex-cell.hologram-hex {
373 stroke: #294d45;
374 stroke-width: 1.4;
375 fill: #d6d98b
376}
377
378.hex-unit {
379 pointer-events: none
380}
381
382.hex-unit.hologram {
383 opacity: .42
384}
385
386.hex-facing {
387 fill: #294d45;
388 pointer-events: none
389}
390
391.hex-shot {
392 stroke: #c62828;
393 stroke-width: 1.1;
394 fill: none;
395 opacity: .85
396}
397
398.hex-label {
399 font-size: 5px;
400 font-weight: 700;
401 fill: #24352d;
402 pointer-events: none
339}
403}
340
404
341.square {
405.square {
@@ -438,9 +502,15 @@ main {
438 font-size: 11px
502 font-size: 11px
439}
503}
440
504
441.card-footer .turn-label {
505.card-footer .footer-actions {
442 color: var(--green);
506 display: flex;
443 font-weight: 600
507 align-items: center;
508 gap: 8px
509}
510
511.card-footer .primary {
512 font-size: 11px;
513 padding: 5px 10px
444}
514}
445
515
446.text-button {
516.text-button {
@@ -456,6 +526,7 @@ main {
456 margin-top: 34px
526 margin-top: 34px
457}
527}
458
528
529.waiting .hex-board,
459.waiting .board {
530.waiting .board {
460 filter: saturate(.62)
531 filter: saturate(.62)
461}
532}
web/assets/app.js +381 −206
@@ -1,43 +1,48 @@
1 1 'use strict';
2 2 const $ = (s, root = document) => root.querySelector(s);
3 3 const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4 // Server embeds the deploy commit in <meta name="asset-version">; append to static URLs.
5 4 const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
6 5 const withAssetVersion = url => {
7 6 if (!assetVersion) return url;
8 7 return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion);
9 8 };
10 9 (() => {
11 // Backup only: HTML already no-stores and links use ?v=. Helps stuck PWA/shell tabs.
12 10 if (!assetVersion) return;
13 const key = 'microchess-asset-version';
11 const key = 'synhex-asset-version';
14 12 const prev = localStorage.getItem(key);
15 13 if (prev === assetVersion) return;
16 14 localStorage.setItem(key, assetVersion);
17 15 if (prev) location.reload();
18 16 })();
19 const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
20 const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
21 17 const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
22 18 const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
23 19 const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
24 function customColoursDisabled ()
25 {
26 // Account preference (default off → custom colours visible).
27 return !!(state?.user?.disableCustomColours);
28 }
20 const HEX_DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
21 const HEX_SIZE = 12;
22 function customColoursDisabled () { return !!(state?.user?.disableCustomColours); }
29 23 const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`);
30 24 const pieceUrl = (p, skin) =>
31 25 {
32 26 if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p);
33 27 return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`);
34 28 };
35 function skinForPiece (g, p)
29 function unitLetter (u)
36 30 {
37 if (!g || p === '.') return null;
38 const whiteSkin = g.pieceSkinWhite || 'White';
39 const blackSkin = g.pieceSkinBlack || 'Black';
40 return p === p.toUpperCase() ? whiteSkin : blackSkin;
31 if (u.role === 'vip') return 'k';
32 if (u.weapon === 'shotgun') return 'r';
33 return 'n';
34 }
35 function unitPiece (u) { const g = unitLetter(u); return u.team === 'w' ? g.toUpperCase() : g; }
36 function unitLabel (u)
37 {
38 if (u.role === 'vip') return 'VIP (pistol)';
39 if (u.weapon === 'shotgun') return 'Soldier (shotgun)';
40 return 'Soldier (SMG)';
41 }
42 function skinForUnit (g, u)
43 {
44 if (!g) return null;
45 return u.team === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black');
41 46 }
42 47 function displayColorFor (g)
43 48 {
@@ -51,13 +56,9 @@ function colorTagMarkup (g)
51 56 const display = displayColorFor(g);
52 57 const rules = rulesColorLabel(g);
53 58 const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`;
54 const disc = display.toLowerCase();
55 return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(disc)}"></span>${esc(display)}</span>`;
56 }
57 function kingAvatarUrl (color)
58 {
59 return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`);
59 return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(display.toLowerCase())}"></span>${esc(display)}</span>`;
60 60 }
61 function kingAvatarUrl (color) { return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`); }
61 62 function nextColorSkipping (current, skip)
62 63 {
63 64 let i = PIECE_COLOR_ORDER.indexOf(current);
@@ -98,7 +99,6 @@ function renderAvatarChoices ()
98 99 $('#avatar-option-count').textContent = `${options.length} pieces`;
99 100 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
100 101 }
101
102 102 function openColorPreferences ()
103 103 {
104 104 if (!state) return;
@@ -110,7 +110,7 @@ function openColorPreferences ()
110 110 if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred);
111 111 const paint = () =>
112 112 {
113 showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your pieces look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
113 showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your operatives look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
114 114 $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); };
115 115 $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); };
116 116 document.querySelectorAll('[data-color-role]').forEach(btn =>
@@ -134,10 +134,8 @@ function openColorPreferences ()
134 134 paint();
135 135 }
136 136
137 let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
138 const moveHolds = new Map();
139 const moveFeedback = new Map();
140 let moveHoldTimer;
137 let state, selected = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
138 const playback = new Map();
141 139 let inviteToken = new URLSearchParams(location.search).get('invite');
142 140 const modal = $('#modal');
143 141 function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
@@ -166,7 +164,7 @@ if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
166 164 if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
167 165 if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
168 166 if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
169 document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
167 document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; renderGames(); } });
170 168 async function api (data)
171 169 {
172 170 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
@@ -178,12 +176,7 @@ async function action (data, success)
178 176 try
179 177 {
180 178 const result = await api(data);
181 if (data.action === 'move')
182 {
183 moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null });
184 if (['good', 'poor'].includes(result.feedback?.quality)) moveFeedback.set(data.game, { user: state.user.id, ply: result.feedback.ply, quality: result.feedback.quality, start: null });
185 }
186 selected = null; promotion = null; if (success) await success(result); await refresh(true);
179 selected = null; if (success) await success(result); await refresh(true);
187 180 }
188 181 catch (e) { toast(e.message); await refresh(true); }
189 182 finally { busy = false; }
@@ -198,165 +191,313 @@ async function refresh (force = false)
198 191 if (response.status === 401) { showModal('<h2>Sign in to continue</h2><p>Your session has expired. Your games are saved.</p><a class="button primary" href="auth.php' + esc(location.search || '') + '">Sign in</a>'); return; }
199 192 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
200 193 state = data;
201 window.microchessPwa?.sync();
202 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
194 window.synhexPwa?.sync();
195 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version || g.state?.phase !== 'planning') selected = null; }
203 196 const signature = JSON.stringify(data);
204 197 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
205 198 if (data.invite && !inviteShown)
206 199 {
207 200 inviteShown = true; const i = data.invite;
208 201 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
209 else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
202 else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'Lock your plan. The act plays when you both commit.'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
210 203 }
211 window.microchessPwa?.intro();
204 window.synhexPwa?.intro();
212 205 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
213 206 }
214 function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
207 function empty (yours) { return `<div class="empty"><span class="empty-icon">⬡</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is planning or watching playback.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
215 208 function renderGames ()
216 209 {
217 210 if (!state) return;
218 clearTimeout(moveHoldTimer);
219 let relocating = false;
220 const now = performance.now();
221 for (const [id, hold] of moveHolds)
222 {
223 const g = state.games.find(g => g.id === id);
224 if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
225 {
226 moveHolds.delete(id); continue;
227 }
228 // Start the pause when the confirmed board position is first displayed.
229 if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
230 if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
231 }
232 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
233 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
234 const selector = '#main .game-card, .waiting-heading, #main > footer';
235 const key = el => el.dataset.game || el.tagName;
236 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
237 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
238 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
239 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming || moveHolds.has(g.id)).sort((a, b) => (moveHolds.get(a.id)?.turnOrder ?? a.turnOrder) - (moveHolds.get(b.id)?.turnOrder ?? b.turnOrder) || a.id - b.id);
211 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming).sort((a, b) => a.turnOrder - b.turnOrder || a.id - b.id);
240 212 const waiting = state.games.filter(g => !yours.includes(g));
241 213 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
242 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
243 const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el =>
244 {
245 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
246 return [el.closest('[data-game]').dataset.game, { share: new DOMMatrixReadOnly(getComputedStyle(fill).transform).a, target: el.dataset.share, remaining: animation ? Math.max(0, 650 - Number(animation.currentTime)) : 650 }];
247 }));
248 214 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
249 215 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
250 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
251 216 for (const el of document.querySelectorAll('#main .material-bar'))
252 217 {
253 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
254 // Prefer WAAPI over element.style — CSP style-src 'self' blocks inline CSSOM writes.
255 if (!reduced && old && Math.abs(old.share - share) > .0001)
256 fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear', fill: 'forwards' });
257 else
258 fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' });
259 }
260 renderMoveFeedback(now, reduced);
261 window.microchessPwa?.highlight();
262 if (animate)
263 {
264 for (const el of document.querySelectorAll(selector))
265 {
266 const old = before.get(key(el));
267 el.getAnimations().forEach(animation => animation.cancel());
268 if (!old) continue;
269 const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
270 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
271 el.animate([
272 { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
273 { transform: 'translate(0, 0)', zIndex: 2 }
274 ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
275 }
218 const fill = $('.material-white', el), share = Number(el.dataset.share);
219 fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' });
276 220 }
221 window.synhexPwa?.highlight();
277 222 }
278 223 function card (g)
279 224 {
280 225 let content = '';
281 226 if (g.replay) content = board(g);
282 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
227 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">⬡</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
283 228 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
284 else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`;
229 else content = board(g) + footer(g);
285 230 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
286 231 }
287 function materialBarSkinName (name, fallback)
232 function footer (g)
288 233 {
289 return PIECE_COLOR_ORDER.includes(name) ? name : fallback;
234 const phase = g.state?.phase;
235 let status = 'Waiting';
236 let extra = '';
237 if (phase === 'planning')
238 {
239 status = g.state.committed ? 'Plan locked' : (g.yourTurn ? 'Plan your act' : 'Waiting for a plan');
240 if (g.yourTurn && !g.state.committed) extra = `<button class="primary" data-game-action="commit">Lock plan</button>`;
241 else extra = `<span>Act ${g.state.act + 1}</span>`;
242 }
243 else if (phase === 'playback')
244 {
245 status = g.state.acked ? 'Waiting for opponent' : 'Act ready';
246 if (g.yourTurn && !g.state.acked) extra = `<button class="primary" data-game-action="play">Play</button>`;
247 else extra = `<span>Act ${g.state.act}</span>`;
248 }
249 return `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${status}</span>${g.yourTurn ? `<span class="footer-actions">${extra}<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button></span>` : extra}</div>`;
290 250 }
251 function materialBarSkinName (name, fallback) { return PIECE_COLOR_ORDER.includes(name) ? name : fallback; }
291 252 function materialBarSkins (g)
292 253 {
293 254 if (customColoursDisabled()) return { left: 'White', right: 'Black' };
294 return {
295 left: materialBarSkinName(g.pieceSkinWhite, 'White'),
296 right: materialBarSkinName(g.pieceSkinBlack, 'Black')
297 };
255 return { left: materialBarSkinName(g.pieceSkinWhite, 'White'), right: materialBarSkinName(g.pieceSkinBlack, 'Black') };
298 256 }
299 257 function materialBar (g)
300 258 {
301 const totals = { w: 0, b: 0 };
302 for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
259 const totals = g.strength || { w: 0, b: 0 };
303 260 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
304 261 const { left, right } = materialBarSkins(g);
305 262 const you = g.color === 'w' ? left : right;
306 const label = `${left}: ${totals.w} material points. ${right}: ${totals.b} material points. You play ${you}${you === 'White' || you === 'Black' ? '' : ` (${g.color === 'w' ? 'White' : 'Black'})`}.`;
307 const ariaSides = left === 'White' && right === 'Black'
308 ? 'White on the left and Black on the right'
309 : `${left} (White) on the left and ${right} (Black) on the right`;
310 // Classes only — inline style= is blocked by CSP style-src 'self'.
311 return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Material balance, ${esc(ariaSides)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)} Pawn 1 · Knight/Bishop 3 · Rook 5 · Queen 9. Kings are not counted." tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`;
263 const label = `${left}: ${totals.w} strength. ${right}: ${totals.b} strength. You play ${you}. VIP 3 · Soldier 1.`;
264 return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Team strength" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)}" tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`;
312 265 }
313 function renderMoveFeedback (now, reduced)
266 function hexKey (q, r) { return q + ',' + r; }
267 function offsetOf (q, r) { return { col: q + Math.floor(r / 2), row: r }; }
268 function axialOf (col, row) { return { q: col - Math.floor(row / 2), r: row }; }
269 function hexDist (a, b) { return (Math.abs(a.q - b.q) + Math.abs(a.q + a.r - b.q - b.r) + Math.abs(a.r - b.r)) / 2; }
270 function hexNeighbors (q, r) { return HEX_DIRS.map(([dq, dr]) => ({ q: q + dq, r: r + dr })); }
271 function hexPixel (col, row, size)
314 272 {
315 for (const [id, feedback] of moveFeedback)
273 const w = Math.sqrt(3) * size;
274 return { x: w * (col + 0.5 * (row & 1)) + size * Math.sqrt(3), y: size * 1.5 * row + size * 1.2, w };
275 }
276 function hexPoints (cx, cy, size)
277 {
278 const pts = [];
279 for (let i = 0; i < 6; i++)
280 {
281 const a = Math.PI / 180 * (60 * i - 30);
282 pts.push(`${cx + size * Math.cos(a)},${cy + size * Math.sin(a)}`);
283 }
284 return pts.join(' ');
285 }
286 function walkableSet (g)
287 {
288 const walls = new Set(g.state.walls || []);
289 const set = new Set();
290 const cols = g.state.grid.cols, rows = g.state.grid.rows;
291 for (let row = 0; row < rows; row++) for (let col = 0; col < cols; col++)
316 292 {
317 const g = state.games.find(g => g.id === id);
318 if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
319 if (g.state.ply !== feedback.ply) continue;
320 if (feedback.start === null)
293 const { q, r } = axialOf(col, row);
294 const k = hexKey(q, r);
295 if (!walls.has(k)) set.add(k);
296 }
297 return set;
298 }
299 function hexPath (from, to, walkable)
300 {
301 const start = hexKey(from.q, from.r), goal = hexKey(to.q, to.r);
302 if (!walkable.has(start) || !walkable.has(goal)) return null;
303 if (start === goal) return [from];
304 const open = new Map([[start, 0]]), came = new Map(), gScore = new Map([[start, 0]]);
305 while (open.size)
306 {
307 let current = null, best = Infinity;
308 for (const [k, f] of open) if (f < best) { best = f; current = k; }
309 open.delete(current);
310 if (current === goal)
311 {
312 const path = [];
313 while (current !== start) { const [q, r] = current.split(',').map(Number); path.push({ q, r }); current = came.get(current); }
314 path.push(from);
315 return path.reverse();
316 }
317 const [cq, cr] = current.split(',').map(Number);
318 for (const n of hexNeighbors(cq, cr))
321 319 {
322 feedback.start = now;
323 setTimeout(() =>
320 const nk = hexKey(n.q, n.r);
321 if (!walkable.has(nk)) continue;
322 const tg = gScore.get(current) + 1;
323 if (!gScore.has(nk) || tg < gScore.get(nk))
324 324 {
325 if (moveFeedback.get(id) !== feedback) return;
326 moveFeedback.delete(id);
327 document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
328 }, 1800);
325 came.set(nk, current); gScore.set(nk, tg); open.set(nk, tg + hexDist(n, to));
326 }
329 327 }
330 const elapsed = now - feedback.start;
331 if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
332 const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
333 const overlay = document.createElement('div');
334 overlay.className = `move-feedback ${feedback.quality}`;
335 const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
336 el.append(overlay);
337 if (reduced) { overlay.style.opacity = '1'; continue; }
338 const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
339 const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
340 animation.currentTime = elapsed;
341 328 }
329 return null;
330 }
331 function currentUnits (g)
332 {
333 const play = playback.get(g.id);
334 if (play?.units) return play.units;
335 return g.state?.units || [];
342 336 }
343 337 function board (g)
344 338 {
345 const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
346 const active = selected?.game === g.id ? selected.from : null;
347 const legal = g.legal.filter(m => m.from === active).map(m => m.to);
348 let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
349 indices.forEach((i, view) =>
339 if (!g.state?.grid) return '<div class="board-wrap"><p class="inline-note">Loading board…</p></div>';
340 const cols = g.state.grid.cols, rows = g.state.grid.rows;
341 const size = HEX_SIZE;
342 const width = Math.sqrt(3) * size * (cols + 1.2);
343 const height = size * 1.5 * rows + size * 2.2;
344 const walls = new Set(g.state.walls || []);
345 const units = currentUnits(g);
346 const mine = selected?.game === g.id ? selected : null;
347 const pathKeys = new Set((mine?.path || []).map(p => hexKey(p.q, p.r)));
348 const holo = hologramOf(g, mine);
349 const play = playback.get(g.id);
350 let hexes = '';
351 for (let row = 0; row < rows; row++)
350 352 {
351 const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
352 const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
353 const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
354 const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
355 html += `<button class="square ${(i % 4 + Math.floor(i / 4)) % 2 === 0 ? 'dark' : ''} ${active === i ? 'selected' : ''} ${legal.includes(i) ? 'legal' : ''} ${p !== '.' ? 'occupied' : ''} ${last ? 'last' : ''} ${checked ? 'checked' : ''}" data-square="${i}" aria-label="${label}" ${g.yourTurn ? '' : 'disabled'} ${active === i ? 'aria-pressed="true"' : ''}>${p !== '.' ? `<img src="${pieceUrl(p, skinForPiece(g, p))}" alt="" draggable="false">` : ''}${view % 4 === 0 ? `<span class="coordinate rank">${5 - Math.floor(i / 4)}</span>` : ''}${view >= 16 ? `<span class="coordinate">${String.fromCharCode(97 + i % 4)}</span>` : ''}</button>`;
356 });
357 html += '</div>';
358 if (promotion?.game === g.id) html += `<div class="promotion" role="group" aria-label="Choose promotion"><span class="eyebrow">A NEW POSSIBILITY</span><h3>Promote your pawn</h3><p>Choose the piece for your next chapter.</p><div class="promotion-options">${['q', 'r', 'b', 'n'].map(p => `<button data-promotion="${p}"><img src="${pieceUrl(g.color === 'w' ? p.toUpperCase() : p, displayColorFor(g))}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
359 return html + '</div>';
353 for (let col = 0; col < cols; col++)
354 {
355 const { q, r } = axialOf(col, row);
356 const { x, y } = hexPixel(col, row, size);
357 const k = hexKey(q, r);
358 const wall = walls.has(k);
359 const classes = ['hex-cell', (col + row) % 2 ? 'odd' : '', wall ? 'wall' : '', pathKeys.has(k) ? 'path' : '', holo && holo.q === q && holo.r === r ? 'hologram-hex' : ''].filter(Boolean).join(' ');
360 hexes += `<polygon class="${classes}" data-hex="${k}" points="${hexPoints(x, y, size)}"></polygon>`;
361 }
362 }
363 let sprites = '';
364 for (const u of units)
365 {
366 const { col, row } = offsetOf(u.q, u.r);
367 const { x, y } = hexPixel(col, row, size);
368 const p = unitPiece(u);
369 const src = pieceUrl(p, skinForUnit(g, u));
370 const cls = u.hologram ? 'hex-unit hologram' : 'hex-unit';
371 sprites += `<image class="${cls}" data-unit="${esc(u.id)}" href="${src}" xlink:href="${src}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
372 const [dq, dr] = HEX_DIRS[u.facing ?? 0];
373 const fx = x + dq * size * 0.55, fy = y + dr * size * 0.48;
374 sprites += `<polygon class="hex-facing" points="${fx},${fy - 2.2} ${fx + 2.4},${fy + 1.6} ${fx - 2.4},${fy + 1.6}" transform="rotate(${(u.facing ?? 0) * 60} ${fx} ${fy})"></polygon>`;
375 if (u.role === 'vip') sprites += `<text class="hex-label" x="${x}" y="${y + size * 0.92}" text-anchor="middle">VIP</text>`;
376 }
377 if (holo && mine)
378 {
379 const unit = units.find(u => u.id === mine.unitId);
380 if (unit)
381 {
382 const { col, row } = offsetOf(holo.q, holo.r);
383 const { x, y } = hexPixel(col, row, size);
384 const p = unitPiece(unit);
385 sprites += `<image class="hex-unit hologram" href="${pieceUrl(p, skinForUnit(g, unit))}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
386 const facing = holo.facing ?? unit.facing ?? 0;
387 const front = hexNeighbors(holo.q, holo.r)[facing];
388 if (front)
389 {
390 const fo = offsetOf(front.q, front.r);
391 const fp = hexPixel(fo.col, fo.row, size);
392 sprites += `<polygon class="hex-cell hologram-hex" data-facing-handle="${mine.unitId}" data-hex="${hexKey(front.q, front.r)}" points="${hexPoints(fp.x, fp.y, size * 0.72)}"></polygon>`;
393 }
394 }
395 }
396 let shots = '';
397 if (play?.shots)
398 {
399 for (const sh of play.shots)
400 {
401 const a = units.find(u => u.id === sh.id), b = units.find(u => u.id === (sh.victim || sh.target));
402 if (!a) continue;
403 const ao = offsetOf(a.q, a.r), ap = hexPixel(ao.col, ao.row, size);
404 const aim = sh.aim || b;
405 if (!aim) continue;
406 const bo = offsetOf(aim.q, aim.r), bp = hexPixel(bo.col, bo.row, size);
407 shots += `<line class="hex-shot" x1="${ap.x}" y1="${ap.y}" x2="${bp.x}" y2="${bp.y}"></line>`;
408 }
409 }
410 const planning = g.yourTurn && g.state.phase === 'planning' && !g.state.committed;
411 return `<div class="board-wrap"><svg class="hex-board board" viewBox="0 0 ${width} ${height}" role="group" aria-label="Synhex hex board" ${planning ? '' : 'data-inert="1"'}>${hexes}${shots}${sprites}</svg></div>`;
412 }
413 function hologramOf (g, mine)
414 {
415 if (!mine?.path?.length) return null;
416 const idx = mine.hologramAt == null ? mine.path.length - 1 : mine.hologramAt;
417 return mine.path[Math.max(0, Math.min(mine.path.length - 1, idx))];
418 }
419 function draftPlan (g)
420 {
421 const units = {};
422 if (selected?.game === g.id && selected.unitId)
423 {
424 const rest = g.state.draft?.units || {};
425 Object.assign(units, rest);
426 units[selected.unitId] = { path: selected.path || [], facing: selected.facing };
427 }
428 else Object.assign(units, g.state.draft?.units || {});
429 return { units };
430 }
431 function chooseHex (g, q, r)
432 {
433 if (!g.yourTurn || busy || g.state.phase !== 'planning' || g.state.committed) return;
434 const units = currentUnits(g);
435 const unit = units.find(u => u.q === q && u.r === r && u.team === g.color && u.alive && !u.hologram);
436 if (unit)
437 {
438 if (selected?.game === g.id && selected.unitId === unit.id) selected = null;
439 else selected = { game: g.id, unitId: unit.id, path: [], version: g.version, hologramAt: null };
440 renderGames();
441 return;
442 }
443 if (!selected || selected.game !== g.id) return;
444 const me = units.find(u => u.id === selected.unitId); if (!me) return;
445 const walkable = walkableSet(g);
446 const last = selected.path.length ? selected.path[selected.path.length - 1] : { q: me.q, r: me.r };
447 if (hexDist(last, { q, r }) === 1 && walkable.has(hexKey(q, r)))
448 {
449 selected.path = [...selected.path, { q, r }];
450 selected.hologramAt = selected.path.length - 1;
451 }
452 else
453 {
454 const found = hexPath(last, { q, r }, walkable);
455 if (!found || found.length < 2) { renderGames(); return; }
456 selected.path = selected.path.concat(found.slice(1));
457 selected.hologramAt = selected.path.length - 1;
458 }
459 renderGames();
460 }
461 function setFacing (g, q, r)
462 {
463 if (!selected || selected.game !== g.id || !selected.path.length) return;
464 const idx = selected.hologramAt == null ? selected.path.length - 1 : selected.hologramAt;
465 const wp = selected.path[idx];
466 const dir = HEX_DIRS.findIndex(([dq, dr]) => wp.q + dq === q && wp.r + dr === r);
467 if (dir < 0)
468 {
469 let best = 0, bestD = Infinity;
470 HEX_DIRS.forEach(([dq, dr], i) =>
471 {
472 const d = hexDist({ q: wp.q + dq, r: wp.r + dr }, { q, r });
473 if (d < bestD) { bestD = d; best = i; }
474 });
475 selected.path[idx] = { ...wp, facing: best };
476 }
477 else selected.path[idx] = { ...wp, facing: dir };
478 renderGames();
479 }
480 function clickPathHex (g, q, r)
481 {
482 if (!selected || selected.game !== g.id) return false;
483 const i = selected.path.findIndex(p => p.q === q && p.r === r);
484 if (i < 0) return false;
485 selected.hologramAt = i;
486 renderGames();
487 return true;
488 }
489 function matchmakingCard ()
490 {
491 const searching = state.matchmaking.status === 'searching';
492 return `<article class="game-card"><div class="pending-content"><span class="big-icon">⬡</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
493 }
494 function renderMatchmaking ()
495 {
496 const target = $('#matchmaking-actions');
497 if (!target || !state) return;
498 target.innerHTML = state.matchmaking?.status === 'searching'
499 ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
500 : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
360 501 }
361 502 function renderFriends ()
362 503 {
@@ -385,50 +526,47 @@ function showRivalry (id)
385 526 $('#modal-content').dataset.friend = id;
386 527 $('#modal-content').dataset.rivalry = id;
387 528 }
388 function refreshRivalry ()
389 {
390 const id = $('#modal-content').dataset.rivalry;
391 if (modal.open && id) showRivalry(id);
392 }
393 function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.check ? 'You are in check. Find a move that protects your king.' : 'Take your time. The board will be here.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered. Make your move to pass the offer to your opponent.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}${g.claimable ? '<button class="secondary" data-option="claim_draw">Claim draw</button>' : '<button class="secondary" data-option="claim-intended">Claim draw with intended move</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; }
394 function chooseSquare (g, i)
395 {
396 if (!g.yourTurn || busy || promotion) return;
397 if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
398 const p = g.state.board[i];
399 if (p !== '.' && (p === p.toUpperCase() ? 'w' : 'b') === g.color) { selected = selected?.game === g.id && selected.from === i ? null : { game: g.id, from: i, version: g.version }; }
400 else selected = null;
401 renderGames();
402 }
403 let claimIntended = null;
404 function attemptMove (g, from, to, promote)
405 {
406 const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
407 if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
408 const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
409 action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
410 }
411 function matchmakingCard ()
412 {
413 const searching = state.matchmaking.status === 'searching';
414 return `<article class="game-card"><div class="pending-content"><span class="big-icon">♘</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
415 }
416 function renderMatchmaking ()
417 {
418 const target = $('#matchmaking-actions');
419 if (!target || !state) return;
420 target.innerHTML = state.matchmaking?.status === 'searching'
421 ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
422 : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
423 }
529 function refreshRivalry () { const id = $('#modal-content').dataset.rivalry; if (modal.open && id) showRivalry(id); }
530 function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.state?.phase === 'planning' ? 'Plan paths for your four operatives, then lock the plan. The act runs when both of you commit.' : 'Watch the same server-computed act, then plan again.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; }
424 531 async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
425 532 if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
426 533 if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
427 if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.microchessPwa?.settings(); };
428 if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">MICROCHESS</span><h2>Small board. Real chess.</h2><p>The usual rules of chess, on a 4 × 5 board.</p><ul class="rules-list"><li>Each side starts with a king, rook, bishop, knight and one pawn. White moves first.</li><li>Pawns move one square forward, capture diagonally and never move two squares. There is no castling or en passant.</li><li>Reach the last rank to promote to a queen, rook, bishop or knight.</li><li>Protect your king. Checkmate wins; stalemate and dead positions draw.</li><li>Claim a draw after three repetitions or 50 moves by each side without a pawn move or capture. You may also claim with an intended move, via the game menu. Five repetitions or 75 moves draw automatically.</li><li>Click a piece to see legal destinations, then click a dot. Or drag it to a destination.</li><li>The bar below your opponent’s name compares remaining material: White on the left, Black on the right. Pawn 1, knight/bishop 3, rook 5, queen 9; kings are not counted.</li><li>After your move, a blue pulse marks a clear estimated gain; red marks a likely material loss or mating threat. This quick tactical check can miss deeper ideas. Quiet or uncertain moves get no pulse.</li></ul><p class="inline-note">Pieces by Cburnett, from <a href="https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces" target="_blank" rel="noreferrer">Wikimedia Commons</a>, <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank" rel="noreferrer">CC BY-SA 3.0</a>. Unmodified SVGs.</p>`);
534 if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.synhexPwa?.settings(); };
535 if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">SYNHEX</span><h2>Plan together. Fire together.</h2><p>Simultaneous-turn hex tactics. Both players plan, then the server simulates a 3-second act.</p><ul class="rules-list"><li>The board is a 17 × 14 pointy-top hex grid (odd-r), with random walls. Each side has a VIP (pistol), two SMG soldiers and a shotgun soldier.</li><li>If your VIP dies, you lose.</li><li>Click a unit, then click hexes or drag a path. The path end is a hologram. Click a waypoint to place the hologram there; drag the facing hex in front of it to set look direction.</li><li>Re-click a unit to clear its path. Lock your plan; when both players lock, the act runs.</li><li>Press Play to watch the same server-computed result, then plan the next act.</li><li>Units walk up to 5 hexes per act. They shoot enemies in a forward 120° cone with line of sight. Hits are instant kills. Friendly fire is possible.</li><li>Accuracy starts at 15% plus bonuses for standing still, aiming dead-ahead, close range, focus fire, and more — see <code>lib/game-config.php</code>.</li><li>Enemies are visible at match start, when in your cone and LoS, or when they fire; otherwise a hologram marks their last known position.</li></ul>`);
536 function playTimeline (g)
537 {
538 const tl = g.state?.timeline; if (!tl) { action({ action: 'ack_playback', game: g.id, version: g.version }); return; }
539 const snaps = tl.snapshots || [];
540 if (!snaps.length || matchMedia('(prefers-reduced-motion: reduce)').matches)
541 {
542 playback.set(g.id, { units: tl.endUnits || snaps.at(-1)?.units, shots: tl.shots || [] });
543 renderGames();
544 action({ action: 'ack_playback', game: g.id, version: g.version });
545 return;
546 }
547 let i = 0;
548 const play = { timer: null };
549 const step = () =>
550 {
551 const snap = snaps[Math.min(i, snaps.length - 1)];
552 const shots = (tl.shots || []).filter(s => s.t === snap.t);
553 playback.set(g.id, { units: snap.units, shots, timer: play.timer });
554 renderGames();
555 i++;
556 if (i >= snaps.length)
557 {
558 clearInterval(play.timer);
559 playback.set(g.id, { units: tl.endUnits || snap.units, shots: [] });
560 renderGames();
561 action({ action: 'ack_playback', game: g.id, version: g.version }, () => playback.delete(g.id));
562 }
563 };
564 step();
565 play.timer = setInterval(step, Math.max(30, Math.min(120, Math.floor((tl.durationMs || 3000) / Math.max(1, snaps.length)))));
566 }
429 567 document.addEventListener('click', e =>
430 568 {
431 const el = e.target.closest('button'); if (!el) return;
569 const el = e.target.closest('button, polygon, image'); if (!el) return;
432 570 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
433 571 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
434 572 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
@@ -436,10 +574,27 @@ document.addEventListener('click', e =>
436 574 if (el.id === 'avatar-button') chooseAvatar();
437 575 if (el.id === 'color-pref-button') openColorPreferences();
438 576 if (el.dataset.createLink) createLink(el.dataset.createLink);
439 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
440 if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
441 if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
442 if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
577 if (el.dataset.hex && g)
578 {
579 if (suppressClick) { suppressClick = false; return; }
580 const [q, r] = el.dataset.hex.split(',').map(Number);
581 if (el.hasAttribute('data-facing-handle')) { setFacing(g, q, r); return; }
582 if (clickPathHex(g, q, r)) return;
583 chooseHex(g, q, r);
584 }
585 if (el.dataset.unit && g)
586 {
587 const u = currentUnits(g).find(u => u.id === el.dataset.unit);
588 if (u) chooseHex(g, u.q, u.r);
589 }
590 if (el.dataset.gameAction && g)
591 {
592 if (el.dataset.gameAction === 'stop-confirm') showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
593 else if (el.dataset.gameAction === 'options') options(g);
594 else if (el.dataset.gameAction === 'commit') action({ action: 'commit_plan', game: g.id, version: g.version, plan: draftPlan(g) });
595 else if (el.dataset.gameAction === 'play') playTimeline(g);
596 else action({ action: el.dataset.gameAction, game: g.id, version: g.version });
597 }
443 598 if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
444 599 });
445 600 $('#modal-content').addEventListener('click', async e =>
@@ -451,8 +606,8 @@ $('#modal-content').addEventListener('click', async e =>
451 606 if (b.dataset.modalAction === 'close') closeModal();
452 607 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
453 608 if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } }
454 if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.microchessPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
455 if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.microchessPwa?.endpoint() }, () => location.reload());
609 if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.synhexPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
610 if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.synhexPwa?.endpoint() }, () => location.reload());
456 611 if (b.dataset.friendAction)
457 612 {
458 613 const id = $('#modal-content').dataset.friend;
@@ -463,7 +618,6 @@ $('#modal-content').addEventListener('click', async e =>
463 618 {
464 619 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
465 620 if (b.dataset.option === 'resign-confirm') { showModal('<h2>Resign this game?</h2><p>Your opponent will win this game. You can request a rematch afterwards.</p><div class="actions"><button class="danger" data-option="resign">Resign</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); return; }
466 if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
467 621 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
468 622 }
469 623 });
@@ -471,23 +625,43 @@ $('#modal-content').addEventListener('change', e => { if (e.target.id === 'avata
471 625 let suppressClick = false;
472 626 document.addEventListener('pointerdown', e =>
473 627 {
474 const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
475 const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
476 const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
477 drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
628 const cell = e.target.closest('[data-hex], [data-unit]'); if (!cell || e.button !== 0 || busy) return;
629 const g = state?.games.find(g => g.id === Number(cell.closest('[data-game]').dataset.game)); if (!g?.yourTurn || g.state?.phase !== 'planning' || g.state.committed) return;
630 if (cell.hasAttribute('data-facing-handle'))
631 {
632 drag = { kind: 'facing', game: g.id, id: e.pointerId };
633 return;
634 }
635 const unitId = cell.dataset.unit || currentUnits(g).find(u => hexKey(u.q, u.r) === cell.dataset.hex && u.team === g.color && u.alive && !u.hologram)?.id;
636 if (!unitId) return;
637 const unit = currentUnits(g).find(u => u.id === unitId);
638 selected = { game: g.id, unitId, path: [], version: g.version, hologramAt: null };
639 drag = { kind: 'path', game: g.id, unitId, last: { q: unit.q, r: unit.r }, id: e.pointerId, moving: false };
640 renderGames();
478 641 });
479 642 document.addEventListener('pointermove', e =>
480 643 {
481 644 if (!drag || e.pointerId !== drag.id) return;
482 if (!drag.moving && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) > 7) { drag.moving = true; const g = state.games.find(g => g.id === drag.game); selected = { game: g.id, from: drag.from, version: g.version }; renderGames(); const img = document.createElement('img'); img.className = 'drag-ghost'; img.src = pieceUrl(drag.p, skinForPiece(state?.games?.find(x => x.id === drag.game), drag.p)); document.body.append(img); }
483 if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
645 const g = state.games.find(g => g.id === drag.game); if (!g) return;
646 const el = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-hex]');
647 if (!el) return;
648 const [q, r] = el.dataset.hex.split(',').map(Number);
649 if (drag.kind === 'facing') { setFacing(g, q, r); return; }
650 if (hexDist(drag.last, { q, r }) !== 1) return;
651 if (!walkableSet(g).has(hexKey(q, r))) return;
652 drag.moving = true;
653 selected.path = [...(selected.path || []), { q, r }];
654 selected.hologramAt = selected.path.length - 1;
655 drag.last = { q, r };
656 renderGames();
484 657 }, { passive: false });
485 658 document.addEventListener('pointerup', e =>
486 659 {
487 if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
488 if (d.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); const sq = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-square]'); if (sq && Number(sq.closest('[data-game]').dataset.game) === d.game) attemptMove(state.games.find(g => g.id === d.game), d.from, Number(sq.dataset.square)); }
660 if (!drag || e.pointerId !== drag.id) return;
661 if (drag.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); }
662 drag = null;
489 663 });
490 document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
664 document.addEventListener('pointercancel', () => { drag = null; });
491 665 refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
492 666
493 667 let replay = null, replayTimer = null, historyRequest = 0;
@@ -521,7 +695,7 @@ async function openReplay (id)
521 695 }
522 696 function showReplay (game)
523 697 {
524 const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Microchess ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>';
698 const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Synhex ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>';
525 699 if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; }
526 700 else { showModal(content); modal.classList.add('replay-modal'); }
527 701 replay = { ...game, index: 0 };
@@ -532,7 +706,6 @@ async function copyReplayLink ()
532 706 const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken);
533 707 try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); }
534 708 catch {
535 // Keep a usable copy fallback when clipboard access is unavailable.
536 709 const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link');
537 710 $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.');
538 711 }
@@ -540,12 +713,13 @@ async function copyReplayLink ()
540 713 function renderReplay ()
541 714 {
542 715 if (!replay || !$('#replay-card')) return;
543 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] };
716 const frame = replay.positions[replay.index] || { units: [], walls: [], grid: { cols: 17, rows: 14 } };
717 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], state: { phase: 'replay', grid: frame.grid, walls: frame.walls, units: (frame.units || []).map(u => ({ ...u, hologram: false })), act: frame.act } };
544 718 const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White';
545 719 const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black';
546 720 $('#replay-card').innerHTML = `<article class="game-card" data-game="replay"><div class="card-header replay-players" id="modal-title"><span title="${esc(whiteTip)}"><img src="${pieceUrl('K', replay.pieceSkinWhite || 'White')}" alt="${esc(replay.pieceSkinWhite || 'White')}">${esc(replay.whiteName)}</span><span aria-hidden="true">–</span><span title="${esc(blackTip)}"><img src="${pieceUrl('k', replay.pieceSkinBlack || 'Black')}" alt="${esc(replay.pieceSkinBlack || 'Black')}">${esc(replay.blackName)}</span></div>${board(g)}</article>`;
547 $('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
548 const last = replay.positions.length - 1;
721 $('#replay-progress').textContent = `${replay.index} / ${Math.max(0, replay.positions.length - 1)} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
722 const last = Math.max(0, replay.positions.length - 1);
549 723 $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶';
550 724 $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play');
551 725 $('[data-replay-control="play"]').disabled = last < 1;
@@ -571,7 +745,7 @@ $('#modal-content').addEventListener('click', e => {
571 745 }
572 746 } else {
573 747 stopReplay();
574 const last = replay.positions.length - 1;
748 const last = Math.max(0, replay.positions.length - 1);
575 749 replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1)));
576 750 }
577 751 renderReplay();
@@ -579,9 +753,10 @@ $('#modal-content').addEventListener('click', e => {
579 753 const savedAnimations = new Set();
580 754 function animateSavedGames ()
581 755 {
756 if (!state?.games) return;
582 757 for (const g of state.games) {
583 758 if (!g.replayId) continue;
584 const key = `microchess-saved:${state.user.id}:${g.replayId}`;
759 const key = `synhex-saved:${state.user.id}:${g.replayId}`;
585 760 let seen = savedAnimations.has(key);
586 761 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
587 762 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
@@ -1,43 +1,48 @@
1'use strict';
1'use strict';
2const $ = (s, root = document) => root.querySelector(s);
2const $ = (s, root = document) => root.querySelector(s);
3const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
3const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4// Server embeds the deploy commit in <meta name="asset-version">; append to static URLs.
5const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
4const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
6const withAssetVersion = url => {
5const withAssetVersion = url => {
7 if (!assetVersion) return url;
6 if (!assetVersion) return url;
8 return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion);
7 return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion);
9};
8};
10(() => {
9(() => {
11 // Backup only: HTML already no-stores and links use ?v=. Helps stuck PWA/shell tabs.
12 if (!assetVersion) return;
10 if (!assetVersion) return;
13 const key = 'microchess-asset-version';
11 const key = 'synhex-asset-version';
14 const prev = localStorage.getItem(key);
12 const prev = localStorage.getItem(key);
15 if (prev === assetVersion) return;
13 if (prev === assetVersion) return;
16 localStorage.setItem(key, assetVersion);
14 localStorage.setItem(key, assetVersion);
17 if (prev) location.reload();
15 if (prev) location.reload();
18})();
16})();
19const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
20const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
21const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
17const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
22const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
18const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
23const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
19const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
24function customColoursDisabled ()
20const HEX_DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
25{
21const HEX_SIZE = 12;
26 // Account preference (default off → custom colours visible).
22function customColoursDisabled () { return !!(state?.user?.disableCustomColours); }
27 return !!(state?.user?.disableCustomColours);
28}
29const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`);
23const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`);
30const pieceUrl = (p, skin) =>
24const pieceUrl = (p, skin) =>
31{
25{
32 if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p);
26 if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p);
33 return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`);
27 return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`);
34};
28};
35function skinForPiece (g, p)
29function unitLetter (u)
36{
30{
37 if (!g || p === '.') return null;
31 if (u.role === 'vip') return 'k';
38 const whiteSkin = g.pieceSkinWhite || 'White';
32 if (u.weapon === 'shotgun') return 'r';
39 const blackSkin = g.pieceSkinBlack || 'Black';
33 return 'n';
40 return p === p.toUpperCase() ? whiteSkin : blackSkin;
34}
35function unitPiece (u) { const g = unitLetter(u); return u.team === 'w' ? g.toUpperCase() : g; }
36function unitLabel (u)
37{
38 if (u.role === 'vip') return 'VIP (pistol)';
39 if (u.weapon === 'shotgun') return 'Soldier (shotgun)';
40 return 'Soldier (SMG)';
41}
42function skinForUnit (g, u)
43{
44 if (!g) return null;
45 return u.team === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black');
41}
46}
42function displayColorFor (g)
47function displayColorFor (g)
43{
48{
@@ -51,13 +56,9 @@ function colorTagMarkup (g)
51 const display = displayColorFor(g);
56 const display = displayColorFor(g);
52 const rules = rulesColorLabel(g);
57 const rules = rulesColorLabel(g);
53 const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`;
58 const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`;
54 const disc = display.toLowerCase();
59 return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(display.toLowerCase())}"></span>${esc(display)}</span>`;
55 return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(disc)}"></span>${esc(display)}</span>`;
56}
57function kingAvatarUrl (color)
58{
59 return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`);
60}
60}
61function kingAvatarUrl (color) { return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`); }
61function nextColorSkipping (current, skip)
62function nextColorSkipping (current, skip)
62{
63{
63 let i = PIECE_COLOR_ORDER.indexOf(current);
64 let i = PIECE_COLOR_ORDER.indexOf(current);
@@ -98,7 +99,6 @@ function renderAvatarChoices ()
98 $('#avatar-option-count').textContent = `${options.length} pieces`;
99 $('#avatar-option-count').textContent = `${options.length} pieces`;
99 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
100 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
100}
101}
101
102function openColorPreferences ()
102function openColorPreferences ()
103{
103{
104 if (!state) return;
104 if (!state) return;
@@ -110,7 +110,7 @@ function openColorPreferences ()
110 if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred);
110 if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred);
111 const paint = () =>
111 const paint = () =>
112 {
112 {
113 showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your pieces look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
113 showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your operatives look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
114 $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); };
114 $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); };
115 $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); };
115 $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); };
116 document.querySelectorAll('[data-color-role]').forEach(btn =>
116 document.querySelectorAll('[data-color-role]').forEach(btn =>
@@ -134,10 +134,8 @@ function openColorPreferences ()
134 paint();
134 paint();
135}
135}
136
136
137let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
137let state, selected = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
138const moveHolds = new Map();
138const playback = new Map();
139const moveFeedback = new Map();
140let moveHoldTimer;
141let inviteToken = new URLSearchParams(location.search).get('invite');
139let inviteToken = new URLSearchParams(location.search).get('invite');
142const modal = $('#modal');
140const modal = $('#modal');
143function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
141function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
@@ -166,7 +164,7 @@ if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
166if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
164if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
167if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
165if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
168if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
166if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
169document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
167document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; renderGames(); } });
170async function api (data)
168async function api (data)
171{
169{
172 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
170 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
@@ -178,12 +176,7 @@ async function action (data, success)
178 try
176 try
179 {
177 {
180 const result = await api(data);
178 const result = await api(data);
181 if (data.action === 'move')
179 selected = null; if (success) await success(result); await refresh(true);
182 {
183 moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null });
184 if (['good', 'poor'].includes(result.feedback?.quality)) moveFeedback.set(data.game, { user: state.user.id, ply: result.feedback.ply, quality: result.feedback.quality, start: null });
185 }
186 selected = null; promotion = null; if (success) await success(result); await refresh(true);
187 }
180 }
188 catch (e) { toast(e.message); await refresh(true); }
181 catch (e) { toast(e.message); await refresh(true); }
189 finally { busy = false; }
182 finally { busy = false; }
@@ -198,165 +191,313 @@ async function refresh (force = false)
198 if (response.status === 401) { showModal('<h2>Sign in to continue</h2><p>Your session has expired. Your games are saved.</p><a class="button primary" href="auth.php' + esc(location.search || '') + '">Sign in</a>'); return; }
191 if (response.status === 401) { showModal('<h2>Sign in to continue</h2><p>Your session has expired. Your games are saved.</p><a class="button primary" href="auth.php' + esc(location.search || '') + '">Sign in</a>'); return; }
199 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
192 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
200 state = data;
193 state = data;
201 window.microchessPwa?.sync();
194 window.synhexPwa?.sync();
202 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
195 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version || g.state?.phase !== 'planning') selected = null; }
203 const signature = JSON.stringify(data);
196 const signature = JSON.stringify(data);
204 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
197 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
205 if (data.invite && !inviteShown)
198 if (data.invite && !inviteShown)
206 {
199 {
207 inviteShown = true; const i = data.invite;
200 inviteShown = true; const i = data.invite;
208 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
201 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
209 else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
202 else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'Lock your plan. The act plays when you both commit.'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
210 }
203 }
211 window.microchessPwa?.intro();
204 window.synhexPwa?.intro();
212 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
205 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
213}
206}
214function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
207function empty (yours) { return `<div class="empty"><span class="empty-icon">⬡</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is planning or watching playback.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
215function renderGames ()
208function renderGames ()
216{
209{
217 if (!state) return;
210 if (!state) return;
218 clearTimeout(moveHoldTimer);
211 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming).sort((a, b) => a.turnOrder - b.turnOrder || a.id - b.id);
219 let relocating = false;
220 const now = performance.now();
221 for (const [id, hold] of moveHolds)
222 {
223 const g = state.games.find(g => g.id === id);
224 if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
225 {
226 moveHolds.delete(id); continue;
227 }
228 // Start the pause when the confirmed board position is first displayed.
229 if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
230 if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
231 }
232 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
233 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
234 const selector = '#main .game-card, .waiting-heading, #main > footer';
235 const key = el => el.dataset.game || el.tagName;
236 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
237 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
238 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
239 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming || moveHolds.has(g.id)).sort((a, b) => (moveHolds.get(a.id)?.turnOrder ?? a.turnOrder) - (moveHolds.get(b.id)?.turnOrder ?? b.turnOrder) || a.id - b.id);
240 const waiting = state.games.filter(g => !yours.includes(g));
212 const waiting = state.games.filter(g => !yours.includes(g));
241 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
213 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
242 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
243 const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el =>
244 {
245 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
246 return [el.closest('[data-game]').dataset.game, { share: new DOMMatrixReadOnly(getComputedStyle(fill).transform).a, target: el.dataset.share, remaining: animation ? Math.max(0, 650 - Number(animation.currentTime)) : 650 }];
247 }));
248 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
214 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
249 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
215 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
250 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
251 for (const el of document.querySelectorAll('#main .material-bar'))
216 for (const el of document.querySelectorAll('#main .material-bar'))
252 {
217 {
253 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
218 const fill = $('.material-white', el), share = Number(el.dataset.share);
254 // Prefer WAAPI over element.style — CSP style-src 'self' blocks inline CSSOM writes.
219 fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' });
255 if (!reduced && old && Math.abs(old.share - share) > .0001)
256 fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear', fill: 'forwards' });
257 else
258 fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' });
259 }
260 renderMoveFeedback(now, reduced);
261 window.microchessPwa?.highlight();
262 if (animate)
263 {
264 for (const el of document.querySelectorAll(selector))
265 {
266 const old = before.get(key(el));
267 el.getAnimations().forEach(animation => animation.cancel());
268 if (!old) continue;
269 const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
270 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
271 el.animate([
272 { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
273 { transform: 'translate(0, 0)', zIndex: 2 }
274 ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
275 }
276 }
220 }
221 window.synhexPwa?.highlight();
277}
222}
278function card (g)
223function card (g)
279{
224{
280 let content = '';
225 let content = '';
281 if (g.replay) content = board(g);
226 if (g.replay) content = board(g);
282 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
227 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">⬡</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
283 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
228 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
284 else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`;
229 else content = board(g) + footer(g);
285 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
230 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
286}
231}
287function materialBarSkinName (name, fallback)
232function footer (g)
288{
233{
289 return PIECE_COLOR_ORDER.includes(name) ? name : fallback;
234 const phase = g.state?.phase;
235 let status = 'Waiting';
236 let extra = '';
237 if (phase === 'planning')
238 {
239 status = g.state.committed ? 'Plan locked' : (g.yourTurn ? 'Plan your act' : 'Waiting for a plan');
240 if (g.yourTurn && !g.state.committed) extra = `<button class="primary" data-game-action="commit">Lock plan</button>`;
241 else extra = `<span>Act ${g.state.act + 1}</span>`;
242 }
243 else if (phase === 'playback')
244 {
245 status = g.state.acked ? 'Waiting for opponent' : 'Act ready';
246 if (g.yourTurn && !g.state.acked) extra = `<button class="primary" data-game-action="play">Play</button>`;
247 else extra = `<span>Act ${g.state.act}</span>`;
248 }
249 return `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${status}</span>${g.yourTurn ? `<span class="footer-actions">${extra}<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button></span>` : extra}</div>`;
290}
250}
251function materialBarSkinName (name, fallback) { return PIECE_COLOR_ORDER.includes(name) ? name : fallback; }
291function materialBarSkins (g)
252function materialBarSkins (g)
292{
253{
293 if (customColoursDisabled()) return { left: 'White', right: 'Black' };
254 if (customColoursDisabled()) return { left: 'White', right: 'Black' };
294 return {
255 return { left: materialBarSkinName(g.pieceSkinWhite, 'White'), right: materialBarSkinName(g.pieceSkinBlack, 'Black') };
295 left: materialBarSkinName(g.pieceSkinWhite, 'White'),
296 right: materialBarSkinName(g.pieceSkinBlack, 'Black')
297 };
298}
256}
299function materialBar (g)
257function materialBar (g)
300{
258{
301 const totals = { w: 0, b: 0 };
259 const totals = g.strength || { w: 0, b: 0 };
302 for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
303 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
260 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
304 const { left, right } = materialBarSkins(g);
261 const { left, right } = materialBarSkins(g);
305 const you = g.color === 'w' ? left : right;
262 const you = g.color === 'w' ? left : right;
306 const label = `${left}: ${totals.w} material points. ${right}: ${totals.b} material points. You play ${you}${you === 'White' || you === 'Black' ? '' : ` (${g.color === 'w' ? 'White' : 'Black'})`}.`;
263 const label = `${left}: ${totals.w} strength. ${right}: ${totals.b} strength. You play ${you}. VIP 3 · Soldier 1.`;
307 const ariaSides = left === 'White' && right === 'Black'
264 return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Team strength" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)}" tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`;
308 ? 'White on the left and Black on the right'
309 : `${left} (White) on the left and ${right} (Black) on the right`;
310 // Classes only — inline style= is blocked by CSP style-src 'self'.
311 return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Material balance, ${esc(ariaSides)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)} Pawn 1 · Knight/Bishop 3 · Rook 5 · Queen 9. Kings are not counted." tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`;
312}
265}
313function renderMoveFeedback (now, reduced)
266function hexKey (q, r) { return q + ',' + r; }
267function offsetOf (q, r) { return { col: q + Math.floor(r / 2), row: r }; }
268function axialOf (col, row) { return { q: col - Math.floor(row / 2), r: row }; }
269function hexDist (a, b) { return (Math.abs(a.q - b.q) + Math.abs(a.q + a.r - b.q - b.r) + Math.abs(a.r - b.r)) / 2; }
270function hexNeighbors (q, r) { return HEX_DIRS.map(([dq, dr]) => ({ q: q + dq, r: r + dr })); }
271function hexPixel (col, row, size)
314{
272{
315 for (const [id, feedback] of moveFeedback)
273 const w = Math.sqrt(3) * size;
274 return { x: w * (col + 0.5 * (row & 1)) + size * Math.sqrt(3), y: size * 1.5 * row + size * 1.2, w };
275}
276function hexPoints (cx, cy, size)
277{
278 const pts = [];
279 for (let i = 0; i < 6; i++)
280 {
281 const a = Math.PI / 180 * (60 * i - 30);
282 pts.push(`${cx + size * Math.cos(a)},${cy + size * Math.sin(a)}`);
283 }
284 return pts.join(' ');
285}
286function walkableSet (g)
287{
288 const walls = new Set(g.state.walls || []);
289 const set = new Set();
290 const cols = g.state.grid.cols, rows = g.state.grid.rows;
291 for (let row = 0; row < rows; row++) for (let col = 0; col < cols; col++)
316 {
292 {
317 const g = state.games.find(g => g.id === id);
293 const { q, r } = axialOf(col, row);
318 if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
294 const k = hexKey(q, r);
319 if (g.state.ply !== feedback.ply) continue;
295 if (!walls.has(k)) set.add(k);
320 if (feedback.start === null)
296 }
297 return set;
298}
299function hexPath (from, to, walkable)
300{
301 const start = hexKey(from.q, from.r), goal = hexKey(to.q, to.r);
302 if (!walkable.has(start) || !walkable.has(goal)) return null;
303 if (start === goal) return [from];
304 const open = new Map([[start, 0]]), came = new Map(), gScore = new Map([[start, 0]]);
305 while (open.size)
306 {
307 let current = null, best = Infinity;
308 for (const [k, f] of open) if (f < best) { best = f; current = k; }
309 open.delete(current);
310 if (current === goal)
311 {
312 const path = [];
313 while (current !== start) { const [q, r] = current.split(',').map(Number); path.push({ q, r }); current = came.get(current); }
314 path.push(from);
315 return path.reverse();
316 }
317 const [cq, cr] = current.split(',').map(Number);
318 for (const n of hexNeighbors(cq, cr))
321 {
319 {
322 feedback.start = now;
320 const nk = hexKey(n.q, n.r);
323 setTimeout(() =>
321 if (!walkable.has(nk)) continue;
322 const tg = gScore.get(current) + 1;
323 if (!gScore.has(nk) || tg < gScore.get(nk))
324 {
324 {
325 if (moveFeedback.get(id) !== feedback) return;
325 came.set(nk, current); gScore.set(nk, tg); open.set(nk, tg + hexDist(n, to));
326 moveFeedback.delete(id);
326 }
327 document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
328 }, 1800);
329 }
327 }
330 const elapsed = now - feedback.start;
331 if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
332 const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
333 const overlay = document.createElement('div');
334 overlay.className = `move-feedback ${feedback.quality}`;
335 const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
336 el.append(overlay);
337 if (reduced) { overlay.style.opacity = '1'; continue; }
338 const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
339 const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
340 animation.currentTime = elapsed;
341 }
328 }
329 return null;
330}
331function currentUnits (g)
332{
333 const play = playback.get(g.id);
334 if (play?.units) return play.units;
335 return g.state?.units || [];
342}
336}
343function board (g)
337function board (g)
344{
338{
345 const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
339 if (!g.state?.grid) return '<div class="board-wrap"><p class="inline-note">Loading board…</p></div>';
346 const active = selected?.game === g.id ? selected.from : null;
340 const cols = g.state.grid.cols, rows = g.state.grid.rows;
347 const legal = g.legal.filter(m => m.from === active).map(m => m.to);
341 const size = HEX_SIZE;
348 let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
342 const width = Math.sqrt(3) * size * (cols + 1.2);
349 indices.forEach((i, view) =>
343 const height = size * 1.5 * rows + size * 2.2;
344 const walls = new Set(g.state.walls || []);
345 const units = currentUnits(g);
346 const mine = selected?.game === g.id ? selected : null;
347 const pathKeys = new Set((mine?.path || []).map(p => hexKey(p.q, p.r)));
348 const holo = hologramOf(g, mine);
349 const play = playback.get(g.id);
350 let hexes = '';
351 for (let row = 0; row < rows; row++)
350 {
352 {
351 const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
353 for (let col = 0; col < cols; col++)
352 const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
354 {
353 const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
355 const { q, r } = axialOf(col, row);
354 const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
356 const { x, y } = hexPixel(col, row, size);
355 html += `<button class="square ${(i % 4 + Math.floor(i / 4)) % 2 === 0 ? 'dark' : ''} ${active === i ? 'selected' : ''} ${legal.includes(i) ? 'legal' : ''} ${p !== '.' ? 'occupied' : ''} ${last ? 'last' : ''} ${checked ? 'checked' : ''}" data-square="${i}" aria-label="${label}" ${g.yourTurn ? '' : 'disabled'} ${active === i ? 'aria-pressed="true"' : ''}>${p !== '.' ? `<img src="${pieceUrl(p, skinForPiece(g, p))}" alt="" draggable="false">` : ''}${view % 4 === 0 ? `<span class="coordinate rank">${5 - Math.floor(i / 4)}</span>` : ''}${view >= 16 ? `<span class="coordinate">${String.fromCharCode(97 + i % 4)}</span>` : ''}</button>`;
357 const k = hexKey(q, r);
356 });
358 const wall = walls.has(k);
357 html += '</div>';
359 const classes = ['hex-cell', (col + row) % 2 ? 'odd' : '', wall ? 'wall' : '', pathKeys.has(k) ? 'path' : '', holo && holo.q === q && holo.r === r ? 'hologram-hex' : ''].filter(Boolean).join(' ');
358 if (promotion?.game === g.id) html += `<div class="promotion" role="group" aria-label="Choose promotion"><span class="eyebrow">A NEW POSSIBILITY</span><h3>Promote your pawn</h3><p>Choose the piece for your next chapter.</p><div class="promotion-options">${['q', 'r', 'b', 'n'].map(p => `<button data-promotion="${p}"><img src="${pieceUrl(g.color === 'w' ? p.toUpperCase() : p, displayColorFor(g))}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
360 hexes += `<polygon class="${classes}" data-hex="${k}" points="${hexPoints(x, y, size)}"></polygon>`;
359 return html + '</div>';
361 }
362 }
363 let sprites = '';
364 for (const u of units)
365 {
366 const { col, row } = offsetOf(u.q, u.r);
367 const { x, y } = hexPixel(col, row, size);
368 const p = unitPiece(u);
369 const src = pieceUrl(p, skinForUnit(g, u));
370 const cls = u.hologram ? 'hex-unit hologram' : 'hex-unit';
371 sprites += `<image class="${cls}" data-unit="${esc(u.id)}" href="${src}" xlink:href="${src}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
372 const [dq, dr] = HEX_DIRS[u.facing ?? 0];
373 const fx = x + dq * size * 0.55, fy = y + dr * size * 0.48;
374 sprites += `<polygon class="hex-facing" points="${fx},${fy - 2.2} ${fx + 2.4},${fy + 1.6} ${fx - 2.4},${fy + 1.6}" transform="rotate(${(u.facing ?? 0) * 60} ${fx} ${fy})"></polygon>`;
375 if (u.role === 'vip') sprites += `<text class="hex-label" x="${x}" y="${y + size * 0.92}" text-anchor="middle">VIP</text>`;
376 }
377 if (holo && mine)
378 {
379 const unit = units.find(u => u.id === mine.unitId);
380 if (unit)
381 {
382 const { col, row } = offsetOf(holo.q, holo.r);
383 const { x, y } = hexPixel(col, row, size);
384 const p = unitPiece(unit);
385 sprites += `<image class="hex-unit hologram" href="${pieceUrl(p, skinForUnit(g, unit))}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
386 const facing = holo.facing ?? unit.facing ?? 0;
387 const front = hexNeighbors(holo.q, holo.r)[facing];
388 if (front)
389 {
390 const fo = offsetOf(front.q, front.r);
391 const fp = hexPixel(fo.col, fo.row, size);
392 sprites += `<polygon class="hex-cell hologram-hex" data-facing-handle="${mine.unitId}" data-hex="${hexKey(front.q, front.r)}" points="${hexPoints(fp.x, fp.y, size * 0.72)}"></polygon>`;
393 }
394 }
395 }
396 let shots = '';
397 if (play?.shots)
398 {
399 for (const sh of play.shots)
400 {
401 const a = units.find(u => u.id === sh.id), b = units.find(u => u.id === (sh.victim || sh.target));
402 if (!a) continue;
403 const ao = offsetOf(a.q, a.r), ap = hexPixel(ao.col, ao.row, size);
404 const aim = sh.aim || b;
405 if (!aim) continue;
406 const bo = offsetOf(aim.q, aim.r), bp = hexPixel(bo.col, bo.row, size);
407 shots += `<line class="hex-shot" x1="${ap.x}" y1="${ap.y}" x2="${bp.x}" y2="${bp.y}"></line>`;
408 }
409 }
410 const planning = g.yourTurn && g.state.phase === 'planning' && !g.state.committed;
411 return `<div class="board-wrap"><svg class="hex-board board" viewBox="0 0 ${width} ${height}" role="group" aria-label="Synhex hex board" ${planning ? '' : 'data-inert="1"'}>${hexes}${shots}${sprites}</svg></div>`;
412}
413function hologramOf (g, mine)
414{
415 if (!mine?.path?.length) return null;
416 const idx = mine.hologramAt == null ? mine.path.length - 1 : mine.hologramAt;
417 return mine.path[Math.max(0, Math.min(mine.path.length - 1, idx))];
418}
419function draftPlan (g)
420{
421 const units = {};
422 if (selected?.game === g.id && selected.unitId)
423 {
424 const rest = g.state.draft?.units || {};
425 Object.assign(units, rest);
426 units[selected.unitId] = { path: selected.path || [], facing: selected.facing };
427 }
428 else Object.assign(units, g.state.draft?.units || {});
429 return { units };
430}
431function chooseHex (g, q, r)
432{
433 if (!g.yourTurn || busy || g.state.phase !== 'planning' || g.state.committed) return;
434 const units = currentUnits(g);
435 const unit = units.find(u => u.q === q && u.r === r && u.team === g.color && u.alive && !u.hologram);
436 if (unit)
437 {
438 if (selected?.game === g.id && selected.unitId === unit.id) selected = null;
439 else selected = { game: g.id, unitId: unit.id, path: [], version: g.version, hologramAt: null };
440 renderGames();
441 return;
442 }
443 if (!selected || selected.game !== g.id) return;
444 const me = units.find(u => u.id === selected.unitId); if (!me) return;
445 const walkable = walkableSet(g);
446 const last = selected.path.length ? selected.path[selected.path.length - 1] : { q: me.q, r: me.r };
447 if (hexDist(last, { q, r }) === 1 && walkable.has(hexKey(q, r)))
448 {
449 selected.path = [...selected.path, { q, r }];
450 selected.hologramAt = selected.path.length - 1;
451 }
452 else
453 {
454 const found = hexPath(last, { q, r }, walkable);
455 if (!found || found.length < 2) { renderGames(); return; }
456 selected.path = selected.path.concat(found.slice(1));
457 selected.hologramAt = selected.path.length - 1;
458 }
459 renderGames();
460}
461function setFacing (g, q, r)
462{
463 if (!selected || selected.game !== g.id || !selected.path.length) return;
464 const idx = selected.hologramAt == null ? selected.path.length - 1 : selected.hologramAt;
465 const wp = selected.path[idx];
466 const dir = HEX_DIRS.findIndex(([dq, dr]) => wp.q + dq === q && wp.r + dr === r);
467 if (dir < 0)
468 {
469 let best = 0, bestD = Infinity;
470 HEX_DIRS.forEach(([dq, dr], i) =>
471 {
472 const d = hexDist({ q: wp.q + dq, r: wp.r + dr }, { q, r });
473 if (d < bestD) { bestD = d; best = i; }
474 });
475 selected.path[idx] = { ...wp, facing: best };
476 }
477 else selected.path[idx] = { ...wp, facing: dir };
478 renderGames();
479}
480function clickPathHex (g, q, r)
481{
482 if (!selected || selected.game !== g.id) return false;
483 const i = selected.path.findIndex(p => p.q === q && p.r === r);
484 if (i < 0) return false;
485 selected.hologramAt = i;
486 renderGames();
487 return true;
488}
489function matchmakingCard ()
490{
491 const searching = state.matchmaking.status === 'searching';
492 return `<article class="game-card"><div class="pending-content"><span class="big-icon">⬡</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
493}
494function renderMatchmaking ()
495{
496 const target = $('#matchmaking-actions');
497 if (!target || !state) return;
498 target.innerHTML = state.matchmaking?.status === 'searching'
499 ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
500 : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
360}
501}
361function renderFriends ()
502function renderFriends ()
362{
503{
@@ -385,50 +526,47 @@ function showRivalry (id)
385 $('#modal-content').dataset.friend = id;
526 $('#modal-content').dataset.friend = id;
386 $('#modal-content').dataset.rivalry = id;
527 $('#modal-content').dataset.rivalry = id;
387}
528}
388function refreshRivalry ()
529function refreshRivalry () { const id = $('#modal-content').dataset.rivalry; if (modal.open && id) showRivalry(id); }
389{
530function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.state?.phase === 'planning' ? 'Plan paths for your four operatives, then lock the plan. The act runs when both of you commit.' : 'Watch the same server-computed act, then plan again.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; }
390 const id = $('#modal-content').dataset.rivalry;
391 if (modal.open && id) showRivalry(id);
392}
393function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.check ? 'You are in check. Find a move that protects your king.' : 'Take your time. The board will be here.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered. Make your move to pass the offer to your opponent.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}${g.claimable ? '<button class="secondary" data-option="claim_draw">Claim draw</button>' : '<button class="secondary" data-option="claim-intended">Claim draw with intended move</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; }
394function chooseSquare (g, i)
395{
396 if (!g.yourTurn || busy || promotion) return;
397 if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
398 const p = g.state.board[i];
399 if (p !== '.' && (p === p.toUpperCase() ? 'w' : 'b') === g.color) { selected = selected?.game === g.id && selected.from === i ? null : { game: g.id, from: i, version: g.version }; }
400 else selected = null;
401 renderGames();
402}
403let claimIntended = null;
404function attemptMove (g, from, to, promote)
405{
406 const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
407 if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
408 const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
409 action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
410}
411function matchmakingCard ()
412{
413 const searching = state.matchmaking.status === 'searching';
414 return `<article class="game-card"><div class="pending-content"><span class="big-icon">♘</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
415}
416function renderMatchmaking ()
417{
418 const target = $('#matchmaking-actions');
419 if (!target || !state) return;
420 target.innerHTML = state.matchmaking?.status === 'searching'
421 ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
422 : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
423}
424async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
531async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
425if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
532if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
426if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
533if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
427if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.microchessPwa?.settings(); };
534if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.synhexPwa?.settings(); };
428if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">MICROCHESS</span><h2>Small board. Real chess.</h2><p>The usual rules of chess, on a 4 × 5 board.</p><ul class="rules-list"><li>Each side starts with a king, rook, bishop, knight and one pawn. White moves first.</li><li>Pawns move one square forward, capture diagonally and never move two squares. There is no castling or en passant.</li><li>Reach the last rank to promote to a queen, rook, bishop or knight.</li><li>Protect your king. Checkmate wins; stalemate and dead positions draw.</li><li>Claim a draw after three repetitions or 50 moves by each side without a pawn move or capture. You may also claim with an intended move, via the game menu. Five repetitions or 75 moves draw automatically.</li><li>Click a piece to see legal destinations, then click a dot. Or drag it to a destination.</li><li>The bar below your opponent’s name compares remaining material: White on the left, Black on the right. Pawn 1, knight/bishop 3, rook 5, queen 9; kings are not counted.</li><li>After your move, a blue pulse marks a clear estimated gain; red marks a likely material loss or mating threat. This quick tactical check can miss deeper ideas. Quiet or uncertain moves get no pulse.</li></ul><p class="inline-note">Pieces by Cburnett, from <a href="https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces" target="_blank" rel="noreferrer">Wikimedia Commons</a>, <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank" rel="noreferrer">CC BY-SA 3.0</a>. Unmodified SVGs.</p>`);
535if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">SYNHEX</span><h2>Plan together. Fire together.</h2><p>Simultaneous-turn hex tactics. Both players plan, then the server simulates a 3-second act.</p><ul class="rules-list"><li>The board is a 17 × 14 pointy-top hex grid (odd-r), with random walls. Each side has a VIP (pistol), two SMG soldiers and a shotgun soldier.</li><li>If your VIP dies, you lose.</li><li>Click a unit, then click hexes or drag a path. The path end is a hologram. Click a waypoint to place the hologram there; drag the facing hex in front of it to set look direction.</li><li>Re-click a unit to clear its path. Lock your plan; when both players lock, the act runs.</li><li>Press Play to watch the same server-computed result, then plan the next act.</li><li>Units walk up to 5 hexes per act. They shoot enemies in a forward 120° cone with line of sight. Hits are instant kills. Friendly fire is possible.</li><li>Accuracy starts at 15% plus bonuses for standing still, aiming dead-ahead, close range, focus fire, and more — see <code>lib/game-config.php</code>.</li><li>Enemies are visible at match start, when in your cone and LoS, or when they fire; otherwise a hologram marks their last known position.</li></ul>`);
536function playTimeline (g)
537{
538 const tl = g.state?.timeline; if (!tl) { action({ action: 'ack_playback', game: g.id, version: g.version }); return; }
539 const snaps = tl.snapshots || [];
540 if (!snaps.length || matchMedia('(prefers-reduced-motion: reduce)').matches)
541 {
542 playback.set(g.id, { units: tl.endUnits || snaps.at(-1)?.units, shots: tl.shots || [] });
543 renderGames();
544 action({ action: 'ack_playback', game: g.id, version: g.version });
545 return;
546 }
547 let i = 0;
548 const play = { timer: null };
549 const step = () =>
550 {
551 const snap = snaps[Math.min(i, snaps.length - 1)];
552 const shots = (tl.shots || []).filter(s => s.t === snap.t);
553 playback.set(g.id, { units: snap.units, shots, timer: play.timer });
554 renderGames();
555 i++;
556 if (i >= snaps.length)
557 {
558 clearInterval(play.timer);
559 playback.set(g.id, { units: tl.endUnits || snap.units, shots: [] });
560 renderGames();
561 action({ action: 'ack_playback', game: g.id, version: g.version }, () => playback.delete(g.id));
562 }
563 };
564 step();
565 play.timer = setInterval(step, Math.max(30, Math.min(120, Math.floor((tl.durationMs || 3000) / Math.max(1, snaps.length)))));
566}
429document.addEventListener('click', e =>
567document.addEventListener('click', e =>
430{
568{
431 const el = e.target.closest('button'); if (!el) return;
569 const el = e.target.closest('button, polygon, image'); if (!el) return;
432 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
570 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
433 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
571 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
434 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
572 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
@@ -436,10 +574,27 @@ document.addEventListener('click', e =>
436 if (el.id === 'avatar-button') chooseAvatar();
574 if (el.id === 'avatar-button') chooseAvatar();
437 if (el.id === 'color-pref-button') openColorPreferences();
575 if (el.id === 'color-pref-button') openColorPreferences();
438 if (el.dataset.createLink) createLink(el.dataset.createLink);
576 if (el.dataset.createLink) createLink(el.dataset.createLink);
439 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
577 if (el.dataset.hex && g)
440 if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
578 {
441 if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
579 if (suppressClick) { suppressClick = false; return; }
442 if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
580 const [q, r] = el.dataset.hex.split(',').map(Number);
581 if (el.hasAttribute('data-facing-handle')) { setFacing(g, q, r); return; }
582 if (clickPathHex(g, q, r)) return;
583 chooseHex(g, q, r);
584 }
585 if (el.dataset.unit && g)
586 {
587 const u = currentUnits(g).find(u => u.id === el.dataset.unit);
588 if (u) chooseHex(g, u.q, u.r);
589 }
590 if (el.dataset.gameAction && g)
591 {
592 if (el.dataset.gameAction === 'stop-confirm') showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
593 else if (el.dataset.gameAction === 'options') options(g);
594 else if (el.dataset.gameAction === 'commit') action({ action: 'commit_plan', game: g.id, version: g.version, plan: draftPlan(g) });
595 else if (el.dataset.gameAction === 'play') playTimeline(g);
596 else action({ action: el.dataset.gameAction, game: g.id, version: g.version });
597 }
443 if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
598 if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
444});
599});
445$('#modal-content').addEventListener('click', async e =>
600$('#modal-content').addEventListener('click', async e =>
@@ -451,8 +606,8 @@ $('#modal-content').addEventListener('click', async e =>
451 if (b.dataset.modalAction === 'close') closeModal();
606 if (b.dataset.modalAction === 'close') closeModal();
452 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
607 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
453 if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } }
608 if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } }
454 if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.microchessPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
609 if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.synhexPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
455 if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.microchessPwa?.endpoint() }, () => location.reload());
610 if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.synhexPwa?.endpoint() }, () => location.reload());
456 if (b.dataset.friendAction)
611 if (b.dataset.friendAction)
457 {
612 {
458 const id = $('#modal-content').dataset.friend;
613 const id = $('#modal-content').dataset.friend;
@@ -463,7 +618,6 @@ $('#modal-content').addEventListener('click', async e =>
463 {
618 {
464 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
619 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
465 if (b.dataset.option === 'resign-confirm') { showModal('<h2>Resign this game?</h2><p>Your opponent will win this game. You can request a rematch afterwards.</p><div class="actions"><button class="danger" data-option="resign">Resign</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); return; }
620 if (b.dataset.option === 'resign-confirm') { showModal('<h2>Resign this game?</h2><p>Your opponent will win this game. You can request a rematch afterwards.</p><div class="actions"><button class="danger" data-option="resign">Resign</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); return; }
466 if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
467 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
621 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
468 }
622 }
469});
623});
@@ -471,23 +625,43 @@ $('#modal-content').addEventListener('change', e => { if (e.target.id === 'avata
471let suppressClick = false;
625let suppressClick = false;
472document.addEventListener('pointerdown', e =>
626document.addEventListener('pointerdown', e =>
473{
627{
474 const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
628 const cell = e.target.closest('[data-hex], [data-unit]'); if (!cell || e.button !== 0 || busy) return;
475 const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
629 const g = state?.games.find(g => g.id === Number(cell.closest('[data-game]').dataset.game)); if (!g?.yourTurn || g.state?.phase !== 'planning' || g.state.committed) return;
476 const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
630 if (cell.hasAttribute('data-facing-handle'))
477 drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
631 {
632 drag = { kind: 'facing', game: g.id, id: e.pointerId };
633 return;
634 }
635 const unitId = cell.dataset.unit || currentUnits(g).find(u => hexKey(u.q, u.r) === cell.dataset.hex && u.team === g.color && u.alive && !u.hologram)?.id;
636 if (!unitId) return;
637 const unit = currentUnits(g).find(u => u.id === unitId);
638 selected = { game: g.id, unitId, path: [], version: g.version, hologramAt: null };
639 drag = { kind: 'path', game: g.id, unitId, last: { q: unit.q, r: unit.r }, id: e.pointerId, moving: false };
640 renderGames();
478});
641});
479document.addEventListener('pointermove', e =>
642document.addEventListener('pointermove', e =>
480{
643{
481 if (!drag || e.pointerId !== drag.id) return;
644 if (!drag || e.pointerId !== drag.id) return;
482 if (!drag.moving && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) > 7) { drag.moving = true; const g = state.games.find(g => g.id === drag.game); selected = { game: g.id, from: drag.from, version: g.version }; renderGames(); const img = document.createElement('img'); img.className = 'drag-ghost'; img.src = pieceUrl(drag.p, skinForPiece(state?.games?.find(x => x.id === drag.game), drag.p)); document.body.append(img); }
645 const g = state.games.find(g => g.id === drag.game); if (!g) return;
483 if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
646 const el = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-hex]');
647 if (!el) return;
648 const [q, r] = el.dataset.hex.split(',').map(Number);
649 if (drag.kind === 'facing') { setFacing(g, q, r); return; }
650 if (hexDist(drag.last, { q, r }) !== 1) return;
651 if (!walkableSet(g).has(hexKey(q, r))) return;
652 drag.moving = true;
653 selected.path = [...(selected.path || []), { q, r }];
654 selected.hologramAt = selected.path.length - 1;
655 drag.last = { q, r };
656 renderGames();
484}, { passive: false });
657}, { passive: false });
485document.addEventListener('pointerup', e =>
658document.addEventListener('pointerup', e =>
486{
659{
487 if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
660 if (!drag || e.pointerId !== drag.id) return;
488 if (d.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); const sq = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-square]'); if (sq && Number(sq.closest('[data-game]').dataset.game) === d.game) attemptMove(state.games.find(g => g.id === d.game), d.from, Number(sq.dataset.square)); }
661 if (drag.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); }
662 drag = null;
489});
663});
490document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
664document.addEventListener('pointercancel', () => { drag = null; });
491refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
665refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
492
666
493let replay = null, replayTimer = null, historyRequest = 0;
667let replay = null, replayTimer = null, historyRequest = 0;
@@ -521,7 +695,7 @@ async function openReplay (id)
521}
695}
522function showReplay (game)
696function showReplay (game)
523{
697{
524 const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Microchess ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>';
698 const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Synhex ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>';
525 if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; }
699 if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; }
526 else { showModal(content); modal.classList.add('replay-modal'); }
700 else { showModal(content); modal.classList.add('replay-modal'); }
527 replay = { ...game, index: 0 };
701 replay = { ...game, index: 0 };
@@ -532,7 +706,6 @@ async function copyReplayLink ()
532 const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken);
706 const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken);
533 try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); }
707 try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); }
534 catch {
708 catch {
535 // Keep a usable copy fallback when clipboard access is unavailable.
536 const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link');
709 const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link');
537 $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.');
710 $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.');
538 }
711 }
@@ -540,12 +713,13 @@ async function copyReplayLink ()
540function renderReplay ()
713function renderReplay ()
541{
714{
542 if (!replay || !$('#replay-card')) return;
715 if (!replay || !$('#replay-card')) return;
543 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] };
716 const frame = replay.positions[replay.index] || { units: [], walls: [], grid: { cols: 17, rows: 14 } };
717 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], state: { phase: 'replay', grid: frame.grid, walls: frame.walls, units: (frame.units || []).map(u => ({ ...u, hologram: false })), act: frame.act } };
544 const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White';
718 const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White';
545 const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black';
719 const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black';
546 $('#replay-card').innerHTML = `<article class="game-card" data-game="replay"><div class="card-header replay-players" id="modal-title"><span title="${esc(whiteTip)}"><img src="${pieceUrl('K', replay.pieceSkinWhite || 'White')}" alt="${esc(replay.pieceSkinWhite || 'White')}">${esc(replay.whiteName)}</span><span aria-hidden="true">–</span><span title="${esc(blackTip)}"><img src="${pieceUrl('k', replay.pieceSkinBlack || 'Black')}" alt="${esc(replay.pieceSkinBlack || 'Black')}">${esc(replay.blackName)}</span></div>${board(g)}</article>`;
720 $('#replay-card').innerHTML = `<article class="game-card" data-game="replay"><div class="card-header replay-players" id="modal-title"><span title="${esc(whiteTip)}"><img src="${pieceUrl('K', replay.pieceSkinWhite || 'White')}" alt="${esc(replay.pieceSkinWhite || 'White')}">${esc(replay.whiteName)}</span><span aria-hidden="true">–</span><span title="${esc(blackTip)}"><img src="${pieceUrl('k', replay.pieceSkinBlack || 'Black')}" alt="${esc(replay.pieceSkinBlack || 'Black')}">${esc(replay.blackName)}</span></div>${board(g)}</article>`;
547 $('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
721 $('#replay-progress').textContent = `${replay.index} / ${Math.max(0, replay.positions.length - 1)} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
548 const last = replay.positions.length - 1;
722 const last = Math.max(0, replay.positions.length - 1);
549 $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶';
723 $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶';
550 $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play');
724 $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play');
551 $('[data-replay-control="play"]').disabled = last < 1;
725 $('[data-replay-control="play"]').disabled = last < 1;
@@ -571,7 +745,7 @@ $('#modal-content').addEventListener('click', e => {
571 }
745 }
572 } else {
746 } else {
573 stopReplay();
747 stopReplay();
574 const last = replay.positions.length - 1;
748 const last = Math.max(0, replay.positions.length - 1);
575 replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1)));
749 replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1)));
576 }
750 }
577 renderReplay();
751 renderReplay();
@@ -579,9 +753,10 @@ $('#modal-content').addEventListener('click', e => {
579const savedAnimations = new Set();
753const savedAnimations = new Set();
580function animateSavedGames ()
754function animateSavedGames ()
581{
755{
756 if (!state?.games) return;
582 for (const g of state.games) {
757 for (const g of state.games) {
583 if (!g.replayId) continue;
758 if (!g.replayId) continue;
584 const key = `microchess-saved:${state.user.id}:${g.replayId}`;
759 const key = `synhex-saved:${state.user.id}:${g.replayId}`;
585 let seen = savedAnimations.has(key);
760 let seen = savedAnimations.has(key);
586 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
761 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
587 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
762 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
web/assets/pwa.js +7 −7
@@ -29,9 +29,9 @@
29 29 function settings ()
30 30 {
31 31 const el = document.querySelector('#notification-settings'); if (!el) return;
32 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Microchess to your home screen, open it there, and enable notifications.</p>'; return; }
32 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Synhex to your home screen, open it there, and enable notifications.</p>'; return; }
33 33 if (!supported) { el.innerHTML = '<p>This browser does not support turn notifications.</p>'; return; }
34 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }
34 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Synhex.</p>'; return; }
35 35 el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;
36 36 }
37 37 function showNotice (title, content, kind)
@@ -68,13 +68,13 @@
68 68 if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {
69 69 let brave = false;
70 70 try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}
71 advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Microchess alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
71 advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Synhex alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
72 72 } else if (phase === 'permission' || error.name === 'NotAllowedError') {
73 73 advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';
74 74 } else if (phase === 'subscribe') {
75 advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Microchess from its home-screen icon.</p>';
75 advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Synhex from its home-screen icon.</p>';
76 76 } else {
77 advice = '<p>Microchess could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
77 advice = '<p>Synhex could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
78 78 }
79 79 const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';
80 80 showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');
@@ -159,8 +159,8 @@
159 159 if (!event.target.closest('[data-install-app]')) return;
160 160 if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
161 161 const help = document.querySelector('#install-help');
162 if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; }
162 if (help) { help.hidden = false; help.textContent = standalone() ? 'Synhex is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Synhex using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Synhex in Chrome or Safari.'; }
163 163 });
164 window.microchessPwa = { sync, settings, highlight, endpoint, intro };
164 window.synhexPwa = { sync, settings, highlight, endpoint, intro };
165 165 if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }
166 166 })();
@@ -29,9 +29,9 @@
29 function settings ()
29 function settings ()
30 {
30 {
31 const el = document.querySelector('#notification-settings'); if (!el) return;
31 const el = document.querySelector('#notification-settings'); if (!el) return;
32 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Microchess to your home screen, open it there, and enable notifications.</p>'; return; }
32 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Synhex to your home screen, open it there, and enable notifications.</p>'; return; }
33 if (!supported) { el.innerHTML = '<p>This browser does not support turn notifications.</p>'; return; }
33 if (!supported) { el.innerHTML = '<p>This browser does not support turn notifications.</p>'; return; }
34 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }
34 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Synhex.</p>'; return; }
35 el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;
35 el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;
36 }
36 }
37 function showNotice (title, content, kind)
37 function showNotice (title, content, kind)
@@ -68,13 +68,13 @@
68 if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {
68 if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {
69 let brave = false;
69 let brave = false;
70 try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}
70 try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}
71 advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Microchess alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
71 advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Synhex alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
72 } else if (phase === 'permission' || error.name === 'NotAllowedError') {
72 } else if (phase === 'permission' || error.name === 'NotAllowedError') {
73 advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';
73 advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';
74 } else if (phase === 'subscribe') {
74 } else if (phase === 'subscribe') {
75 advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Microchess from its home-screen icon.</p>';
75 advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Synhex from its home-screen icon.</p>';
76 } else {
76 } else {
77 advice = '<p>Microchess could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
77 advice = '<p>Synhex could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
78 }
78 }
79 const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';
79 const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';
80 showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');
80 showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');
@@ -159,8 +159,8 @@
159 if (!event.target.closest('[data-install-app]')) return;
159 if (!event.target.closest('[data-install-app]')) return;
160 if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
160 if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
161 const help = document.querySelector('#install-help');
161 const help = document.querySelector('#install-help');
162 if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; }
162 if (help) { help.hidden = false; help.textContent = standalone() ? 'Synhex is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Synhex using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Synhex in Chrome or Safari.'; }
163 });
163 });
164 window.microchessPwa = { sync, settings, highlight, endpoint, intro };
164 window.synhexPwa = { sync, settings, highlight, endpoint, intro };
165 if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }
165 if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }
166})();
166})();
web/index.php +5 −5
@@ -10,29 +10,29 @@ $loginQuery=http_build_query(array_filter(['invite'=>$invite,'game'=>$game]));
10 10 <html lang="en">
11 11 <head>
12 12 <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
13 <meta name="theme-color" content="#f5f3ed"><title>Microchess — Small board. Big game.</title>
13 <meta name="theme-color" content="#f5f3ed"><title>Synhex — Plan together. Fire together.</title>
14 14 <link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/pieces/nlt.svg')) ?>" type="image/svg+xml">
15 15 <link rel="manifest" href="manifest.webmanifest">
16 16 <link rel="apple-touch-icon" href="<?= htmlspecialchars(assetUrl('assets/app-icon-180.png')) ?>">
17 <meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="Microchess">
17 <meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="Synhex">
18 18 <meta name="asset-version" content="<?= htmlspecialchars(assetVersion()) ?>">
19 19 <link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css')) ?>"><script src="<?= htmlspecialchars(assetUrl('assets/app.js')) ?>" defer></script><script src="<?= htmlspecialchars(assetUrl('assets/pwa.js')) ?>" defer></script>
20 20 </head>
21 21 <body<?= $sharedReplay?' class="replay-page"':'' ?>>
22 22 <?php if (!$sharedReplay): ?>
23 <header class="topbar"><a class="brand" href="./"><span class="brandmark">m<span>↗</span></span>microchess<span class="brand-dot">.</span></a><span class="tagline">Small board. Big game.</span><div class="account-nav"><button id="settings-button" class="quiet" aria-label="Open account settings">Account</button><button id="friends-toggle" class="mobile-friends" aria-controls="sidebar" aria-expanded="false">Friends <span id="friend-count">0</span></button></div></header>
23 <header class="topbar"><a class="brand" href="./"><span class="brandmark">s<span>↗</span></span>synhex<span class="brand-dot">.</span></a><span class="tagline">Plan together. Fire together.</span><div class="account-nav"><button id="settings-button" class="quiet" aria-label="Open account settings">Account</button><button id="friends-toggle" class="mobile-friends" aria-controls="sidebar" aria-expanded="false">Friends <span id="friend-count">0</span></button></div></header>
24 24 <?php endif ?>
25 25 <?php if ($sharedReplay): ?>
26 26 <main id="replay-page" aria-label="Game replay"><div id="modal-content"><p role="status">Loading saved game…</p></div></main>
27 27 <?php elseif (!$logged): ?>
28 <main class="login"><span class="eyebrow">A LITTLE CHESS. A LOT OF POSSIBILITIES.</span><h1>Your next move<br>starts here.</h1><p>Five pieces. Twenty squares. Challenge your friends to a game of Microchess, one move at a time.</p><a class="button primary" href="auth.php<?= $loginQuery?'?'.htmlspecialchars($loginQuery):'' ?>">Sign in with Tim Falken <span>↗</span></a><small>Sign in to play and accept invitations.</small><button class="text-button" data-install-app>Add to home screen</button><p id="install-help" hidden></p></main>
28 <main class="login"><span class="eyebrow">SIMULTANEOUS TACTICS. HEX BY HEX.</span><h1>Lock your plan.<br>Watch it fire.</h1><p>Four operatives on a hex grid. You and your opponent plan at the same time, then play back the act together.</p><a class="button primary" href="auth.php<?= $loginQuery?'?'.htmlspecialchars($loginQuery):'' ?>">Sign in with Tim Falken <span>↗</span></a><small>Sign in to play and accept invitations.</small><button class="text-button" data-install-app>Add to home screen</button><p id="install-help" hidden></p></main>
29 29 <?php else: ?>
30 30 <div class="layout"><main id="main"><div class="page-heading"><div><h1>Your games<span class="brand-dot">.</span></h1></div><button id="match-link" class="primary">+ New game</button></div>
31 31 <div class="section-heading"><h2><span class="status-dot"></span>Your Turn <span id="your-count" class="count">0</span></h2></div>
32 32 <div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>
33 33 <div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>
34 34 <footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>
35 <div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
35 <div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>⬡</span><h3>Better with a rival.</h3><p>Invite a friend, lock your plan.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
36 36 <?php endif ?>
37 37 <?php if (!$sharedReplay): ?>
38 38 <dialog id="notification-dialog" aria-labelledby="notification-dialog-title"><button class="modal-close quiet" data-close-notification-dialog aria-label="Close dialog">✕</button><div id="notification-dialog-content"></div></dialog>
@@ -10,29 +10,29 @@ $loginQuery=http_build_query(array_filter(['invite'=>$invite,'game'=>$game]));
10<html lang="en">
10<html lang="en">
11<head>
11<head>
12<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
12<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
13<meta name="theme-color" content="#f5f3ed"><title>Microchess — Small board. Big game.</title>
13<meta name="theme-color" content="#f5f3ed"><title>Synhex — Plan together. Fire together.</title>
14<link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/pieces/nlt.svg')) ?>" type="image/svg+xml">
14<link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/pieces/nlt.svg')) ?>" type="image/svg+xml">
15<link rel="manifest" href="manifest.webmanifest">
15<link rel="manifest" href="manifest.webmanifest">
16<link rel="apple-touch-icon" href="<?= htmlspecialchars(assetUrl('assets/app-icon-180.png')) ?>">
16<link rel="apple-touch-icon" href="<?= htmlspecialchars(assetUrl('assets/app-icon-180.png')) ?>">
17<meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="Microchess">
17<meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="Synhex">
18<meta name="asset-version" content="<?= htmlspecialchars(assetVersion()) ?>">
18<meta name="asset-version" content="<?= htmlspecialchars(assetVersion()) ?>">
19<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css')) ?>"><script src="<?= htmlspecialchars(assetUrl('assets/app.js')) ?>" defer></script><script src="<?= htmlspecialchars(assetUrl('assets/pwa.js')) ?>" defer></script>
19<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css')) ?>"><script src="<?= htmlspecialchars(assetUrl('assets/app.js')) ?>" defer></script><script src="<?= htmlspecialchars(assetUrl('assets/pwa.js')) ?>" defer></script>
20</head>
20</head>
21<body<?= $sharedReplay?' class="replay-page"':'' ?>>
21<body<?= $sharedReplay?' class="replay-page"':'' ?>>
22<?php if (!$sharedReplay): ?>
22<?php if (!$sharedReplay): ?>
23<header class="topbar"><a class="brand" href="./"><span class="brandmark">m<span>↗</span></span>microchess<span class="brand-dot">.</span></a><span class="tagline">Small board. Big game.</span><div class="account-nav"><button id="settings-button" class="quiet" aria-label="Open account settings">Account</button><button id="friends-toggle" class="mobile-friends" aria-controls="sidebar" aria-expanded="false">Friends <span id="friend-count">0</span></button></div></header>
23<header class="topbar"><a class="brand" href="./"><span class="brandmark">s<span>↗</span></span>synhex<span class="brand-dot">.</span></a><span class="tagline">Plan together. Fire together.</span><div class="account-nav"><button id="settings-button" class="quiet" aria-label="Open account settings">Account</button><button id="friends-toggle" class="mobile-friends" aria-controls="sidebar" aria-expanded="false">Friends <span id="friend-count">0</span></button></div></header>
24<?php endif ?>
24<?php endif ?>
25<?php if ($sharedReplay): ?>
25<?php if ($sharedReplay): ?>
26<main id="replay-page" aria-label="Game replay"><div id="modal-content"><p role="status">Loading saved game…</p></div></main>
26<main id="replay-page" aria-label="Game replay"><div id="modal-content"><p role="status">Loading saved game…</p></div></main>
27<?php elseif (!$logged): ?>
27<?php elseif (!$logged): ?>
28<main class="login"><span class="eyebrow">A LITTLE CHESS. A LOT OF POSSIBILITIES.</span><h1>Your next move<br>starts here.</h1><p>Five pieces. Twenty squares. Challenge your friends to a game of Microchess, one move at a time.</p><a class="button primary" href="auth.php<?= $loginQuery?'?'.htmlspecialchars($loginQuery):'' ?>">Sign in with Tim Falken <span>↗</span></a><small>Sign in to play and accept invitations.</small><button class="text-button" data-install-app>Add to home screen</button><p id="install-help" hidden></p></main>
28<main class="login"><span class="eyebrow">SIMULTANEOUS TACTICS. HEX BY HEX.</span><h1>Lock your plan.<br>Watch it fire.</h1><p>Four operatives on a hex grid. You and your opponent plan at the same time, then play back the act together.</p><a class="button primary" href="auth.php<?= $loginQuery?'?'.htmlspecialchars($loginQuery):'' ?>">Sign in with Tim Falken <span>↗</span></a><small>Sign in to play and accept invitations.</small><button class="text-button" data-install-app>Add to home screen</button><p id="install-help" hidden></p></main>
29<?php else: ?>
29<?php else: ?>
30<div class="layout"><main id="main"><div class="page-heading"><div><h1>Your games<span class="brand-dot">.</span></h1></div><button id="match-link" class="primary">+ New game</button></div>
30<div class="layout"><main id="main"><div class="page-heading"><div><h1>Your games<span class="brand-dot">.</span></h1></div><button id="match-link" class="primary">+ New game</button></div>
31<div class="section-heading"><h2><span class="status-dot"></span>Your Turn <span id="your-count" class="count">0</span></h2></div>
31<div class="section-heading"><h2><span class="status-dot"></span>Your Turn <span id="your-count" class="count">0</span></h2></div>
32<div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>
32<div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>
33<div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>
33<div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>
34<footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>
34<footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>
35<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
35<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>⬡</span><h3>Better with a rival.</h3><p>Invite a friend, lock your plan.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
36<?php endif ?>
36<?php endif ?>
37<?php if (!$sharedReplay): ?>
37<?php if (!$sharedReplay): ?>
38<dialog id="notification-dialog" aria-labelledby="notification-dialog-title"><button class="modal-close quiet" data-close-notification-dialog aria-label="Close dialog">✕</button><div id="notification-dialog-content"></div></dialog>
38<dialog id="notification-dialog" aria-labelledby="notification-dialog-title"><button class="modal-close quiet" data-close-notification-dialog aria-label="Close dialog">✕</button><div id="notification-dialog-content"></div></dialog>
web/lib/Chess.php deleted +0 −114
@@ -1,114 +0,0 @@
1 <?php
2 declare(strict_types=1);
3
4 /** Board indices: a5=0, d5=3, a1=16, d1=19. Uppercase is white. */
5 final class Chess
6 {
7 public static function initial(): array
8 {
9 $s = ['board'=>[], 'turn'=>'w', 'halfmove'=>0, 'ply'=>0, 'history'=>[], 'last'=>null];
10 // Keep empty squares explicit; the position contains exactly twenty squares.
11 $s['board'] = ['k','n','b','r','p','.','.','.','.','.','.','.','.','.','.','P','R','B','N','K'];
12 $s['history'][] = self::key($s);
13 return $s;
14 }
15 public static function color(string $p): ?string { return $p==='.' ? null : (ctype_upper($p)?'w':'b'); }
16 public static function opposite(string $c): string { return $c==='w'?'b':'w'; }
17 public static function key(array $s): string { return implode('', $s['board']).$s['turn']; }
18 public static function attacked(array $b, int $target, string $by): bool
19 {
20 foreach ($b as $i=>$p) {
21 if (self::color($p)!==$by) continue;
22 $dx=$target%4-$i%4; $dy=intdiv($target,4)-intdiv($i,4); $t=strtolower($p);
23 if ($t==='p' && abs($dx)===1 && $dy===($by==='w'?-1:1)) return true;
24 if ($t==='n' && abs($dx)*abs($dy)===2) return true;
25 if ($t==='k' && max(abs($dx),abs($dy))===1) return true;
26 $diagonal=abs($dx)===abs($dy) && $dx!==0;
27 $straight=($dx===0 xor $dy===0);
28 if (!(($t==='b' && $diagonal)||($t==='r' && $straight)||($t==='q' && ($diagonal||$straight)))) continue;
29 $sx=$dx<=>0; $sy=$dy<=>0; $x=$i%4+$sx; $y=intdiv($i,4)+$sy;
30 while ($y*4+$x!==$target) { if ($b[$y*4+$x]!=='.') continue 2; $x+=$sx; $y+=$sy; }
31 return true;
32 }
33 return false;
34 }
35 public static function check(array $s, ?string $color=null): bool
36 {
37 $color ??= $s['turn'];
38 $king=array_search($color==='w'?'K':'k',$s['board'],true);
39 return $king===false || self::attacked($s['board'],$king,self::opposite($color));
40 }
41 public static function legal(array $s): array
42 {
43 $out=[]; $b=$s['board']; $c=$s['turn'];
44 foreach ($b as $from=>$p) {
45 if (self::color($p)!==$c) continue;
46 for ($to=0;$to<20;$to++) {
47 if ($to===$from || self::color($b[$to])===$c || strtolower($b[$to])==='k') continue;
48 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4);
49 if (strtolower($p)==='p') {
50 $ok=$dy===($c==='w'?-1:1) && (($dx===0 && $b[$to]==='.')||(abs($dx)===1 && $b[$to]!=='.'));
51 } else {
52 $ok=self::pieceReaches($b,$from,$to);
53 }
54 if (!$ok) continue;
55 $next=$s; $next['board'][$to]=$p; $next['board'][$from]='.';
56 if (self::check($next,$c)) continue;
57 if (strtolower($p)==='p' && (intdiv($to,4)===0||intdiv($to,4)===4)) {
58 foreach (['q','r','b','n'] as $promotion) $out[]=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
59 } else $out[]=['from'=>$from,'to'=>$to,'promotion'=>null];
60 }
61 }
62 return $out;
63 }
64 private static function pieceReaches(array $b,int $from,int $to): bool
65 {
66 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4); $t=strtolower($b[$from]);
67 if ($t==='n') return abs($dx)*abs($dy)===2;
68 if ($t==='k') return max(abs($dx),abs($dy))===1;
69 $d=abs($dx)===abs($dy) && $dx!==0; $r=($dx===0 xor $dy===0);
70 if (!(($t==='b'&&$d)||($t==='r'&&$r)||($t==='q'&&($d||$r)))) return false;
71 $sx=$dx<=>0; $sy=$dy<=>0; $x=$from%4+$sx; $y=intdiv($from,4)+$sy;
72 while ($y*4+$x!==$to) { if ($b[$y*4+$x]!=='.') return false; $x+=$sx; $y+=$sy; }
73 return true;
74 }
75 public static function move(array $s,int $from,int $to,?string $promotion=null): array
76 {
77 $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
78 if (!in_array($move,self::legal($s),true)) throw new DomainException('That move is not legal.');
79 return self::afterLegal($s,$move);
80 }
81 /** Apply a move already generated by legal(); external input must go through move(). */
82 public static function afterLegal(array $s,array $move): array
83 {
84 ['from'=>$from,'to'=>$to,'promotion'=>$promotion]=$move;
85 $p=$s['board'][$from];
86 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
87 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
88 $s['board'][$from]='.'; $s['turn']=self::opposite($s['turn']); $s['ply']++; $s['last']=$move;
89 $s['history'][]=self::key($s); return $s;
90 }
91 public static function dead(array $s): bool
92 {
93 $minors=[];
94 foreach ($s['board'] as $i=>$p) {
95 if (in_array(strtolower($p),['.','k'],true)) continue;
96 if (!in_array(strtolower($p),['b','n'],true)) return false;
97 $minors[$i]=$p;
98 }
99 if (count($minors)<=1) return true;
100 $squares=[];
101 foreach ($minors as $i=>$p) { if (strtolower($p)!=='b') return false; $squares[]=($i%4+intdiv($i,4))%2; }
102 return count(array_unique($squares))===1;
103 }
104 public static function repetitions(array $s): int { return count(array_filter($s['history'],fn($k)=>$k===self::key($s))); }
105 public static function claimable(array $s): bool { return $s['halfmove']>=100 || self::repetitions($s)>=3; }
106 public static function result(array $s): ?array
107 {
108 if (!self::legal($s)) return self::check($s)?['winner'=>self::opposite($s['turn']),'reason'=>'Checkmate']:['winner'=>null,'reason'=>'Stalemate'];
109 if (self::dead($s)) return ['winner'=>null,'reason'=>'Dead position'];
110 if ($s['halfmove']>=150) return ['winner'=>null,'reason'=>'75-move rule'];
111 if (self::repetitions($s)>=5) return ['winner'=>null,'reason'=>'Fivefold repetition'];
112 return null;
113 }
114 }
@@ -1,114 +0,0 @@
1<?php
2declare(strict_types=1);
3
4/** Board indices: a5=0, d5=3, a1=16, d1=19. Uppercase is white. */
5final class Chess
6{
7 public static function initial(): array
8 {
9 $s = ['board'=>[], 'turn'=>'w', 'halfmove'=>0, 'ply'=>0, 'history'=>[], 'last'=>null];
10 // Keep empty squares explicit; the position contains exactly twenty squares.
11 $s['board'] = ['k','n','b','r','p','.','.','.','.','.','.','.','.','.','.','P','R','B','N','K'];
12 $s['history'][] = self::key($s);
13 return $s;
14 }
15 public static function color(string $p): ?string { return $p==='.' ? null : (ctype_upper($p)?'w':'b'); }
16 public static function opposite(string $c): string { return $c==='w'?'b':'w'; }
17 public static function key(array $s): string { return implode('', $s['board']).$s['turn']; }
18 public static function attacked(array $b, int $target, string $by): bool
19 {
20 foreach ($b as $i=>$p) {
21 if (self::color($p)!==$by) continue;
22 $dx=$target%4-$i%4; $dy=intdiv($target,4)-intdiv($i,4); $t=strtolower($p);
23 if ($t==='p' && abs($dx)===1 && $dy===($by==='w'?-1:1)) return true;
24 if ($t==='n' && abs($dx)*abs($dy)===2) return true;
25 if ($t==='k' && max(abs($dx),abs($dy))===1) return true;
26 $diagonal=abs($dx)===abs($dy) && $dx!==0;
27 $straight=($dx===0 xor $dy===0);
28 if (!(($t==='b' && $diagonal)||($t==='r' && $straight)||($t==='q' && ($diagonal||$straight)))) continue;
29 $sx=$dx<=>0; $sy=$dy<=>0; $x=$i%4+$sx; $y=intdiv($i,4)+$sy;
30 while ($y*4+$x!==$target) { if ($b[$y*4+$x]!=='.') continue 2; $x+=$sx; $y+=$sy; }
31 return true;
32 }
33 return false;
34 }
35 public static function check(array $s, ?string $color=null): bool
36 {
37 $color ??= $s['turn'];
38 $king=array_search($color==='w'?'K':'k',$s['board'],true);
39 return $king===false || self::attacked($s['board'],$king,self::opposite($color));
40 }
41 public static function legal(array $s): array
42 {
43 $out=[]; $b=$s['board']; $c=$s['turn'];
44 foreach ($b as $from=>$p) {
45 if (self::color($p)!==$c) continue;
46 for ($to=0;$to<20;$to++) {
47 if ($to===$from || self::color($b[$to])===$c || strtolower($b[$to])==='k') continue;
48 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4);
49 if (strtolower($p)==='p') {
50 $ok=$dy===($c==='w'?-1:1) && (($dx===0 && $b[$to]==='.')||(abs($dx)===1 && $b[$to]!=='.'));
51 } else {
52 $ok=self::pieceReaches($b,$from,$to);
53 }
54 if (!$ok) continue;
55 $next=$s; $next['board'][$to]=$p; $next['board'][$from]='.';
56 if (self::check($next,$c)) continue;
57 if (strtolower($p)==='p' && (intdiv($to,4)===0||intdiv($to,4)===4)) {
58 foreach (['q','r','b','n'] as $promotion) $out[]=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
59 } else $out[]=['from'=>$from,'to'=>$to,'promotion'=>null];
60 }
61 }
62 return $out;
63 }
64 private static function pieceReaches(array $b,int $from,int $to): bool
65 {
66 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4); $t=strtolower($b[$from]);
67 if ($t==='n') return abs($dx)*abs($dy)===2;
68 if ($t==='k') return max(abs($dx),abs($dy))===1;
69 $d=abs($dx)===abs($dy) && $dx!==0; $r=($dx===0 xor $dy===0);
70 if (!(($t==='b'&&$d)||($t==='r'&&$r)||($t==='q'&&($d||$r)))) return false;
71 $sx=$dx<=>0; $sy=$dy<=>0; $x=$from%4+$sx; $y=intdiv($from,4)+$sy;
72 while ($y*4+$x!==$to) { if ($b[$y*4+$x]!=='.') return false; $x+=$sx; $y+=$sy; }
73 return true;
74 }
75 public static function move(array $s,int $from,int $to,?string $promotion=null): array
76 {
77 $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
78 if (!in_array($move,self::legal($s),true)) throw new DomainException('That move is not legal.');
79 return self::afterLegal($s,$move);
80 }
81 /** Apply a move already generated by legal(); external input must go through move(). */
82 public static function afterLegal(array $s,array $move): array
83 {
84 ['from'=>$from,'to'=>$to,'promotion'=>$promotion]=$move;
85 $p=$s['board'][$from];
86 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
87 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
88 $s['board'][$from]='.'; $s['turn']=self::opposite($s['turn']); $s['ply']++; $s['last']=$move;
89 $s['history'][]=self::key($s); return $s;
90 }
91 public static function dead(array $s): bool
92 {
93 $minors=[];
94 foreach ($s['board'] as $i=>$p) {
95 if (in_array(strtolower($p),['.','k'],true)) continue;
96 if (!in_array(strtolower($p),['b','n'],true)) return false;
97 $minors[$i]=$p;
98 }
99 if (count($minors)<=1) return true;
100 $squares=[];
101 foreach ($minors as $i=>$p) { if (strtolower($p)!=='b') return false; $squares[]=($i%4+intdiv($i,4))%2; }
102 return count(array_unique($squares))===1;
103 }
104 public static function repetitions(array $s): int { return count(array_filter($s['history'],fn($k)=>$k===self::key($s))); }
105 public static function claimable(array $s): bool { return $s['halfmove']>=100 || self::repetitions($s)>=3; }
106 public static function result(array $s): ?array
107 {
108 if (!self::legal($s)) return self::check($s)?['winner'=>self::opposite($s['turn']),'reason'=>'Checkmate']:['winner'=>null,'reason'=>'Stalemate'];
109 if (self::dead($s)) return ['winner'=>null,'reason'=>'Dead position'];
110 if ($s['halfmove']>=150) return ['winner'=>null,'reason'=>'75-move rule'];
111 if (self::repetitions($s)>=5) return ['winner'=>null,'reason'=>'Fivefold repetition'];
112 return null;
113 }
114}
web/lib/HexGrid.php added +292 −0
@@ -0,0 +1,292 @@
1 <?php
2 declare(strict_types=1);
3
4 /**
5 * Pointy-top hex math using axial (q, r) and odd-r offset (col, row).
6 * Direction indices: 0 E, 1 NE, 2 NW, 3 W, 4 SW, 5 SE.
7 */
8 final class HexGrid
9 {
10 public const DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
11
12 public static function axial(int $col, int $row): array
13 {
14 return [$col - intdiv($row, 2), $row];
15 }
16
17 public static function offset(int $q, int $r): array
18 {
19 return [$q + intdiv($r, 2), $r];
20 }
21
22 public static function key(int $q, int $r): string
23 {
24 return $q.','.$r;
25 }
26
27 public static function parse(string $key): array
28 {
29 $p = explode(',', $key, 2);
30 return [(int)$p[0], (int)$p[1]];
31 }
32
33 public static function inBounds(int $q, int $r, int $cols, int $rows): bool
34 {
35 [$col, $row] = self::offset($q, $r);
36 return $col >= 0 && $col < $cols && $row >= 0 && $row < $rows;
37 }
38
39 public static function neighbors(int $q, int $r): array
40 {
41 $out = [];
42 foreach (self::DIRS as [$dq, $dr]) {
43 $out[] = [$q + $dq, $r + $dr];
44 }
45 return $out;
46 }
47
48 public static function neighbor(int $q, int $r, int $dir): array
49 {
50 $d = self::DIRS[($dir % 6 + 6) % 6];
51 return [$q + $d[0], $r + $d[1]];
52 }
53
54 public static function distance(int $q1, int $r1, int $q2, int $r2): int
55 {
56 return intdiv(abs($q1 - $q2) + abs($q1 + $r1 - $q2 - $r2) + abs($r1 - $r2), 2);
57 }
58
59 public static function cubeRound(float $x, float $z, float $y): array
60 {
61 $rx = (int)round($x);
62 $rz = (int)round($z);
63 $ry = (int)round($y);
64 $dx = abs($rx - $x);
65 $dz = abs($rz - $z);
66 $dy = abs($ry - $y);
67 if ($dx > $dz && $dx > $dy) {
68 $rx = -$rz - $ry;
69 } elseif ($dz > $dy) {
70 $rz = -$rx - $ry;
71 }
72 return [$rx, $rz];
73 }
74
75 /** Inclusive hex line from A to B. */
76 public static function line(int $q1, int $r1, int $q2, int $r2): array
77 {
78 $n = self::distance($q1, $r1, $q2, $r2);
79 if ($n === 0) {
80 return [[$q1, $r1]];
81 }
82 $out = [];
83 $y1 = -$q1 - $r1;
84 $y2 = -$q2 - $r2;
85 for ($i = 0; $i <= $n; $i++) {
86 $t = $i / $n;
87 $out[] = self::cubeRound(
88 $q1 + ($q2 - $q1) * $t,
89 $r1 + ($r2 - $r1) * $t,
90 $y1 + ($y2 - $y1) * $t
91 );
92 }
93 return $out;
94 }
95
96 /** Hexes from origin stepping in a facing, excluding origin. */
97 public static function ray(int $q, int $r, int $dir, int $length): array
98 {
99 $out = [];
100 for ($i = 0; $i < $length; $i++) {
101 [$q, $r] = self::neighbor($q, $r, $dir);
102 $out[] = [$q, $r];
103 }
104 return $out;
105 }
106
107 /**
108 * LoS is blocked by walls on intermediate hexes. Endpoints may be occupied.
109 * @param array<string,true> $walls
110 */
111 public static function los(int $q1, int $r1, int $q2, int $r2, array $walls): bool
112 {
113 $line = self::line($q1, $r1, $q2, $r2);
114 $last = count($line) - 1;
115 for ($i = 1; $i < $last; $i++) {
116 if (isset($walls[self::key($line[$i][0], $line[$i][1])])) {
117 return false;
118 }
119 }
120 return true;
121 }
122
123 public static function pixel(int $q, int $r): array
124 {
125 return [sqrt(3) * ($q + $r / 2), 1.5 * $r];
126 }
127
128 public static function facingAngle(int $dir): float
129 {
130 $d = self::DIRS[($dir % 6 + 6) % 6];
131 [$x, $y] = self::pixel($d[0], $d[1]);
132 return atan2($y, $x);
133 }
134
135 public static function bearing(int $q1, int $r1, int $q2, int $r2): float
136 {
137 [$x1, $y1] = self::pixel($q1, $r1);
138 [$x2, $y2] = self::pixel($q2, $r2);
139 return atan2($y2 - $y1, $x2 - $x1);
140 }
141
142 public static function angleDiff(float $a, float $b): float
143 {
144 $d = fmod($a - $b + M_PI, 2 * M_PI);
145 if ($d < 0) {
146 $d += 2 * M_PI;
147 }
148 return $d - M_PI;
149 }
150
151 public static function inCone(int $uq, int $ur, int $facing, int $tq, int $tr, float $halfDeg): bool
152 {
153 if ($uq === $tq && $ur === $tr) {
154 return false;
155 }
156 return abs(self::angleDiff(self::bearing($uq, $ur, $tq, $tr), self::facingAngle($facing))) <= deg2rad($halfDeg) + 1e-9;
157 }
158
159 public static function dirToward(int $q1, int $r1, int $q2, int $r2): int
160 {
161 $best = 0;
162 $bestAbs = INF;
163 $bearing = self::bearing($q1, $r1, $q2, $r2);
164 for ($d = 0; $d < 6; $d++) {
165 $abs = abs(self::angleDiff($bearing, self::facingAngle($d)));
166 if ($abs < $bestAbs) {
167 $bestAbs = $abs;
168 $best = $d;
169 }
170 }
171 return $best;
172 }
173
174 public static function onFacingLine(int $q, int $r, int $facing, int $tq, int $tr, int $length): bool
175 {
176 foreach (self::ray($q, $r, $facing, $length) as [$qq, $rr]) {
177 if ($qq === $tq && $rr === $tr) {
178 return true;
179 }
180 }
181 return false;
182 }
183
184 /**
185 * A* path across walkable hexes. Returns inclusive hex list or null.
186 * @param array<string,true> $walkable
187 */
188 public static function path(int $q1, int $r1, int $q2, int $r2, array $walkable): ?array
189 {
190 $start = self::key($q1, $r1);
191 $goal = self::key($q2, $r2);
192 if (!isset($walkable[$start]) || !isset($walkable[$goal])) {
193 return null;
194 }
195 if ($start === $goal) {
196 return [[$q1, $r1]];
197 }
198 $open = [$start => 0];
199 $came = [];
200 $g = [$start => 0];
201 while ($open) {
202 $current = array_key_first($open);
203 $best = $open[$current];
204 foreach ($open as $k => $f) {
205 if ($f < $best) {
206 $current = $k;
207 $best = $f;
208 }
209 }
210 unset($open[$current]);
211 if ($current === $goal) {
212 $path = [];
213 while ($current !== $start) {
214 $path[] = self::parse($current);
215 $current = $came[$current];
216 }
217 $path[] = [$q1, $r1];
218 return array_reverse($path);
219 }
220 [$cq, $cr] = self::parse($current);
221 foreach (self::neighbors($cq, $cr) as [$nq, $nr]) {
222 $nk = self::key($nq, $nr);
223 if (!isset($walkable[$nk])) {
224 continue;
225 }
226 $tg = $g[$current] + 1;
227 if (!isset($g[$nk]) || $tg < $g[$nk]) {
228 $came[$nk] = $current;
229 $g[$nk] = $tg;
230 $open[$nk] = $tg + self::distance($nq, $nr, $q2, $r2);
231 }
232 }
233 }
234 return null;
235 }
236
237 /**
238 * @return array<string,true>
239 */
240 public static function allHexes(int $cols, int $rows): array
241 {
242 $out = [];
243 for ($row = 0; $row < $rows; $row++) {
244 for ($col = 0; $col < $cols; $col++) {
245 [$q, $r] = self::axial($col, $row);
246 $out[self::key($q, $r)] = true;
247 }
248 }
249 return $out;
250 }
251 }
252
253 /** Deterministic 32-bit RNG used by wall generation and combat. */
254 final class SynhexRng
255 {
256 private int $state;
257
258 public function __construct(int $seed)
259 {
260 $this->state = $seed | 1;
261 }
262
263 public function next(): int
264 {
265 $x = $this->state;
266 $x = ($x ^ ($x << 13)) & 0x7fffffff;
267 $x = ($x ^ ($x >> 17)) & 0x7fffffff;
268 $x = ($x ^ ($x << 5)) & 0x7fffffff;
269 return $this->state = $x;
270 }
271
272 public function below(int $n): int
273 {
274 return $n <= 0 ? 0 : $this->next() % $n;
275 }
276
277 public function chance(int $percent): bool
278 {
279 if ($percent <= 0) {
280 return false;
281 }
282 if ($percent >= 100) {
283 return true;
284 }
285 return $this->below(100) < $percent;
286 }
287
288 public function unit(): float
289 {
290 return $this->next() / 0x7fffffff;
291 }
292 }
@@ -0,0 +1,292 @@
1<?php
2declare(strict_types=1);
3
4/**
5 * Pointy-top hex math using axial (q, r) and odd-r offset (col, row).
6 * Direction indices: 0 E, 1 NE, 2 NW, 3 W, 4 SW, 5 SE.
7 */
8final class HexGrid
9{
10 public const DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
11
12 public static function axial(int $col, int $row): array
13 {
14 return [$col - intdiv($row, 2), $row];
15 }
16
17 public static function offset(int $q, int $r): array
18 {
19 return [$q + intdiv($r, 2), $r];
20 }
21
22 public static function key(int $q, int $r): string
23 {
24 return $q.','.$r;
25 }
26
27 public static function parse(string $key): array
28 {
29 $p = explode(',', $key, 2);
30 return [(int)$p[0], (int)$p[1]];
31 }
32
33 public static function inBounds(int $q, int $r, int $cols, int $rows): bool
34 {
35 [$col, $row] = self::offset($q, $r);
36 return $col >= 0 && $col < $cols && $row >= 0 && $row < $rows;
37 }
38
39 public static function neighbors(int $q, int $r): array
40 {
41 $out = [];
42 foreach (self::DIRS as [$dq, $dr]) {
43 $out[] = [$q + $dq, $r + $dr];
44 }
45 return $out;
46 }
47
48 public static function neighbor(int $q, int $r, int $dir): array
49 {
50 $d = self::DIRS[($dir % 6 + 6) % 6];
51 return [$q + $d[0], $r + $d[1]];
52 }
53
54 public static function distance(int $q1, int $r1, int $q2, int $r2): int
55 {
56 return intdiv(abs($q1 - $q2) + abs($q1 + $r1 - $q2 - $r2) + abs($r1 - $r2), 2);
57 }
58
59 public static function cubeRound(float $x, float $z, float $y): array
60 {
61 $rx = (int)round($x);
62 $rz = (int)round($z);
63 $ry = (int)round($y);
64 $dx = abs($rx - $x);
65 $dz = abs($rz - $z);
66 $dy = abs($ry - $y);
67 if ($dx > $dz && $dx > $dy) {
68 $rx = -$rz - $ry;
69 } elseif ($dz > $dy) {
70 $rz = -$rx - $ry;
71 }
72 return [$rx, $rz];
73 }
74
75 /** Inclusive hex line from A to B. */
76 public static function line(int $q1, int $r1, int $q2, int $r2): array
77 {
78 $n = self::distance($q1, $r1, $q2, $r2);
79 if ($n === 0) {
80 return [[$q1, $r1]];
81 }
82 $out = [];
83 $y1 = -$q1 - $r1;
84 $y2 = -$q2 - $r2;
85 for ($i = 0; $i <= $n; $i++) {
86 $t = $i / $n;
87 $out[] = self::cubeRound(
88 $q1 + ($q2 - $q1) * $t,
89 $r1 + ($r2 - $r1) * $t,
90 $y1 + ($y2 - $y1) * $t
91 );
92 }
93 return $out;
94 }
95
96 /** Hexes from origin stepping in a facing, excluding origin. */
97 public static function ray(int $q, int $r, int $dir, int $length): array
98 {
99 $out = [];
100 for ($i = 0; $i < $length; $i++) {
101 [$q, $r] = self::neighbor($q, $r, $dir);
102 $out[] = [$q, $r];
103 }
104 return $out;
105 }
106
107 /**
108 * LoS is blocked by walls on intermediate hexes. Endpoints may be occupied.
109 * @param array<string,true> $walls
110 */
111 public static function los(int $q1, int $r1, int $q2, int $r2, array $walls): bool
112 {
113 $line = self::line($q1, $r1, $q2, $r2);
114 $last = count($line) - 1;
115 for ($i = 1; $i < $last; $i++) {
116 if (isset($walls[self::key($line[$i][0], $line[$i][1])])) {
117 return false;
118 }
119 }
120 return true;
121 }
122
123 public static function pixel(int $q, int $r): array
124 {
125 return [sqrt(3) * ($q + $r / 2), 1.5 * $r];
126 }
127
128 public static function facingAngle(int $dir): float
129 {
130 $d = self::DIRS[($dir % 6 + 6) % 6];
131 [$x, $y] = self::pixel($d[0], $d[1]);
132 return atan2($y, $x);
133 }
134
135 public static function bearing(int $q1, int $r1, int $q2, int $r2): float
136 {
137 [$x1, $y1] = self::pixel($q1, $r1);
138 [$x2, $y2] = self::pixel($q2, $r2);
139 return atan2($y2 - $y1, $x2 - $x1);
140 }
141
142 public static function angleDiff(float $a, float $b): float
143 {
144 $d = fmod($a - $b + M_PI, 2 * M_PI);
145 if ($d < 0) {
146 $d += 2 * M_PI;
147 }
148 return $d - M_PI;
149 }
150
151 public static function inCone(int $uq, int $ur, int $facing, int $tq, int $tr, float $halfDeg): bool
152 {
153 if ($uq === $tq && $ur === $tr) {
154 return false;
155 }
156 return abs(self::angleDiff(self::bearing($uq, $ur, $tq, $tr), self::facingAngle($facing))) <= deg2rad($halfDeg) + 1e-9;
157 }
158
159 public static function dirToward(int $q1, int $r1, int $q2, int $r2): int
160 {
161 $best = 0;
162 $bestAbs = INF;
163 $bearing = self::bearing($q1, $r1, $q2, $r2);
164 for ($d = 0; $d < 6; $d++) {
165 $abs = abs(self::angleDiff($bearing, self::facingAngle($d)));
166 if ($abs < $bestAbs) {
167 $bestAbs = $abs;
168 $best = $d;
169 }
170 }
171 return $best;
172 }
173
174 public static function onFacingLine(int $q, int $r, int $facing, int $tq, int $tr, int $length): bool
175 {
176 foreach (self::ray($q, $r, $facing, $length) as [$qq, $rr]) {
177 if ($qq === $tq && $rr === $tr) {
178 return true;
179 }
180 }
181 return false;
182 }
183
184 /**
185 * A* path across walkable hexes. Returns inclusive hex list or null.
186 * @param array<string,true> $walkable
187 */
188 public static function path(int $q1, int $r1, int $q2, int $r2, array $walkable): ?array
189 {
190 $start = self::key($q1, $r1);
191 $goal = self::key($q2, $r2);
192 if (!isset($walkable[$start]) || !isset($walkable[$goal])) {
193 return null;
194 }
195 if ($start === $goal) {
196 return [[$q1, $r1]];
197 }
198 $open = [$start => 0];
199 $came = [];
200 $g = [$start => 0];
201 while ($open) {
202 $current = array_key_first($open);
203 $best = $open[$current];
204 foreach ($open as $k => $f) {
205 if ($f < $best) {
206 $current = $k;
207 $best = $f;
208 }
209 }
210 unset($open[$current]);
211 if ($current === $goal) {
212 $path = [];
213 while ($current !== $start) {
214 $path[] = self::parse($current);
215 $current = $came[$current];
216 }
217 $path[] = [$q1, $r1];
218 return array_reverse($path);
219 }
220 [$cq, $cr] = self::parse($current);
221 foreach (self::neighbors($cq, $cr) as [$nq, $nr]) {
222 $nk = self::key($nq, $nr);
223 if (!isset($walkable[$nk])) {
224 continue;
225 }
226 $tg = $g[$current] + 1;
227 if (!isset($g[$nk]) || $tg < $g[$nk]) {
228 $came[$nk] = $current;
229 $g[$nk] = $tg;
230 $open[$nk] = $tg + self::distance($nq, $nr, $q2, $r2);
231 }
232 }
233 }
234 return null;
235 }
236
237 /**
238 * @return array<string,true>
239 */
240 public static function allHexes(int $cols, int $rows): array
241 {
242 $out = [];
243 for ($row = 0; $row < $rows; $row++) {
244 for ($col = 0; $col < $cols; $col++) {
245 [$q, $r] = self::axial($col, $row);
246 $out[self::key($q, $r)] = true;
247 }
248 }
249 return $out;
250 }
251}
252
253/** Deterministic 32-bit RNG used by wall generation and combat. */
254final class SynhexRng
255{
256 private int $state;
257
258 public function __construct(int $seed)
259 {
260 $this->state = $seed | 1;
261 }
262
263 public function next(): int
264 {
265 $x = $this->state;
266 $x = ($x ^ ($x << 13)) & 0x7fffffff;
267 $x = ($x ^ ($x >> 17)) & 0x7fffffff;
268 $x = ($x ^ ($x << 5)) & 0x7fffffff;
269 return $this->state = $x;
270 }
271
272 public function below(int $n): int
273 {
274 return $n <= 0 ? 0 : $this->next() % $n;
275 }
276
277 public function chance(int $percent): bool
278 {
279 if ($percent <= 0) {
280 return false;
281 }
282 if ($percent >= 100) {
283 return true;
284 }
285 return $this->below(100) < $percent;
286 }
287
288 public function unit(): float
289 {
290 return $this->next() / 0x7fffffff;
291 }
292}
web/lib/MoveFeedback.php deleted +0 −98
@@ -1,98 +0,0 @@
1 <?php
2 declare(strict_types=1);
3 require_once __DIR__.'/Chess.php';
4
5 /** Small tactical estimate for the submitted move, never a claim of perfect play. */
6 final class MoveFeedback
7 {
8 private const VALUES=['p'=>100,'n'=>300,'b'=>300,'r'=>500,'q'=>900,'k'=>0];
9 private const MATE=100000;
10 private const THRESHOLD=100;
11 private int $nodes=0;
12 private int $deadline;
13
14 public function __construct(private int $milliseconds=200,private int $maxNodes=8000) {}
15
16 public function rate(array $before,array $after): array
17 {
18 $started=hrtime(true);$this->deadline=$started+max(0,$this->milliseconds)*1000000;$this->nodes=0;
19 $out=['quality'=>null,'reason'=>'quiet','model'=>'tactical-estimate','ply'=>$after['ply']];
20 try {
21 $this->budget();
22 $result=Chess::result($after);
23 if ($result) {
24 if ($result['winner']===$before['turn']) $out['quality']='good';
25 $out['reason']=$result['winner']===null?'draw':'checkmate';
26 } elseif (Chess::claimable($before)||Chess::claimable($after)) {
27 // A move-only grade would omit the player's draw-claim option.
28 $out['reason']='draw-claim';
29 } else {
30 // Opponent's best reply, our answer, then up to two tactical continuation plies.
31 $score=-$this->search($after,2,2,-self::MATE,self::MATE,0);
32 $gain=$score-$this->material($before);
33 if ($score<=-self::MATE+100) {$out['quality']='poor';$out['reason']='mate-threat';}
34 elseif ($score>=self::MATE-100) {$out['quality']='good';$out['reason']='mate-threat';}
35 elseif ($gain>=self::THRESHOLD) {$out['quality']='good';$out['reason']='material-gain';}
36 elseif ($gain<=-self::THRESHOLD) {$out['quality']='poor';$out['reason']='material-loss';}
37 $out['gain']=$gain;
38 }
39 } catch (FeedbackLimit $e) {
40 $out['quality']=null;$out['reason']='inconclusive';
41 }
42 $out['nodes']=$this->nodes;$out['elapsed_ms']=round((hrtime(true)-$started)/1000000,2);
43 return $out;
44 }
45
46 private function budget(): void
47 {
48 if (++$this->nodes>$this->maxNodes || hrtime(true)>=$this->deadline) throw new FeedbackLimit();
49 }
50
51 /** Material from the side-to-move perspective; one pawn is 100. */
52 private function material(array $s): int
53 {
54 $value=0;
55 foreach ($s['board'] as $p) if ($p!=='.') $value+=(Chess::color($p)===$s['turn']?1:-1)*self::VALUES[strtolower($p)];
56 return $value;
57 }
58
59 private function search(array $s,int $depth,int $tactical,int $alpha,int $beta,int $ply,int $evasions=2): int
60 {
61 $this->budget();
62 $legal=Chess::legal($s);$check=Chess::check($s);
63 if (!$legal) return $check?-self::MATE+$ply:0;
64 if (Chess::dead($s)||$s['halfmove']>=150||Chess::repetitions($s)>=5) return 0;
65 $claim=Chess::claimable($s);
66 if ($depth===0 && $tactical===0) {
67 if (!$check) return $claim?max(0,$this->material($s)):$this->material($s);
68 // Give checks a little extra room; never pretend that staying in check is a legal option.
69 if ($evasions===0) throw new FeedbackLimit();
70 $tactical=1;$evasions--;
71 }
72 $best=$claim?0:-self::MATE;
73 if ($depth===0 && !$check) {
74 // Quiet material baseline; follow captures/promotions to avoid praising an exchange halfway through.
75 $best=max($best,$this->material($s));
76 if ($best>=$beta) return $best;
77 $alpha=max($alpha,$best);
78 $legal=array_values(array_filter($legal,fn($m)=>$s['board'][$m['to']]!=='.'||$m['promotion']!==null));
79 }
80 usort($legal,fn($a,$b)=>$this->priority($s,$b)<=>$this->priority($s,$a));
81 foreach ($legal as $m) {
82 $next=Chess::afterLegal($s,$m);
83 $score=-$this->search($next,max(0,$depth-1),$depth>0?$tactical:$tactical-1,-$beta,-$alpha,$ply+1,$evasions);
84 // The mover may also claim a draw using this intended move.
85 if (Chess::claimable($next)) $score=max(0,$score);
86 $best=max($best,$score);$alpha=max($alpha,$score);
87 if ($alpha>=$beta) break;
88 }
89 return $best;
90 }
91
92 private function priority(array $s,array $m): int
93 {
94 $victim=$s['board'][$m['to']];
95 return ($m['promotion']?self::VALUES[$m['promotion']]:0)+($victim==='.'?0:10*self::VALUES[strtolower($victim)]-self::VALUES[strtolower($s['board'][$m['from']])]);
96 }
97 }
98 final class FeedbackLimit extends RuntimeException {}
@@ -1,98 +0,0 @@
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/Chess.php';
4
5/** Small tactical estimate for the submitted move, never a claim of perfect play. */
6final class MoveFeedback
7{
8 private const VALUES=['p'=>100,'n'=>300,'b'=>300,'r'=>500,'q'=>900,'k'=>0];
9 private const MATE=100000;
10 private const THRESHOLD=100;
11 private int $nodes=0;
12 private int $deadline;
13
14 public function __construct(private int $milliseconds=200,private int $maxNodes=8000) {}
15
16 public function rate(array $before,array $after): array
17 {
18 $started=hrtime(true);$this->deadline=$started+max(0,$this->milliseconds)*1000000;$this->nodes=0;
19 $out=['quality'=>null,'reason'=>'quiet','model'=>'tactical-estimate','ply'=>$after['ply']];
20 try {
21 $this->budget();
22 $result=Chess::result($after);
23 if ($result) {
24 if ($result['winner']===$before['turn']) $out['quality']='good';
25 $out['reason']=$result['winner']===null?'draw':'checkmate';
26 } elseif (Chess::claimable($before)||Chess::claimable($after)) {
27 // A move-only grade would omit the player's draw-claim option.
28 $out['reason']='draw-claim';
29 } else {
30 // Opponent's best reply, our answer, then up to two tactical continuation plies.
31 $score=-$this->search($after,2,2,-self::MATE,self::MATE,0);
32 $gain=$score-$this->material($before);
33 if ($score<=-self::MATE+100) {$out['quality']='poor';$out['reason']='mate-threat';}
34 elseif ($score>=self::MATE-100) {$out['quality']='good';$out['reason']='mate-threat';}
35 elseif ($gain>=self::THRESHOLD) {$out['quality']='good';$out['reason']='material-gain';}
36 elseif ($gain<=-self::THRESHOLD) {$out['quality']='poor';$out['reason']='material-loss';}
37 $out['gain']=$gain;
38 }
39 } catch (FeedbackLimit $e) {
40 $out['quality']=null;$out['reason']='inconclusive';
41 }
42 $out['nodes']=$this->nodes;$out['elapsed_ms']=round((hrtime(true)-$started)/1000000,2);
43 return $out;
44 }
45
46 private function budget(): void
47 {
48 if (++$this->nodes>$this->maxNodes || hrtime(true)>=$this->deadline) throw new FeedbackLimit();
49 }
50
51 /** Material from the side-to-move perspective; one pawn is 100. */
52 private function material(array $s): int
53 {
54 $value=0;
55 foreach ($s['board'] as $p) if ($p!=='.') $value+=(Chess::color($p)===$s['turn']?1:-1)*self::VALUES[strtolower($p)];
56 return $value;
57 }
58
59 private function search(array $s,int $depth,int $tactical,int $alpha,int $beta,int $ply,int $evasions=2): int
60 {
61 $this->budget();
62 $legal=Chess::legal($s);$check=Chess::check($s);
63 if (!$legal) return $check?-self::MATE+$ply:0;
64 if (Chess::dead($s)||$s['halfmove']>=150||Chess::repetitions($s)>=5) return 0;
65 $claim=Chess::claimable($s);
66 if ($depth===0 && $tactical===0) {
67 if (!$check) return $claim?max(0,$this->material($s)):$this->material($s);
68 // Give checks a little extra room; never pretend that staying in check is a legal option.
69 if ($evasions===0) throw new FeedbackLimit();
70 $tactical=1;$evasions--;
71 }
72 $best=$claim?0:-self::MATE;
73 if ($depth===0 && !$check) {
74 // Quiet material baseline; follow captures/promotions to avoid praising an exchange halfway through.
75 $best=max($best,$this->material($s));
76 if ($best>=$beta) return $best;
77 $alpha=max($alpha,$best);
78 $legal=array_values(array_filter($legal,fn($m)=>$s['board'][$m['to']]!=='.'||$m['promotion']!==null));
79 }
80 usort($legal,fn($a,$b)=>$this->priority($s,$b)<=>$this->priority($s,$a));
81 foreach ($legal as $m) {
82 $next=Chess::afterLegal($s,$m);
83 $score=-$this->search($next,max(0,$depth-1),$depth>0?$tactical:$tactical-1,-$beta,-$alpha,$ply+1,$evasions);
84 // The mover may also claim a draw using this intended move.
85 if (Chess::claimable($next)) $score=max(0,$score);
86 $best=max($best,$score);$alpha=max($alpha,$score);
87 if ($alpha>=$beta) break;
88 }
89 return $best;
90 }
91
92 private function priority(array $s,array $m): int
93 {
94 $victim=$s['board'][$m['to']];
95 return ($m['promotion']?self::VALUES[$m['promotion']]:0)+($victim==='.'?0:10*self::VALUES[strtolower($victim)]-self::VALUES[strtolower($s['board'][$m['from']])]);
96 }
97}
98final class FeedbackLimit extends RuntimeException {}
web/lib/Push.php +9 −2
@@ -57,8 +57,15 @@ function pushGame(int $id,string $kind='turn',?string $recipient=null): void {
57 57 if (!$g) return;
58 58 if ($kind==='turn') {
59 59 if ($g['status']!=='active') return;
60 if ($recipient) {
61 $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
62 return;
63 }
60 64 $s=json_decode($g['state'],true);
61 $recipient=$s['turn']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a']);
65 foreach (SynhexMatch::playersToNotify($g,$s) as $user) {
66 $GLOBALS['push_events'][$id.':'.$user]=['game'=>$id,'user'=>$user,'version'=>(int)$g['version'],'kind'=>$kind];
67 }
68 return;
62 69 }
63 70 if (!$recipient) return;
64 71 $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
@@ -89,7 +96,7 @@ function pushDeliver(array $events,?Minishlink\WebPush\WebPush $push=null): void
89 96 foreach ($jobs as [$event,$g,$s]) {
90 97 $opponent=profile($g['a']===$event['user']?$g['b']:$g['a'])['name'];
91 98 $body=match($event['kind']) {'challenge'=>$opponent.' invited you to play.','rematch'=>$opponent.' wants a rematch.',default=>'Your turn against '.$opponent.'.'};
92 $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Microchess','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]);
99 $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Synhex','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]);
93 100 }
94 101 foreach ($push->flush() as $report) {
95 102 if ($report->isSubscriptionExpired()) query('DELETE FROM push_subscriptions WHERE endpoint=?',[(string)$report->getRequest()->getUri()]);
@@ -57,8 +57,15 @@ function pushGame(int $id,string $kind='turn',?string $recipient=null): void {
57 if (!$g) return;
57 if (!$g) return;
58 if ($kind==='turn') {
58 if ($kind==='turn') {
59 if ($g['status']!=='active') return;
59 if ($g['status']!=='active') return;
60 if ($recipient) {
61 $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
62 return;
63 }
60 $s=json_decode($g['state'],true);
64 $s=json_decode($g['state'],true);
61 $recipient=$s['turn']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a']);
65 foreach (SynhexMatch::playersToNotify($g,$s) as $user) {
66 $GLOBALS['push_events'][$id.':'.$user]=['game'=>$id,'user'=>$user,'version'=>(int)$g['version'],'kind'=>$kind];
67 }
68 return;
62 }
69 }
63 if (!$recipient) return;
70 if (!$recipient) return;
64 $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
71 $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
@@ -89,7 +96,7 @@ function pushDeliver(array $events,?Minishlink\WebPush\WebPush $push=null): void
89 foreach ($jobs as [$event,$g,$s]) {
96 foreach ($jobs as [$event,$g,$s]) {
90 $opponent=profile($g['a']===$event['user']?$g['b']:$g['a'])['name'];
97 $opponent=profile($g['a']===$event['user']?$g['b']:$g['a'])['name'];
91 $body=match($event['kind']) {'challenge'=>$opponent.' invited you to play.','rematch'=>$opponent.' wants a rematch.',default=>'Your turn against '.$opponent.'.'};
98 $body=match($event['kind']) {'challenge'=>$opponent.' invited you to play.','rematch'=>$opponent.' wants a rematch.',default=>'Your turn against '.$opponent.'.'};
92 $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Microchess','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]);
99 $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Synhex','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]);
93 }
100 }
94 foreach ($push->flush() as $report) {
101 foreach ($push->flush() as $report) {
95 if ($report->isSubscriptionExpired()) query('DELETE FROM push_subscriptions WHERE endpoint=?',[(string)$report->getRequest()->getUri()]);
102 if ($report->isSubscriptionExpired()) query('DELETE FROM push_subscriptions WHERE endpoint=?',[(string)$report->getRequest()->getUri()]);
web/lib/SynhexMatch.php added +399 −0
@@ -0,0 +1,399 @@
1 <?php
2 declare(strict_types=1);
3
4 /** Match lifecycle: spawn, plans, fog, commit/playback. */
5 final class SynhexMatch
6 {
7 public static function config(): array
8 {
9 if (function_exists('gameConfig')) {
10 return gameConfig();
11 }
12 return require __DIR__.'/game-config.php';
13 }
14
15 public static function initial(?int $seed = null, ?array $cfg = null): array
16 {
17 $cfg ??= self::config();
18 $seed ??= random_int(1, 0x7ffffffe);
19 $cols = (int)$cfg['grid_cols'];
20 $rows = (int)$cfg['grid_rows'];
21 $units = [];
22 $spawns = [];
23 foreach (['w', 'b'] as $team) {
24 foreach ($cfg['spawn'][$team] as $spec) {
25 [$q, $r] = HexGrid::axial((int)$spec['col'], (int)$spec['row']);
26 $id = $team.'-'.$spec['id'];
27 $units[] = [
28 'id' => $id,
29 'team' => $team,
30 'role' => $spec['role'],
31 'weapon' => $spec['weapon'],
32 'q' => $q,
33 'r' => $r,
34 'facing' => (int)$spec['facing'],
35 'alive' => true,
36 'remaining' => [],
37 'stationaryPrevAct' => true,
38 'shotTargetPrevAct' => null,
39 'deathTick' => null,
40 ];
41 $spawns[] = [$q, $r];
42 }
43 }
44 $walls = self::generateWalls($seed, $cfg, $spawns);
45 $lastKnown = ['w' => [], 'b' => []];
46 foreach ($units as $u) {
47 $other = $u['team'] === 'w' ? 'b' : 'w';
48 $lastKnown[$other][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => true];
49 }
50 return [
51 'phase' => 'planning',
52 'act' => 0,
53 'seed' => $seed,
54 'grid' => ['cols' => $cols, 'rows' => $rows, 'orientation' => $cfg['hex_orientation'], 'offset' => $cfg['hex_offset']],
55 'walls' => $walls,
56 'units' => $units,
57 'initialUnits' => $units,
58 'plans' => ['w' => null, 'b' => null],
59 'drafts' => ['w' => null, 'b' => null],
60 'committed' => ['w' => false, 'b' => false],
61 'acked' => ['w' => false, 'b' => false],
62 'timeline' => null,
63 'history' => [],
64 'lastKnown' => $lastKnown,
65 'result' => null,
66 ];
67 }
68
69 /**
70 * @param list<array{0:int,1:int}> $spawns
71 * @return list<string>
72 */
73 public static function generateWalls(int $seed, array $cfg, array $spawns): array
74 {
75 $cols = (int)$cfg['grid_cols'];
76 $rows = (int)$cfg['grid_rows'];
77 $density = (float)$cfg['wall_density'];
78 $clear = (int)$cfg['wall_clear_radius'];
79 $attempts = max(1, (int)$cfg['wall_gen_attempts']);
80 $all = HexGrid::allHexes($cols, $rows);
81 $protected = [];
82 foreach ($spawns as [$q, $r]) {
83 foreach ($all as $key => $_) {
84 [$qq, $rr] = HexGrid::parse($key);
85 if (HexGrid::distance($q, $r, $qq, $rr) <= $clear) {
86 $protected[$key] = true;
87 }
88 }
89 }
90 $start = HexGrid::key($spawns[0][0], $spawns[0][1]);
91 $mid = intdiv(count($spawns), 2);
92 $goal = HexGrid::key($spawns[$mid][0], $spawns[$mid][1]);
93 $rng = new SynhexRng($seed);
94 $walls = [];
95 for ($try = 0; $try < $attempts; $try++) {
96 $walls = [];
97 foreach ($all as $key => $_) {
98 if (isset($protected[$key])) {
99 continue;
100 }
101 if ($rng->unit() < $density) {
102 $walls[$key] = true;
103 }
104 }
105 $walkable = $all;
106 foreach ($walls as $key => $_) {
107 unset($walkable[$key]);
108 }
109 $midCol = intdiv($cols, 2);
110 if ($density > 0) {
111 for ($row = 2; $row < $rows - 2; $row++) {
112 if ($row % 3 === 0) {
113 continue;
114 }
115 [$q, $r] = HexGrid::axial($midCol, $row);
116 $k = HexGrid::key($q, $r);
117 if (!isset($protected[$k])) {
118 $walls[$k] = true;
119 unset($walkable[$k]);
120 }
121 }
122 }
123 [$sq, $sr] = HexGrid::parse($start);
124 [$gq, $gr] = HexGrid::parse($goal);
125 if (HexGrid::path($sq, $sr, $gq, $gr, $walkable)) {
126 break;
127 }
128 $density *= 0.85;
129 }
130 return array_keys($walls);
131 }
132
133 public static function isYourTurn(array $s, string $color): bool
134 {
135 if (($s['phase'] ?? '') === 'planning') {
136 return empty($s['committed'][$color]);
137 }
138 if (($s['phase'] ?? '') === 'playback') {
139 return empty($s['acked'][$color]);
140 }
141 return false;
142 }
143
144 public static function playersToNotify(array $g, array $s): array
145 {
146 $out = [];
147 foreach (['w', 'b'] as $color) {
148 if (self::isYourTurn($s, $color)) {
149 $out[] = $color === 'w' ? $g['white'] : ($g['white'] === $g['a'] ? $g['b'] : $g['a']);
150 }
151 }
152 return $out;
153 }
154
155 public static function walkable(array $s): array
156 {
157 $all = HexGrid::allHexes($s['grid']['cols'], $s['grid']['rows']);
158 foreach ($s['walls'] as $key) {
159 unset($all[$key]);
160 }
161 return $all;
162 }
163
164 public static function sanitizePlan(array $s, string $color, mixed $plan, array $cfg): array
165 {
166 if (!is_array($plan)) {
167 $plan = [];
168 }
169 $unitsIn = $plan['units'] ?? $plan;
170 if (!is_array($unitsIn)) {
171 throw new DomainException('Invalid plan.');
172 }
173 $own = [];
174 foreach ($s['units'] as $u) {
175 if ($u['team'] === $color && !empty($u['alive'])) {
176 $own[$u['id']] = $u;
177 }
178 }
179 $walkable = self::walkable($s);
180 $out = [];
181 foreach ($unitsIn as $id => $spec) {
182 if (!is_string($id) || !isset($own[$id]) || !is_array($spec)) {
183 continue;
184 }
185 $path = [];
186 $prevQ = $own[$id]['q'];
187 $prevR = $own[$id]['r'];
188 $rawPath = $spec['path'] ?? [];
189 if (!is_array($rawPath)) {
190 throw new DomainException('Invalid path.');
191 }
192 foreach ($rawPath as $step) {
193 if (!is_array($step) || !isset($step['q'], $step['r'])) {
194 throw new DomainException('Invalid waypoint.');
195 }
196 $q = (int)$step['q'];
197 $r = (int)$step['r'];
198 if (!isset($walkable[HexGrid::key($q, $r)]) || HexGrid::distance($prevQ, $prevR, $q, $r) !== 1) {
199 throw new DomainException('Path must walk adjacent open hexes.');
200 }
201 $item = ['q' => $q, 'r' => $r];
202 if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
203 $facing = (int)$step['facing'];
204 if ($facing < 0 || $facing > 5) {
205 throw new DomainException('Facing must be 0–5.');
206 }
207 $item['facing'] = $facing;
208 }
209 $path[] = $item;
210 $prevQ = $q;
211 $prevR = $r;
212 }
213 $entry = ['path' => $path];
214 if (isset($spec['facing']) && is_int($spec['facing'])) {
215 if ($spec['facing'] < 0 || $spec['facing'] > 5) {
216 throw new DomainException('Facing must be 0–5.');
217 }
218 $entry['facing'] = $spec['facing'];
219 }
220 $out[$id] = $entry;
221 }
222 return ['units' => $out];
223 }
224
225 public static function saveDraft(array $s, string $color, mixed $plan, array $cfg): array
226 {
227 if (($s['phase'] ?? '') !== 'planning' || !empty($s['committed'][$color])) {
228 throw new DomainException('Plans are locked for this act.');
229 }
230 $s['drafts'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
231 return $s;
232 }
233
234 public static function commit(array $s, string $color, mixed $plan, array $cfg): array
235 {
236 if (($s['phase'] ?? '') !== 'planning') {
237 throw new DomainException('This act is not in planning.');
238 }
239 if (!empty($s['committed'][$color])) {
240 throw new DomainException('You have already locked this plan.');
241 }
242 $s['plans'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
243 $s['drafts'][$color] = $s['plans'][$color];
244 $s['committed'][$color] = true;
245 if (!empty($s['committed']['w']) && !empty($s['committed']['b'])) {
246 $s = SynhexSim::runAct($s, $cfg);
247 }
248 return $s;
249 }
250
251 public static function ackPlayback(array $s, string $color): array
252 {
253 if (($s['phase'] ?? '') !== 'playback') {
254 throw new DomainException('There is no act to play back.');
255 }
256 $s['acked'][$color] = true;
257 if (!empty($s['acked']['w']) && !empty($s['acked']['b'])) {
258 if (!empty($s['result'])) {
259 $s['phase'] = 'ended';
260 } else {
261 $s['phase'] = 'planning';
262 $s['timeline'] = null;
263 $s['acked'] = ['w' => false, 'b' => false];
264 foreach (['w', 'b'] as $team) {
265 $draft = ['units' => []];
266 foreach ($s['units'] as $u) {
267 if ($u['team'] === $team && !empty($u['alive']) && !empty($u['remaining'])) {
268 $draft['units'][$u['id']] = ['path' => $u['remaining']];
269 }
270 }
271 $s['drafts'][$team] = $draft['units'] ? $draft : null;
272 }
273 }
274 }
275 return $s;
276 }
277
278 public static function visibleUnits(array $s, string $color, array $cfg): array
279 {
280 $out = [];
281 $walls = array_fill_keys($s['walls'], true);
282 $byId = [];
283 foreach ($s['units'] as $u) {
284 $byId[$u['id']] = $u;
285 }
286 $revealAll = ($s['act'] === 0 && ($s['phase'] ?? '') === 'planning' && !empty($cfg['see_enemies_at_match_start']));
287 foreach ($s['units'] as $u) {
288 if ($u['team'] === $color) {
289 $row = $u;
290 $row['hologram'] = false;
291 $row['known'] = true;
292 $out[] = $row;
293 continue;
294 }
295 $visible = $revealAll || self::seenNow($byId, $u, $color, $walls, $cfg);
296 if ($visible) {
297 $row = $u;
298 $row['hologram'] = false;
299 $row['known'] = true;
300 $out[] = $row;
301 continue;
302 }
303 $ghost = $s['lastKnown'][$color][$u['id']] ?? null;
304 if ($ghost) {
305 $out[] = [
306 'id' => $u['id'],
307 'team' => $u['team'],
308 'role' => $u['role'],
309 'weapon' => $u['weapon'],
310 'q' => $ghost['q'],
311 'r' => $ghost['r'],
312 'facing' => $ghost['facing'],
313 'alive' => $ghost['alive'] ?? true,
314 'hologram' => true,
315 'known' => true,
316 ];
317 }
318 }
319 return $out;
320 }
321
322 private static function seenNow(array $byId, array $enemy, string $viewer, array $walls, array $cfg): bool
323 {
324 if (empty($enemy['alive'])) {
325 return false;
326 }
327 foreach ($byId as $u) {
328 if ($u['team'] !== $viewer || empty($u['alive'])) {
329 continue;
330 }
331 $d = HexGrid::distance($u['q'], $u['r'], $enemy['q'], $enemy['r']);
332 if ($d === 0 || $d > (int)$cfg['vision_range']) {
333 continue;
334 }
335 if (HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $enemy['q'], $enemy['r'], (float)$cfg['vision_cone_half_deg'])
336 && HexGrid::los($u['q'], $u['r'], $enemy['q'], $enemy['r'], $walls)) {
337 return true;
338 }
339 }
340 return false;
341 }
342
343 public static function clientView(array $s, string $color, array $cfg): array
344 {
345 $view = [
346 'phase' => $s['phase'],
347 'act' => $s['act'],
348 'grid' => $s['grid'],
349 'walls' => $s['walls'],
350 'units' => self::visibleUnits($s, $color, $cfg),
351 'committed' => !empty($s['committed'][$color]),
352 'opponentCommitted' => !empty($s['committed'][$color === 'w' ? 'b' : 'w']),
353 'acked' => !empty($s['acked'][$color]),
354 'opponentAcked' => !empty($s['acked'][$color === 'w' ? 'b' : 'w']),
355 'draft' => $s['drafts'][$color] ?? $s['plans'][$color] ?? ['units' => []],
356 'timeline' => ($s['phase'] === 'playback') ? $s['timeline'] : null,
357 'result' => $s['result'] ?? null,
358 'rules' => [
359 'walkRange' => (int)$cfg['walk_range'],
360 'actDurationMs' => (int)$cfg['act_duration_ms'],
361 'visionConeHalfDeg' => (float)$cfg['vision_cone_half_deg'],
362 'weapons' => [
363 'pistol' => ['rofMs' => (int)$cfg['weapon_pistol_rof_ms']],
364 'smg' => ['rofMs' => (int)$cfg['weapon_smg_rof_ms']],
365 'shotgun' => ['rofMs' => (int)$cfg['weapon_shotgun_rof_ms'], 'pellets' => (int)$cfg['weapon_shotgun_pellets']],
366 ],
367 ],
368 ];
369 return $view;
370 }
371
372 public static function replayFrames(array $s): array
373 {
374 $frames = [['act' => 0, 'units' => $s['initialUnits'] ?? $s['units'], 'walls' => $s['walls'], 'grid' => $s['grid'], 'timeline' => null]];
375 foreach ($s['history'] ?? [] as $i => $act) {
376 $frames[] = [
377 'act' => $i + 1,
378 'units' => $act['endUnits'] ?? $s['units'],
379 'walls' => $s['walls'],
380 'grid' => $s['grid'],
381 'timeline' => $act,
382 ];
383 }
384 return $frames;
385 }
386
387 public static function unitBar(array $s): array
388 {
389 $cfg = self::config();
390 $totals = ['w' => 0, 'b' => 0];
391 foreach ($s['units'] as $u) {
392 if (empty($u['alive'])) {
393 continue;
394 }
395 $totals[$u['team']] += ($u['role'] === 'vip') ? (int)$cfg['unit_bar_vip'] : (int)$cfg['unit_bar_soldier'];
396 }
397 return $totals;
398 }
399 }
@@ -0,0 +1,399 @@
1<?php
2declare(strict_types=1);
3
4/** Match lifecycle: spawn, plans, fog, commit/playback. */
5final class SynhexMatch
6{
7 public static function config(): array
8 {
9 if (function_exists('gameConfig')) {
10 return gameConfig();
11 }
12 return require __DIR__.'/game-config.php';
13 }
14
15 public static function initial(?int $seed = null, ?array $cfg = null): array
16 {
17 $cfg ??= self::config();
18 $seed ??= random_int(1, 0x7ffffffe);
19 $cols = (int)$cfg['grid_cols'];
20 $rows = (int)$cfg['grid_rows'];
21 $units = [];
22 $spawns = [];
23 foreach (['w', 'b'] as $team) {
24 foreach ($cfg['spawn'][$team] as $spec) {
25 [$q, $r] = HexGrid::axial((int)$spec['col'], (int)$spec['row']);
26 $id = $team.'-'.$spec['id'];
27 $units[] = [
28 'id' => $id,
29 'team' => $team,
30 'role' => $spec['role'],
31 'weapon' => $spec['weapon'],
32 'q' => $q,
33 'r' => $r,
34 'facing' => (int)$spec['facing'],
35 'alive' => true,
36 'remaining' => [],
37 'stationaryPrevAct' => true,
38 'shotTargetPrevAct' => null,
39 'deathTick' => null,
40 ];
41 $spawns[] = [$q, $r];
42 }
43 }
44 $walls = self::generateWalls($seed, $cfg, $spawns);
45 $lastKnown = ['w' => [], 'b' => []];
46 foreach ($units as $u) {
47 $other = $u['team'] === 'w' ? 'b' : 'w';
48 $lastKnown[$other][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => true];
49 }
50 return [
51 'phase' => 'planning',
52 'act' => 0,
53 'seed' => $seed,
54 'grid' => ['cols' => $cols, 'rows' => $rows, 'orientation' => $cfg['hex_orientation'], 'offset' => $cfg['hex_offset']],
55 'walls' => $walls,
56 'units' => $units,
57 'initialUnits' => $units,
58 'plans' => ['w' => null, 'b' => null],
59 'drafts' => ['w' => null, 'b' => null],
60 'committed' => ['w' => false, 'b' => false],
61 'acked' => ['w' => false, 'b' => false],
62 'timeline' => null,
63 'history' => [],
64 'lastKnown' => $lastKnown,
65 'result' => null,
66 ];
67 }
68
69 /**
70 * @param list<array{0:int,1:int}> $spawns
71 * @return list<string>
72 */
73 public static function generateWalls(int $seed, array $cfg, array $spawns): array
74 {
75 $cols = (int)$cfg['grid_cols'];
76 $rows = (int)$cfg['grid_rows'];
77 $density = (float)$cfg['wall_density'];
78 $clear = (int)$cfg['wall_clear_radius'];
79 $attempts = max(1, (int)$cfg['wall_gen_attempts']);
80 $all = HexGrid::allHexes($cols, $rows);
81 $protected = [];
82 foreach ($spawns as [$q, $r]) {
83 foreach ($all as $key => $_) {
84 [$qq, $rr] = HexGrid::parse($key);
85 if (HexGrid::distance($q, $r, $qq, $rr) <= $clear) {
86 $protected[$key] = true;
87 }
88 }
89 }
90 $start = HexGrid::key($spawns[0][0], $spawns[0][1]);
91 $mid = intdiv(count($spawns), 2);
92 $goal = HexGrid::key($spawns[$mid][0], $spawns[$mid][1]);
93 $rng = new SynhexRng($seed);
94 $walls = [];
95 for ($try = 0; $try < $attempts; $try++) {
96 $walls = [];
97 foreach ($all as $key => $_) {
98 if (isset($protected[$key])) {
99 continue;
100 }
101 if ($rng->unit() < $density) {
102 $walls[$key] = true;
103 }
104 }
105 $walkable = $all;
106 foreach ($walls as $key => $_) {
107 unset($walkable[$key]);
108 }
109 $midCol = intdiv($cols, 2);
110 if ($density > 0) {
111 for ($row = 2; $row < $rows - 2; $row++) {
112 if ($row % 3 === 0) {
113 continue;
114 }
115 [$q, $r] = HexGrid::axial($midCol, $row);
116 $k = HexGrid::key($q, $r);
117 if (!isset($protected[$k])) {
118 $walls[$k] = true;
119 unset($walkable[$k]);
120 }
121 }
122 }
123 [$sq, $sr] = HexGrid::parse($start);
124 [$gq, $gr] = HexGrid::parse($goal);
125 if (HexGrid::path($sq, $sr, $gq, $gr, $walkable)) {
126 break;
127 }
128 $density *= 0.85;
129 }
130 return array_keys($walls);
131 }
132
133 public static function isYourTurn(array $s, string $color): bool
134 {
135 if (($s['phase'] ?? '') === 'planning') {
136 return empty($s['committed'][$color]);
137 }
138 if (($s['phase'] ?? '') === 'playback') {
139 return empty($s['acked'][$color]);
140 }
141 return false;
142 }
143
144 public static function playersToNotify(array $g, array $s): array
145 {
146 $out = [];
147 foreach (['w', 'b'] as $color) {
148 if (self::isYourTurn($s, $color)) {
149 $out[] = $color === 'w' ? $g['white'] : ($g['white'] === $g['a'] ? $g['b'] : $g['a']);
150 }
151 }
152 return $out;
153 }
154
155 public static function walkable(array $s): array
156 {
157 $all = HexGrid::allHexes($s['grid']['cols'], $s['grid']['rows']);
158 foreach ($s['walls'] as $key) {
159 unset($all[$key]);
160 }
161 return $all;
162 }
163
164 public static function sanitizePlan(array $s, string $color, mixed $plan, array $cfg): array
165 {
166 if (!is_array($plan)) {
167 $plan = [];
168 }
169 $unitsIn = $plan['units'] ?? $plan;
170 if (!is_array($unitsIn)) {
171 throw new DomainException('Invalid plan.');
172 }
173 $own = [];
174 foreach ($s['units'] as $u) {
175 if ($u['team'] === $color && !empty($u['alive'])) {
176 $own[$u['id']] = $u;
177 }
178 }
179 $walkable = self::walkable($s);
180 $out = [];
181 foreach ($unitsIn as $id => $spec) {
182 if (!is_string($id) || !isset($own[$id]) || !is_array($spec)) {
183 continue;
184 }
185 $path = [];
186 $prevQ = $own[$id]['q'];
187 $prevR = $own[$id]['r'];
188 $rawPath = $spec['path'] ?? [];
189 if (!is_array($rawPath)) {
190 throw new DomainException('Invalid path.');
191 }
192 foreach ($rawPath as $step) {
193 if (!is_array($step) || !isset($step['q'], $step['r'])) {
194 throw new DomainException('Invalid waypoint.');
195 }
196 $q = (int)$step['q'];
197 $r = (int)$step['r'];
198 if (!isset($walkable[HexGrid::key($q, $r)]) || HexGrid::distance($prevQ, $prevR, $q, $r) !== 1) {
199 throw new DomainException('Path must walk adjacent open hexes.');
200 }
201 $item = ['q' => $q, 'r' => $r];
202 if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
203 $facing = (int)$step['facing'];
204 if ($facing < 0 || $facing > 5) {
205 throw new DomainException('Facing must be 0–5.');
206 }
207 $item['facing'] = $facing;
208 }
209 $path[] = $item;
210 $prevQ = $q;
211 $prevR = $r;
212 }
213 $entry = ['path' => $path];
214 if (isset($spec['facing']) && is_int($spec['facing'])) {
215 if ($spec['facing'] < 0 || $spec['facing'] > 5) {
216 throw new DomainException('Facing must be 0–5.');
217 }
218 $entry['facing'] = $spec['facing'];
219 }
220 $out[$id] = $entry;
221 }
222 return ['units' => $out];
223 }
224
225 public static function saveDraft(array $s, string $color, mixed $plan, array $cfg): array
226 {
227 if (($s['phase'] ?? '') !== 'planning' || !empty($s['committed'][$color])) {
228 throw new DomainException('Plans are locked for this act.');
229 }
230 $s['drafts'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
231 return $s;
232 }
233
234 public static function commit(array $s, string $color, mixed $plan, array $cfg): array
235 {
236 if (($s['phase'] ?? '') !== 'planning') {
237 throw new DomainException('This act is not in planning.');
238 }
239 if (!empty($s['committed'][$color])) {
240 throw new DomainException('You have already locked this plan.');
241 }
242 $s['plans'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
243 $s['drafts'][$color] = $s['plans'][$color];
244 $s['committed'][$color] = true;
245 if (!empty($s['committed']['w']) && !empty($s['committed']['b'])) {
246 $s = SynhexSim::runAct($s, $cfg);
247 }
248 return $s;
249 }
250
251 public static function ackPlayback(array $s, string $color): array
252 {
253 if (($s['phase'] ?? '') !== 'playback') {
254 throw new DomainException('There is no act to play back.');
255 }
256 $s['acked'][$color] = true;
257 if (!empty($s['acked']['w']) && !empty($s['acked']['b'])) {
258 if (!empty($s['result'])) {
259 $s['phase'] = 'ended';
260 } else {
261 $s['phase'] = 'planning';
262 $s['timeline'] = null;
263 $s['acked'] = ['w' => false, 'b' => false];
264 foreach (['w', 'b'] as $team) {
265 $draft = ['units' => []];
266 foreach ($s['units'] as $u) {
267 if ($u['team'] === $team && !empty($u['alive']) && !empty($u['remaining'])) {
268 $draft['units'][$u['id']] = ['path' => $u['remaining']];
269 }
270 }
271 $s['drafts'][$team] = $draft['units'] ? $draft : null;
272 }
273 }
274 }
275 return $s;
276 }
277
278 public static function visibleUnits(array $s, string $color, array $cfg): array
279 {
280 $out = [];
281 $walls = array_fill_keys($s['walls'], true);
282 $byId = [];
283 foreach ($s['units'] as $u) {
284 $byId[$u['id']] = $u;
285 }
286 $revealAll = ($s['act'] === 0 && ($s['phase'] ?? '') === 'planning' && !empty($cfg['see_enemies_at_match_start']));
287 foreach ($s['units'] as $u) {
288 if ($u['team'] === $color) {
289 $row = $u;
290 $row['hologram'] = false;
291 $row['known'] = true;
292 $out[] = $row;
293 continue;
294 }
295 $visible = $revealAll || self::seenNow($byId, $u, $color, $walls, $cfg);
296 if ($visible) {
297 $row = $u;
298 $row['hologram'] = false;
299 $row['known'] = true;
300 $out[] = $row;
301 continue;
302 }
303 $ghost = $s['lastKnown'][$color][$u['id']] ?? null;
304 if ($ghost) {
305 $out[] = [
306 'id' => $u['id'],
307 'team' => $u['team'],
308 'role' => $u['role'],
309 'weapon' => $u['weapon'],
310 'q' => $ghost['q'],
311 'r' => $ghost['r'],
312 'facing' => $ghost['facing'],
313 'alive' => $ghost['alive'] ?? true,
314 'hologram' => true,
315 'known' => true,
316 ];
317 }
318 }
319 return $out;
320 }
321
322 private static function seenNow(array $byId, array $enemy, string $viewer, array $walls, array $cfg): bool
323 {
324 if (empty($enemy['alive'])) {
325 return false;
326 }
327 foreach ($byId as $u) {
328 if ($u['team'] !== $viewer || empty($u['alive'])) {
329 continue;
330 }
331 $d = HexGrid::distance($u['q'], $u['r'], $enemy['q'], $enemy['r']);
332 if ($d === 0 || $d > (int)$cfg['vision_range']) {
333 continue;
334 }
335 if (HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $enemy['q'], $enemy['r'], (float)$cfg['vision_cone_half_deg'])
336 && HexGrid::los($u['q'], $u['r'], $enemy['q'], $enemy['r'], $walls)) {
337 return true;
338 }
339 }
340 return false;
341 }
342
343 public static function clientView(array $s, string $color, array $cfg): array
344 {
345 $view = [
346 'phase' => $s['phase'],
347 'act' => $s['act'],
348 'grid' => $s['grid'],
349 'walls' => $s['walls'],
350 'units' => self::visibleUnits($s, $color, $cfg),
351 'committed' => !empty($s['committed'][$color]),
352 'opponentCommitted' => !empty($s['committed'][$color === 'w' ? 'b' : 'w']),
353 'acked' => !empty($s['acked'][$color]),
354 'opponentAcked' => !empty($s['acked'][$color === 'w' ? 'b' : 'w']),
355 'draft' => $s['drafts'][$color] ?? $s['plans'][$color] ?? ['units' => []],
356 'timeline' => ($s['phase'] === 'playback') ? $s['timeline'] : null,
357 'result' => $s['result'] ?? null,
358 'rules' => [
359 'walkRange' => (int)$cfg['walk_range'],
360 'actDurationMs' => (int)$cfg['act_duration_ms'],
361 'visionConeHalfDeg' => (float)$cfg['vision_cone_half_deg'],
362 'weapons' => [
363 'pistol' => ['rofMs' => (int)$cfg['weapon_pistol_rof_ms']],
364 'smg' => ['rofMs' => (int)$cfg['weapon_smg_rof_ms']],
365 'shotgun' => ['rofMs' => (int)$cfg['weapon_shotgun_rof_ms'], 'pellets' => (int)$cfg['weapon_shotgun_pellets']],
366 ],
367 ],
368 ];
369 return $view;
370 }
371
372 public static function replayFrames(array $s): array
373 {
374 $frames = [['act' => 0, 'units' => $s['initialUnits'] ?? $s['units'], 'walls' => $s['walls'], 'grid' => $s['grid'], 'timeline' => null]];
375 foreach ($s['history'] ?? [] as $i => $act) {
376 $frames[] = [
377 'act' => $i + 1,
378 'units' => $act['endUnits'] ?? $s['units'],
379 'walls' => $s['walls'],
380 'grid' => $s['grid'],
381 'timeline' => $act,
382 ];
383 }
384 return $frames;
385 }
386
387 public static function unitBar(array $s): array
388 {
389 $cfg = self::config();
390 $totals = ['w' => 0, 'b' => 0];
391 foreach ($s['units'] as $u) {
392 if (empty($u['alive'])) {
393 continue;
394 }
395 $totals[$u['team']] += ($u['role'] === 'vip') ? (int)$cfg['unit_bar_vip'] : (int)$cfg['unit_bar_soldier'];
396 }
397 return $totals;
398 }
399}
web/lib/SynhexSim.php added +493 −0
@@ -0,0 +1,493 @@
1 <?php
2 declare(strict_types=1);
3
4 /** Frozen-Synapse-style simultaneous act simulation. */
5 final class SynhexSim
6 {
7 /**
8 * Run one locked act. Mutates/returns a new state with timeline, updated units, fog, leftover paths.
9 */
10 public static function runAct(array $s, array $cfg): array
11 {
12 $tickMs = max(1, (int)$cfg['sim_tick_ms']);
13 $duration = max($tickMs, (int)$cfg['act_duration_ms']);
14 $ticks = intdiv($duration, $tickMs);
15 $walk = max(1, (int)$cfg['walk_range']);
16 $stepTicks = max(1, intdiv($ticks, $walk));
17 $walls = array_fill_keys($s['walls'], true);
18 $rng = new SynhexRng(((int)$s['seed'] ^ (($s['act'] + 1) * 10007)) & 0x7fffffff);
19
20 $units = [];
21 foreach ($s['units'] as $u) {
22 $units[$u['id']] = $u + [
23 'alive' => $u['alive'] ?? true,
24 'remaining' => $u['remaining'] ?? [],
25 'thisMoved' => false,
26 'thisTargets' => [],
27 'lastShotAt' => -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'],
28 'deathTick' => $u['deathTick'] ?? null,
29 ];
30 }
31
32 foreach (['w', 'b'] as $team) {
33 $plan = $s['plans'][$team]['units'] ?? [];
34 if (!is_array($plan)) {
35 continue;
36 }
37 foreach ($plan as $id => $spec) {
38 if (!isset($units[$id]) || $units[$id]['team'] !== $team || !$units[$id]['alive']) {
39 continue;
40 }
41 $path = self::normalizePath($spec['path'] ?? []);
42 $units[$id]['remaining'] = $path;
43 if ($path === [] && isset($spec['facing']) && is_int($spec['facing'])) {
44 $units[$id]['facing'] = ($spec['facing'] % 6 + 6) % 6;
45 }
46 }
47 }
48
49 return self::simulate($s, $cfg, $units, $walls, $rng, $tickMs, $duration, $ticks, $walk, $stepTicks);
50 }
51
52 private static function simulate(array $s, array $cfg, array $units, array $walls, SynhexRng $rng, int $tickMs, int $duration, int $ticks, int $walk, int $stepTicks): array
53 {
54 // Reset movement bookkeeping from the draft above.
55 foreach ($units as $id => &$u) {
56 $u['stepsTaken'] = 0;
57 $u['thisMoved'] = false;
58 $u['thisTargets'] = [];
59 $u['lastShotAt'] = -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'];
60 }
61 unset($u);
62
63 $shots = [];
64 $kills = [];
65 $visibleEver = ['w' => [], 'b' => []];
66 $firedTicks = [];
67 $snapshots = [];
68 $deathTick = ['w' => null, 'b' => null];
69
70 $recordSnap = static function (int $t) use (&$snapshots, &$units): void {
71 $snapshots[] = ['t' => $t, 'units' => self::publicUnits($units)];
72 };
73 $recordSnap(0);
74
75 for ($t = 0; $t <= $ticks; $t++) {
76 $steppedIds = [];
77 if ($t > 0 && $t % $stepTicks === 0) {
78 foreach ($units as $id => &$u) {
79 if (!$u['alive'] || $u['stepsTaken'] >= $walk || !$u['remaining']) {
80 continue;
81 }
82 $next = $u['remaining'][0];
83 $nq = (int)$next['q'];
84 $nr = (int)$next['r'];
85 if (isset($walls[HexGrid::key($nq, $nr)]) || !HexGrid::inBounds($nq, $nr, $s['grid']['cols'], $s['grid']['rows'])) {
86 $u['remaining'] = [];
87 continue;
88 }
89 if (HexGrid::distance($u['q'], $u['r'], $nq, $nr) !== 1) {
90 $u['remaining'] = [];
91 continue;
92 }
93 array_shift($u['remaining']);
94 $u['q'] = $nq;
95 $u['r'] = $nr;
96 $u['thisMoved'] = true;
97 $u['stepsTaken']++;
98 $steppedIds[$id] = true;
99 if (array_key_exists('facing', $next) && $next['facing'] !== null && $next['facing'] !== '') {
100 $u['facing'] = ((int)$next['facing'] % 6 + 6) % 6;
101 }
102 }
103 unset($u);
104 }
105
106 $now = $t * $tickMs;
107 $intended = self::intendedShots($units, $walls, $cfg, $now);
108 $focus = [];
109 foreach ($intended as $id => $target) {
110 $focus[$target] = ($focus[$target] ?? 0) + 1;
111 }
112 $aimedAt = array_flip($intended);
113
114 foreach ($intended as $id => $targetId) {
115 $shooter = $units[$id];
116 $weapon = $shooter['weapon'];
117 $rof = (int)$cfg['weapon_'.$weapon.'_rof_ms'];
118 $pellets = $weapon === 'shotgun' ? (int)$cfg['weapon_shotgun_pellets'] : 1;
119 $acc = self::accuracy($cfg, $units, $id, $targetId, $intended, $focus, $aimedAt, $walls, isset($steppedIds[$id]), isset($steppedIds[$targetId]));
120 $units[$id]['lastShotAt'] = $now;
121 $units[$id]['thisTargets'][$targetId] = true;
122 $firedTicks[$id] = $t;
123 $aims = self::pelletAims($shooter, $units[$targetId], $pellets, (int)$cfg['weapon_shotgun_spread']);
124 foreach ($aims as $aim) {
125 $victim = self::rayVictimToward($units, $walls, $shooter, $targetId, $aim[0], $aim[1], (int)$cfg['shot_range'], $cfg['friendly_fire']);
126 $hit = false;
127 if ($victim !== null) {
128 $chance = $victim === $targetId ? $acc : (int)$cfg['base_accuracy'];
129 $hit = $rng->chance($chance);
130 if ($hit && $units[$victim]['alive']) {
131 $units[$victim]['alive'] = false;
132 $units[$victim]['deathTick'] = $t;
133 if (($units[$victim]['role'] ?? '') === 'vip' && $deathTick[$units[$victim]['team']] === null) {
134 $deathTick[$units[$victim]['team']] = $t;
135 }
136 $kills[] = ['t' => $now, 'id' => $victim, 'by' => $id, 'weapon' => $weapon];
137 }
138 }
139 $shots[] = [
140 't' => $now,
141 'id' => $id,
142 'target' => $targetId,
143 'victim' => $victim,
144 'hit' => $hit,
145 'weapon' => $weapon,
146 'accuracy' => $acc,
147 'aim' => ['q' => $aim[0], 'r' => $aim[1]],
148 ];
149 }
150 }
151
152 $seen = self::visibility($units, $walls, $cfg, $firedTicks, $t);
153 foreach (['w', 'b'] as $team) {
154 foreach ($seen[$team] as $oid) {
155 $visibleEver[$team][$oid] = true;
156 }
157 }
158
159 if ($t === 0 || $t === $ticks || $steppedIds) {
160 $recordSnap($now);
161 }
162 }
163
164 $endUnits = [];
165 foreach ($units as $u) {
166 $prevTargets = array_keys($u['thisTargets']);
167 $endUnits[] = [
168 'id' => $u['id'],
169 'team' => $u['team'],
170 'role' => $u['role'],
171 'weapon' => $u['weapon'],
172 'q' => $u['q'],
173 'r' => $u['r'],
174 'facing' => $u['facing'],
175 'alive' => $u['alive'],
176 'remaining' => array_values($u['remaining']),
177 'stationaryPrevAct' => !$u['thisMoved'],
178 'shotTargetPrevAct' => count($prevTargets) === 1 ? $prevTargets[0] : (count($prevTargets) > 1 ? '*' : null),
179 'deathTick' => $u['deathTick'],
180 ];
181 }
182
183 $lastKnown = $s['lastKnown'] ?? ['w' => [], 'b' => []];
184 foreach (['w', 'b'] as $team) {
185 foreach ($endUnits as $u) {
186 if ($u['team'] === $team) {
187 continue;
188 }
189 $seen = isset($visibleEver[$team][$u['id']]) || isset($firedTicks[$u['id']]);
190 if ($seen || ($s['act'] === 0 && !empty($cfg['see_enemies_at_match_start']))) {
191 $lastKnown[$team][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => $u['alive']];
192 }
193 }
194 }
195
196 $winner = null;
197 $reason = null;
198 if ($deathTick['w'] !== null && $deathTick['b'] !== null) {
199 if ($deathTick['w'] === $deathTick['b']) {
200 $reason = 'Both VIPs fell';
201 } else {
202 $winner = $deathTick['w'] < $deathTick['b'] ? 'b' : 'w';
203 $reason = 'VIP eliminated';
204 }
205 } elseif ($deathTick['w'] !== null) {
206 $winner = 'b';
207 $reason = 'VIP eliminated';
208 } elseif ($deathTick['b'] !== null) {
209 $winner = 'w';
210 $reason = 'VIP eliminated';
211 }
212
213 $timeline = [
214 'act' => $s['act'] + 1,
215 'durationMs' => $duration,
216 'tickMs' => $tickMs,
217 'snapshots' => self::dedupeSnaps($snapshots),
218 'shots' => $shots,
219 'kills' => $kills,
220 'endUnits' => $endUnits,
221 'winner' => $winner,
222 'reason' => $reason,
223 ];
224
225 $s['units'] = $endUnits;
226 $s['act'] = $s['act'] + 1;
227 $s['phase'] = 'playback';
228 $s['committed'] = ['w' => false, 'b' => false];
229 $s['acked'] = ['w' => false, 'b' => false];
230 $s['plans'] = ['w' => null, 'b' => null];
231 $s['drafts'] = ['w' => null, 'b' => null];
232 $s['timeline'] = $timeline;
233 $s['history'][] = $timeline;
234 $s['lastKnown'] = $lastKnown;
235 $s['result'] = $winner || $reason ? ['winner' => $winner, 'reason' => $reason] : null;
236 return $s;
237 }
238
239 private static function dedupeSnaps(array $snaps): array
240 {
241 $out = [];
242 $lastT = -1;
243 foreach ($snaps as $snap) {
244 if ($snap['t'] === $lastT) {
245 $out[count($out) - 1] = $snap;
246 } else {
247 $out[] = $snap;
248 $lastT = $snap['t'];
249 }
250 }
251 return $out;
252 }
253
254 private static function publicUnits(array $units): array
255 {
256 $out = [];
257 foreach ($units as $u) {
258 $out[] = [
259 'id' => $u['id'],
260 'team' => $u['team'],
261 'role' => $u['role'],
262 'weapon' => $u['weapon'],
263 'q' => $u['q'],
264 'r' => $u['r'],
265 'facing' => $u['facing'],
266 'alive' => $u['alive'],
267 ];
268 }
269 return $out;
270 }
271
272 private static function normalizePath(mixed $path): array
273 {
274 if (!is_array($path)) {
275 return [];
276 }
277 $out = [];
278 foreach ($path as $step) {
279 if (!is_array($step) || !isset($step['q'], $step['r'])) {
280 continue;
281 }
282 $item = ['q' => (int)$step['q'], 'r' => (int)$step['r']];
283 if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
284 $item['facing'] = ((int)$step['facing'] % 6 + 6) % 6;
285 }
286 $out[] = $item;
287 }
288 return $out;
289 }
290
291 /**
292 * @return array<string,string> shooter id => target id
293 */
294 private static function intendedShots(array $units, array $walls, array $cfg, int $now): array
295 {
296 $out = [];
297 foreach ($units as $id => $u) {
298 if (!$u['alive']) {
299 continue;
300 }
301 $rof = (int)$cfg['weapon_'.$u['weapon'].'_rof_ms'];
302 if ($now - (int)$u['lastShotAt'] < $rof) {
303 continue;
304 }
305 $best = null;
306 $bestD = PHP_INT_MAX;
307 foreach ($units as $oid => $o) {
308 if (!$o['alive'] || $o['team'] === $u['team']) {
309 continue;
310 }
311 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
312 if ($d === 0 || $d > (int)$cfg['shot_range']) {
313 continue;
314 }
315 if (!HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])) {
316 continue;
317 }
318 if (!HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls)) {
319 continue;
320 }
321 if ($d < $bestD) {
322 $bestD = $d;
323 $best = $oid;
324 }
325 }
326 if ($best !== null) {
327 $out[$id] = $best;
328 }
329 }
330 ksort($out);
331 return $out;
332 }
333
334 private static function accuracy(array $cfg, array $units, string $id, string $targetId, array $intended, array $focus, array $aimedAt, array $walls, bool $shooterStepped, bool $targetStepped): int
335 {
336 $s = $units[$id];
337 $t = $units[$targetId];
338 $acc = (int)$cfg['base_accuracy'];
339 if (!$shooterStepped) {
340 $acc += (int)$cfg['accuracy_bonus_shooter_stationary'];
341 }
342 if (HexGrid::onFacingLine($s['q'], $s['r'], (int)$s['facing'], $t['q'], $t['r'], (int)$cfg['shot_range'])) {
343 $acc += (int)$cfg['accuracy_bonus_target_forward'];
344 }
345 $dist = HexGrid::distance($s['q'], $s['r'], $t['q'], $t['r']);
346 if ($dist <= (int)$cfg['close_range_hexes']) {
347 $acc += (int)$cfg['accuracy_bonus_target_close'];
348 if ($s['weapon'] === 'shotgun') {
349 $acc += (int)$cfg['accuracy_bonus_shotgun_close_extra'];
350 }
351 }
352 if (($intended[$targetId] ?? null) !== $id) {
353 $acc += (int)$cfg['accuracy_bonus_target_not_shooting_this'];
354 }
355 if (!empty($s['stationaryPrevAct'])) {
356 $acc += (int)$cfg['accuracy_bonus_still_previous_act'];
357 }
358 $prev = $s['shotTargetPrevAct'] ?? null;
359 if ($prev === null || $prev === $targetId) {
360 $acc += (int)$cfg['accuracy_bonus_same_or_no_target_previous_act'];
361 }
362 if (($focus[$targetId] ?? 0) > 1) {
363 $acc += (int)$cfg['accuracy_bonus_friendly_focus_fire'];
364 }
365 if (self::noCoverWall($s, $t, $walls)) {
366 $acc += (int)$cfg['accuracy_bonus_target_no_cover_wall'];
367 }
368 if (!$targetStepped) {
369 $acc += (int)$cfg['accuracy_bonus_target_stationary'];
370 }
371 if (!isset($aimedAt[$id])) {
372 $acc += (int)$cfg['accuracy_bonus_nobody_shooting_at_shooter'];
373 }
374 return max(0, min((int)$cfg['accuracy_cap'], $acc));
375 }
376
377 private static function noCoverWall(array $shooter, array $target, array $walls): bool
378 {
379 $tq = $target['q'];
380 $tr = $target['r'];
381 $cover = false;
382 foreach (HexGrid::neighbors($tq, $tr) as [$q, $r]) {
383 if (!isset($walls[HexGrid::key($q, $r)])) {
384 continue;
385 }
386 if (HexGrid::distance($shooter['q'], $shooter['r'], $q, $r) < HexGrid::distance($shooter['q'], $shooter['r'], $tq, $tr)) {
387 $cover = true;
388 break;
389 }
390 }
391 return !$cover;
392 }
393
394 /** Aim points for a volley: the target, plus nearby hexes for shotgun pellets. */
395 private static function pelletAims(array $shooter, array $target, int $pellets, int $spread): array
396 {
397 $aims = [[$target['q'], $target['r']]];
398 if ($pellets <= 1) {
399 return $aims;
400 }
401 $neighbors = HexGrid::neighbors($target['q'], $target['r']);
402 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $target['q'], $target['r']);
403 $order = [];
404 foreach ($neighbors as $i => $hex) {
405 $away = HexGrid::distance($shooter['q'], $shooter['r'], $hex[0], $hex[1]);
406 $order[] = [$away, $i, $hex];
407 }
408 usort($order, static fn($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
409 foreach ($order as [, , $hex]) {
410 if (count($aims) >= $pellets) {
411 break;
412 }
413 if (HexGrid::distance($hex[0], $hex[1], $target['q'], $target['r']) <= max(1, $spread)) {
414 $aims[] = $hex;
415 }
416 }
417 while (count($aims) < $pellets) {
418 $aims[] = HexGrid::neighbor($target['q'], $target['r'], ($dir + count($aims)) % 6);
419 }
420 return array_slice($aims, 0, $pellets);
421 }
422
423 private static function rayVictimToward(array $units, array $walls, array $shooter, string $intended, int $aq, int $ar, int $range, bool $friendlyFire): ?string
424 {
425 $occ = [];
426 foreach ($units as $u) {
427 if ($u['alive']) {
428 $occ[HexGrid::key($u['q'], $u['r'])][] = $u['id'];
429 }
430 }
431 $line = HexGrid::line($shooter['q'], $shooter['r'], $aq, $ar);
432 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $aq, $ar);
433 while (count($line) < $range + 1) {
434 $last = $line[count($line) - 1];
435 $line[] = HexGrid::neighbor($last[0], $last[1], $dir);
436 }
437 foreach ($line as $i => [$q, $r]) {
438 if ($i === 0) {
439 continue;
440 }
441 $k = HexGrid::key($q, $r);
442 if (isset($walls[$k])) {
443 return null;
444 }
445 if (!empty($occ[$k])) {
446 foreach ($occ[$k] as $id) {
447 if ($id === $shooter['id']) {
448 continue;
449 }
450 if (!$friendlyFire && $units[$id]['team'] === $shooter['team'] && $id !== $intended) {
451 continue;
452 }
453 return $id;
454 }
455 }
456 }
457 return null;
458 }
459
460 /**
461 * @return array{w: list<string>, b: list<string>}
462 */
463 public static function visibility(array $units, array $walls, array $cfg, array $firedTicks, int $t): array
464 {
465 $seen = ['w' => [], 'b' => []];
466 foreach ($units as $u) {
467 if (!$u['alive']) {
468 continue;
469 }
470 foreach ($units as $o) {
471 if ($o['team'] === $u['team']) {
472 $seen[$u['team']][] = $o['id'];
473 continue;
474 }
475 if (!$o['alive']) {
476 continue;
477 }
478 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
479 $inVision = $d > 0 && $d <= (int)$cfg['vision_range']
480 && HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])
481 && HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls);
482 $firing = !empty($cfg['see_enemies_when_firing']) && isset($firedTicks[$o['id']]) && $firedTicks[$o['id']] === $t;
483 if ($inVision || $firing) {
484 $seen[$u['team']][] = $o['id'];
485 }
486 }
487 }
488 foreach (['w', 'b'] as $team) {
489 $seen[$team] = array_values(array_unique($seen[$team]));
490 }
491 return $seen;
492 }
493 }
@@ -0,0 +1,493 @@
1<?php
2declare(strict_types=1);
3
4/** Frozen-Synapse-style simultaneous act simulation. */
5final class SynhexSim
6{
7 /**
8 * Run one locked act. Mutates/returns a new state with timeline, updated units, fog, leftover paths.
9 */
10 public static function runAct(array $s, array $cfg): array
11 {
12 $tickMs = max(1, (int)$cfg['sim_tick_ms']);
13 $duration = max($tickMs, (int)$cfg['act_duration_ms']);
14 $ticks = intdiv($duration, $tickMs);
15 $walk = max(1, (int)$cfg['walk_range']);
16 $stepTicks = max(1, intdiv($ticks, $walk));
17 $walls = array_fill_keys($s['walls'], true);
18 $rng = new SynhexRng(((int)$s['seed'] ^ (($s['act'] + 1) * 10007)) & 0x7fffffff);
19
20 $units = [];
21 foreach ($s['units'] as $u) {
22 $units[$u['id']] = $u + [
23 'alive' => $u['alive'] ?? true,
24 'remaining' => $u['remaining'] ?? [],
25 'thisMoved' => false,
26 'thisTargets' => [],
27 'lastShotAt' => -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'],
28 'deathTick' => $u['deathTick'] ?? null,
29 ];
30 }
31
32 foreach (['w', 'b'] as $team) {
33 $plan = $s['plans'][$team]['units'] ?? [];
34 if (!is_array($plan)) {
35 continue;
36 }
37 foreach ($plan as $id => $spec) {
38 if (!isset($units[$id]) || $units[$id]['team'] !== $team || !$units[$id]['alive']) {
39 continue;
40 }
41 $path = self::normalizePath($spec['path'] ?? []);
42 $units[$id]['remaining'] = $path;
43 if ($path === [] && isset($spec['facing']) && is_int($spec['facing'])) {
44 $units[$id]['facing'] = ($spec['facing'] % 6 + 6) % 6;
45 }
46 }
47 }
48
49 return self::simulate($s, $cfg, $units, $walls, $rng, $tickMs, $duration, $ticks, $walk, $stepTicks);
50 }
51
52 private static function simulate(array $s, array $cfg, array $units, array $walls, SynhexRng $rng, int $tickMs, int $duration, int $ticks, int $walk, int $stepTicks): array
53 {
54 // Reset movement bookkeeping from the draft above.
55 foreach ($units as $id => &$u) {
56 $u['stepsTaken'] = 0;
57 $u['thisMoved'] = false;
58 $u['thisTargets'] = [];
59 $u['lastShotAt'] = -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'];
60 }
61 unset($u);
62
63 $shots = [];
64 $kills = [];
65 $visibleEver = ['w' => [], 'b' => []];
66 $firedTicks = [];
67 $snapshots = [];
68 $deathTick = ['w' => null, 'b' => null];
69
70 $recordSnap = static function (int $t) use (&$snapshots, &$units): void {
71 $snapshots[] = ['t' => $t, 'units' => self::publicUnits($units)];
72 };
73 $recordSnap(0);
74
75 for ($t = 0; $t <= $ticks; $t++) {
76 $steppedIds = [];
77 if ($t > 0 && $t % $stepTicks === 0) {
78 foreach ($units as $id => &$u) {
79 if (!$u['alive'] || $u['stepsTaken'] >= $walk || !$u['remaining']) {
80 continue;
81 }
82 $next = $u['remaining'][0];
83 $nq = (int)$next['q'];
84 $nr = (int)$next['r'];
85 if (isset($walls[HexGrid::key($nq, $nr)]) || !HexGrid::inBounds($nq, $nr, $s['grid']['cols'], $s['grid']['rows'])) {
86 $u['remaining'] = [];
87 continue;
88 }
89 if (HexGrid::distance($u['q'], $u['r'], $nq, $nr) !== 1) {
90 $u['remaining'] = [];
91 continue;
92 }
93 array_shift($u['remaining']);
94 $u['q'] = $nq;
95 $u['r'] = $nr;
96 $u['thisMoved'] = true;
97 $u['stepsTaken']++;
98 $steppedIds[$id] = true;
99 if (array_key_exists('facing', $next) && $next['facing'] !== null && $next['facing'] !== '') {
100 $u['facing'] = ((int)$next['facing'] % 6 + 6) % 6;
101 }
102 }
103 unset($u);
104 }
105
106 $now = $t * $tickMs;
107 $intended = self::intendedShots($units, $walls, $cfg, $now);
108 $focus = [];
109 foreach ($intended as $id => $target) {
110 $focus[$target] = ($focus[$target] ?? 0) + 1;
111 }
112 $aimedAt = array_flip($intended);
113
114 foreach ($intended as $id => $targetId) {
115 $shooter = $units[$id];
116 $weapon = $shooter['weapon'];
117 $rof = (int)$cfg['weapon_'.$weapon.'_rof_ms'];
118 $pellets = $weapon === 'shotgun' ? (int)$cfg['weapon_shotgun_pellets'] : 1;
119 $acc = self::accuracy($cfg, $units, $id, $targetId, $intended, $focus, $aimedAt, $walls, isset($steppedIds[$id]), isset($steppedIds[$targetId]));
120 $units[$id]['lastShotAt'] = $now;
121 $units[$id]['thisTargets'][$targetId] = true;
122 $firedTicks[$id] = $t;
123 $aims = self::pelletAims($shooter, $units[$targetId], $pellets, (int)$cfg['weapon_shotgun_spread']);
124 foreach ($aims as $aim) {
125 $victim = self::rayVictimToward($units, $walls, $shooter, $targetId, $aim[0], $aim[1], (int)$cfg['shot_range'], $cfg['friendly_fire']);
126 $hit = false;
127 if ($victim !== null) {
128 $chance = $victim === $targetId ? $acc : (int)$cfg['base_accuracy'];
129 $hit = $rng->chance($chance);
130 if ($hit && $units[$victim]['alive']) {
131 $units[$victim]['alive'] = false;
132 $units[$victim]['deathTick'] = $t;
133 if (($units[$victim]['role'] ?? '') === 'vip' && $deathTick[$units[$victim]['team']] === null) {
134 $deathTick[$units[$victim]['team']] = $t;
135 }
136 $kills[] = ['t' => $now, 'id' => $victim, 'by' => $id, 'weapon' => $weapon];
137 }
138 }
139 $shots[] = [
140 't' => $now,
141 'id' => $id,
142 'target' => $targetId,
143 'victim' => $victim,
144 'hit' => $hit,
145 'weapon' => $weapon,
146 'accuracy' => $acc,
147 'aim' => ['q' => $aim[0], 'r' => $aim[1]],
148 ];
149 }
150 }
151
152 $seen = self::visibility($units, $walls, $cfg, $firedTicks, $t);
153 foreach (['w', 'b'] as $team) {
154 foreach ($seen[$team] as $oid) {
155 $visibleEver[$team][$oid] = true;
156 }
157 }
158
159 if ($t === 0 || $t === $ticks || $steppedIds) {
160 $recordSnap($now);
161 }
162 }
163
164 $endUnits = [];
165 foreach ($units as $u) {
166 $prevTargets = array_keys($u['thisTargets']);
167 $endUnits[] = [
168 'id' => $u['id'],
169 'team' => $u['team'],
170 'role' => $u['role'],
171 'weapon' => $u['weapon'],
172 'q' => $u['q'],
173 'r' => $u['r'],
174 'facing' => $u['facing'],
175 'alive' => $u['alive'],
176 'remaining' => array_values($u['remaining']),
177 'stationaryPrevAct' => !$u['thisMoved'],
178 'shotTargetPrevAct' => count($prevTargets) === 1 ? $prevTargets[0] : (count($prevTargets) > 1 ? '*' : null),
179 'deathTick' => $u['deathTick'],
180 ];
181 }
182
183 $lastKnown = $s['lastKnown'] ?? ['w' => [], 'b' => []];
184 foreach (['w', 'b'] as $team) {
185 foreach ($endUnits as $u) {
186 if ($u['team'] === $team) {
187 continue;
188 }
189 $seen = isset($visibleEver[$team][$u['id']]) || isset($firedTicks[$u['id']]);
190 if ($seen || ($s['act'] === 0 && !empty($cfg['see_enemies_at_match_start']))) {
191 $lastKnown[$team][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => $u['alive']];
192 }
193 }
194 }
195
196 $winner = null;
197 $reason = null;
198 if ($deathTick['w'] !== null && $deathTick['b'] !== null) {
199 if ($deathTick['w'] === $deathTick['b']) {
200 $reason = 'Both VIPs fell';
201 } else {
202 $winner = $deathTick['w'] < $deathTick['b'] ? 'b' : 'w';
203 $reason = 'VIP eliminated';
204 }
205 } elseif ($deathTick['w'] !== null) {
206 $winner = 'b';
207 $reason = 'VIP eliminated';
208 } elseif ($deathTick['b'] !== null) {
209 $winner = 'w';
210 $reason = 'VIP eliminated';
211 }
212
213 $timeline = [
214 'act' => $s['act'] + 1,
215 'durationMs' => $duration,
216 'tickMs' => $tickMs,
217 'snapshots' => self::dedupeSnaps($snapshots),
218 'shots' => $shots,
219 'kills' => $kills,
220 'endUnits' => $endUnits,
221 'winner' => $winner,
222 'reason' => $reason,
223 ];
224
225 $s['units'] = $endUnits;
226 $s['act'] = $s['act'] + 1;
227 $s['phase'] = 'playback';
228 $s['committed'] = ['w' => false, 'b' => false];
229 $s['acked'] = ['w' => false, 'b' => false];
230 $s['plans'] = ['w' => null, 'b' => null];
231 $s['drafts'] = ['w' => null, 'b' => null];
232 $s['timeline'] = $timeline;
233 $s['history'][] = $timeline;
234 $s['lastKnown'] = $lastKnown;
235 $s['result'] = $winner || $reason ? ['winner' => $winner, 'reason' => $reason] : null;
236 return $s;
237 }
238
239 private static function dedupeSnaps(array $snaps): array
240 {
241 $out = [];
242 $lastT = -1;
243 foreach ($snaps as $snap) {
244 if ($snap['t'] === $lastT) {
245 $out[count($out) - 1] = $snap;
246 } else {
247 $out[] = $snap;
248 $lastT = $snap['t'];
249 }
250 }
251 return $out;
252 }
253
254 private static function publicUnits(array $units): array
255 {
256 $out = [];
257 foreach ($units as $u) {
258 $out[] = [
259 'id' => $u['id'],
260 'team' => $u['team'],
261 'role' => $u['role'],
262 'weapon' => $u['weapon'],
263 'q' => $u['q'],
264 'r' => $u['r'],
265 'facing' => $u['facing'],
266 'alive' => $u['alive'],
267 ];
268 }
269 return $out;
270 }
271
272 private static function normalizePath(mixed $path): array
273 {
274 if (!is_array($path)) {
275 return [];
276 }
277 $out = [];
278 foreach ($path as $step) {
279 if (!is_array($step) || !isset($step['q'], $step['r'])) {
280 continue;
281 }
282 $item = ['q' => (int)$step['q'], 'r' => (int)$step['r']];
283 if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
284 $item['facing'] = ((int)$step['facing'] % 6 + 6) % 6;
285 }
286 $out[] = $item;
287 }
288 return $out;
289 }
290
291 /**
292 * @return array<string,string> shooter id => target id
293 */
294 private static function intendedShots(array $units, array $walls, array $cfg, int $now): array
295 {
296 $out = [];
297 foreach ($units as $id => $u) {
298 if (!$u['alive']) {
299 continue;
300 }
301 $rof = (int)$cfg['weapon_'.$u['weapon'].'_rof_ms'];
302 if ($now - (int)$u['lastShotAt'] < $rof) {
303 continue;
304 }
305 $best = null;
306 $bestD = PHP_INT_MAX;
307 foreach ($units as $oid => $o) {
308 if (!$o['alive'] || $o['team'] === $u['team']) {
309 continue;
310 }
311 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
312 if ($d === 0 || $d > (int)$cfg['shot_range']) {
313 continue;
314 }
315 if (!HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])) {
316 continue;
317 }
318 if (!HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls)) {
319 continue;
320 }
321 if ($d < $bestD) {
322 $bestD = $d;
323 $best = $oid;
324 }
325 }
326 if ($best !== null) {
327 $out[$id] = $best;
328 }
329 }
330 ksort($out);
331 return $out;
332 }
333
334 private static function accuracy(array $cfg, array $units, string $id, string $targetId, array $intended, array $focus, array $aimedAt, array $walls, bool $shooterStepped, bool $targetStepped): int
335 {
336 $s = $units[$id];
337 $t = $units[$targetId];
338 $acc = (int)$cfg['base_accuracy'];
339 if (!$shooterStepped) {
340 $acc += (int)$cfg['accuracy_bonus_shooter_stationary'];
341 }
342 if (HexGrid::onFacingLine($s['q'], $s['r'], (int)$s['facing'], $t['q'], $t['r'], (int)$cfg['shot_range'])) {
343 $acc += (int)$cfg['accuracy_bonus_target_forward'];
344 }
345 $dist = HexGrid::distance($s['q'], $s['r'], $t['q'], $t['r']);
346 if ($dist <= (int)$cfg['close_range_hexes']) {
347 $acc += (int)$cfg['accuracy_bonus_target_close'];
348 if ($s['weapon'] === 'shotgun') {
349 $acc += (int)$cfg['accuracy_bonus_shotgun_close_extra'];
350 }
351 }
352 if (($intended[$targetId] ?? null) !== $id) {
353 $acc += (int)$cfg['accuracy_bonus_target_not_shooting_this'];
354 }
355 if (!empty($s['stationaryPrevAct'])) {
356 $acc += (int)$cfg['accuracy_bonus_still_previous_act'];
357 }
358 $prev = $s['shotTargetPrevAct'] ?? null;
359 if ($prev === null || $prev === $targetId) {
360 $acc += (int)$cfg['accuracy_bonus_same_or_no_target_previous_act'];
361 }
362 if (($focus[$targetId] ?? 0) > 1) {
363 $acc += (int)$cfg['accuracy_bonus_friendly_focus_fire'];
364 }
365 if (self::noCoverWall($s, $t, $walls)) {
366 $acc += (int)$cfg['accuracy_bonus_target_no_cover_wall'];
367 }
368 if (!$targetStepped) {
369 $acc += (int)$cfg['accuracy_bonus_target_stationary'];
370 }
371 if (!isset($aimedAt[$id])) {
372 $acc += (int)$cfg['accuracy_bonus_nobody_shooting_at_shooter'];
373 }
374 return max(0, min((int)$cfg['accuracy_cap'], $acc));
375 }
376
377 private static function noCoverWall(array $shooter, array $target, array $walls): bool
378 {
379 $tq = $target['q'];
380 $tr = $target['r'];
381 $cover = false;
382 foreach (HexGrid::neighbors($tq, $tr) as [$q, $r]) {
383 if (!isset($walls[HexGrid::key($q, $r)])) {
384 continue;
385 }
386 if (HexGrid::distance($shooter['q'], $shooter['r'], $q, $r) < HexGrid::distance($shooter['q'], $shooter['r'], $tq, $tr)) {
387 $cover = true;
388 break;
389 }
390 }
391 return !$cover;
392 }
393
394 /** Aim points for a volley: the target, plus nearby hexes for shotgun pellets. */
395 private static function pelletAims(array $shooter, array $target, int $pellets, int $spread): array
396 {
397 $aims = [[$target['q'], $target['r']]];
398 if ($pellets <= 1) {
399 return $aims;
400 }
401 $neighbors = HexGrid::neighbors($target['q'], $target['r']);
402 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $target['q'], $target['r']);
403 $order = [];
404 foreach ($neighbors as $i => $hex) {
405 $away = HexGrid::distance($shooter['q'], $shooter['r'], $hex[0], $hex[1]);
406 $order[] = [$away, $i, $hex];
407 }
408 usort($order, static fn($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
409 foreach ($order as [, , $hex]) {
410 if (count($aims) >= $pellets) {
411 break;
412 }
413 if (HexGrid::distance($hex[0], $hex[1], $target['q'], $target['r']) <= max(1, $spread)) {
414 $aims[] = $hex;
415 }
416 }
417 while (count($aims) < $pellets) {
418 $aims[] = HexGrid::neighbor($target['q'], $target['r'], ($dir + count($aims)) % 6);
419 }
420 return array_slice($aims, 0, $pellets);
421 }
422
423 private static function rayVictimToward(array $units, array $walls, array $shooter, string $intended, int $aq, int $ar, int $range, bool $friendlyFire): ?string
424 {
425 $occ = [];
426 foreach ($units as $u) {
427 if ($u['alive']) {
428 $occ[HexGrid::key($u['q'], $u['r'])][] = $u['id'];
429 }
430 }
431 $line = HexGrid::line($shooter['q'], $shooter['r'], $aq, $ar);
432 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $aq, $ar);
433 while (count($line) < $range + 1) {
434 $last = $line[count($line) - 1];
435 $line[] = HexGrid::neighbor($last[0], $last[1], $dir);
436 }
437 foreach ($line as $i => [$q, $r]) {
438 if ($i === 0) {
439 continue;
440 }
441 $k = HexGrid::key($q, $r);
442 if (isset($walls[$k])) {
443 return null;
444 }
445 if (!empty($occ[$k])) {
446 foreach ($occ[$k] as $id) {
447 if ($id === $shooter['id']) {
448 continue;
449 }
450 if (!$friendlyFire && $units[$id]['team'] === $shooter['team'] && $id !== $intended) {
451 continue;
452 }
453 return $id;
454 }
455 }
456 }
457 return null;
458 }
459
460 /**
461 * @return array{w: list<string>, b: list<string>}
462 */
463 public static function visibility(array $units, array $walls, array $cfg, array $firedTicks, int $t): array
464 {
465 $seen = ['w' => [], 'b' => []];
466 foreach ($units as $u) {
467 if (!$u['alive']) {
468 continue;
469 }
470 foreach ($units as $o) {
471 if ($o['team'] === $u['team']) {
472 $seen[$u['team']][] = $o['id'];
473 continue;
474 }
475 if (!$o['alive']) {
476 continue;
477 }
478 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
479 $inVision = $d > 0 && $d <= (int)$cfg['vision_range']
480 && HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])
481 && HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls);
482 $firing = !empty($cfg['see_enemies_when_firing']) && isset($firedTicks[$o['id']]) && $firedTicks[$o['id']] === $t;
483 if ($inVision || $firing) {
484 $seen[$u['team']][] = $o['id'];
485 }
486 }
487 }
488 foreach (['w', 'b'] as $team) {
489 $seen[$team] = array_values(array_unique($seen[$team]));
490 }
491 return $seen;
492 }
493}
web/lib/bootstrap.php +41 −35
@@ -1,7 +1,8 @@
1 1 <?php
2 2 declare(strict_types=1);
3 require_once __DIR__.'/Chess.php';
4 require_once __DIR__.'/MoveFeedback.php';
3 require_once __DIR__.'/HexGrid.php';
4 require_once __DIR__.'/SynhexSim.php';
5 require_once __DIR__.'/SynhexMatch.php';
5 6 require_once __DIR__.'/Push.php';
6 7 require_once __DIR__.'/PieceColors.php';
7 8 ini_set('display_errors','0');
@@ -15,7 +16,7 @@ header('Cache-Control: no-store');
15 16 function db(): PDO {
16 17 static $db;
17 18 if ($db) return $db;
18 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/microchess.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
19 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/synhex.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
19 20 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
20 21 $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
21 22 CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
@@ -161,7 +162,7 @@ function config(): array {
161 162 try {
162 163 if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.');
163 164 if (!file_exists($path)) {
164 $template="<?php\n// Fill in these values on this server. Empty fields use environment variables.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
165 $template="<?php\n// Fill in OAuth values on this server. Empty fields use environment variables.\n// Game balance knobs live in lib/game-config.php; optional overrides of those keys may be added here.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
165 166 if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.');
166 167 }
167 168 $values=require $path;
@@ -170,15 +171,28 @@ function config(): array {
170 171 flock($lock,LOCK_UN);
171 172 fclose($lock);
172 173 }
173 foreach (['base_url'=>'MICROCHESS_BASE_URL','client_id'=>'MICROCHESS_CLIENT_ID','client_secret'=>'MICROCHESS_CLIENT_SECRET'] as $key=>$env) {
174 foreach (['base_url'=>'SYNHEX_BASE_URL','client_id'=>'SYNHEX_CLIENT_ID','client_secret'=>'SYNHEX_CLIENT_SECRET'] as $key=>$env) {
174 175 if (($values[$key]??'')==='') $values[$key]=getenv($env)?:'';
175 176 }
176 177 return $c=$values;
177 178 }
179 function gameConfig(): array {
180 static $g;
181 if ($g !== null) return $g;
182 $path=__DIR__.'/game-config.php';
183 $defaults=require $path;
184 if (!is_array($defaults)) throw new RuntimeException('lib/game-config.php must return an array.');
185 $overlay=config();
186 foreach ($defaults as $key=>$value) {
187 if (in_array($key,['base_url','client_id','client_secret'],true)) continue;
188 if (array_key_exists($key,$overlay) && $overlay[$key]!=='' && $overlay[$key]!==null) $defaults[$key]=$overlay[$key];
189 }
190 return $g=$defaults;
191 }
178 192 function baseUrl(): string {
179 193 if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
180 194 $base=rtrim(config()['base_url'],'/');
181 if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set MICROCHESS_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
195 if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set SYNHEX_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
182 196 return $base;
183 197 }
184 198 function assetVersion(): string {
@@ -189,7 +203,7 @@ function assetVersion(): string {
189 203 $hash=trim((string)file_get_contents($file));
190 204 if ($hash!=='' && preg_match('/^[0-9a-f]{7,64}$/i',$hash)) return $v=$hash;
191 205 }
192 $env=getenv('CI_COMMIT_SHA')?:getenv('MICROCHESS_ASSET_VERSION')?:'';
206 $env=getenv('CI_COMMIT_SHA')?:getenv('SYNHEX_ASSET_VERSION')?:'';
193 207 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i',trim($env))) return $v=trim($env);
194 208 $git=dirname(__DIR__,2).'/.git';
195 209 if (is_dir($git)) {
@@ -206,7 +220,7 @@ function assetUrl(string $path): string {
206 220 }
207 221 function authRequest(string $path,?array $form=null,?string $token=null): array {
208 222 $ch=curl_init('https://auth.timfalken.com'.$path);
209 $headers=['Accept: application/json','User-Agent: Microchess/1.0'];
223 $headers=['Accept: application/json','User-Agent: Synhex/1.0'];
210 224 if ($token) $headers[]='Authorization: Bearer '.$token;
211 225 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]);
212 226 if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]);
@@ -223,7 +237,7 @@ function loginUser(string $id,string $name): void {
223 237 }
224 238 // Generate the editable configuration on the first page request, including localhost.
225 239 config();
226 session_name('microchess_session');
240 session_name('synhex_session');
227 241 ini_set('session.use_strict_mode','1');
228 242 $sessionLifetime=86400;
229 243 $sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
@@ -262,21 +276,10 @@ function befriend(string $a,string $b): void {
262 276 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
263 277 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
264 278 }
265 // Two bytes per ply: source square, destination square and resulting piece (promotion included).
266 // Only the initial board is stored in full; no repeated position snapshots.
267 279 function saveReplay(int $result,string $white,array $s,string $skinWhite='White',string $skinBlack='Black'): void {
268 $history=$s['history'];
269 $packed=substr($history[0],0,21);
270 $pieces='.prnbqkPRNBQK';
271 for ($i=1;$i<count($history);$i++) {
272 $before=$history[$i-1];$after=$history[$i];$from=0;$to=0;
273 for ($j=0;$j<20;$j++) if ($before[$j]!==$after[$j]) {
274 if ($after[$j]==='.') $from=$j; else $to=$j;
275 }
276 $packed.=pack('n',($from*20+$to)*13+strpos($pieces,$after[$to]));
277 }
280 $payload=json_encode(['version'=>1,'state'=>$s],JSON_THROW_ON_ERROR);
278 281 $q=db()->prepare('INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) VALUES(?,?,?,?,?)');
279 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$packed,PDO::PARAM_LOB);$q->bindValue(4,$skinWhite);$q->bindValue(5,$skinBlack);$q->execute();
282 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$payload,PDO::PARAM_LOB);$q->bindValue(4,$skinWhite);$q->bindValue(5,$skinBlack);$q->execute();
280 283 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
281 284 }
282 285 function replayLink(int $id): string {
@@ -288,15 +291,9 @@ function replayPlayers(array $r): array {
288 291 return ['whiteName'=>profile($r['white'])['name'],'blackName'=>profile($black)['name']];
289 292 }
290 293 function replayPositions(string $packed): array {
291 $board=str_split(substr($packed,0,20));$turn=$packed[20];
292 $positions=[['board'=>$board,'turn'=>$turn,'ply'=>0,'last'=>null]];
293 for ($i=21;$i<strlen($packed);$i+=2) {
294 $code=unpack('n',substr($packed,$i,2))[1];$piece='.prnbqkPRNBQK'[$code%13];
295 $squares=intdiv($code,13);$from=intdiv($squares,20);$to=$squares%20;
296 $board[$from]='.';$board[$to]=$piece;$turn=$turn==='w'?'b':'w';
297 $positions[]=['board'=>$board,'turn'=>$turn,'ply'=>count($positions),'last'=>['from'=>$from,'to'=>$to]];
298 }
299 return $positions;
294 $data=json_decode($packed,true);
295 if (!is_array($data) || (int)($data['version']??0)!==1 || !isset($data['state'])) return [];
296 return SynhexMatch::replayFrames($data['state']);
300 297 }
301 298 function finishGame(array $g,?string $winner,string $reason,array $s): void {
302 299 $final=$s;$final['history']=[];
@@ -337,7 +334,7 @@ function matchPlayers(bool $force=false): void {
337 334 }
338 335 function startGame(string $a,string $b): int {
339 336 $white=random_int(0,1)?$a:$b;
340 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,$white,json_encode(Chess::initial()),time()]);
337 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,$white,json_encode(SynhexMatch::initial()),time()]);
341 338 $id=(int)db()->lastInsertId();
342 339 assignGamePieceSkins($id,$white,$white===$a?$b:$a);
343 340 pushGame($id);
@@ -351,11 +348,20 @@ function gameView(array $g,string $u): array {
351 348 $skins=gamePieceSkins($g);
352 349 $displayColor=$color==='w'?$skins['white']:$skins['black'];
353 350 $opponentDisplayColor=$color==='w'?$skins['black']:$skins['white'];
351 $cfg=$s?gameConfig():[];
352 $view=$s?SynhexMatch::clientView($s,$color,$cfg):null;
353 if ($view && in_array($g['status'],['ended','stopped'],true)) {
354 $view['units']=array_map(static fn($u)=>$u+['hologram'=>false,'known'=>true],$s['units']??[]);
355 $view['phase']='ended';
356 $view['timeline']=$s['timeline']??($s['history'][count($s['history']??[])-1]??null);
357 }
358 $yourTurn=$g['status']==='active' && $s && SynhexMatch::isYourTurn($s,$color);
359 $bar=$s?SynhexMatch::unitBar($s):['w'=>0,'b'=>0];
354 360 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,'displayColor'=>$displayColor,'opponentDisplayColor'=>$opponentDisplayColor,'pieceSkinWhite'=>$skins['white'],'pieceSkinBlack'=>$skins['black'],
355 361 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
356 362 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
357 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
358 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
363 'state'=>$view,'yourTurn'=>$yourTurn,'legal'=>[],
364 'check'=>false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
359 365 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
360 'claimable'=>$s?Chess::claimable($s):false,'version'=>(int)$g['version']];
366 'claimable'=>false,'strength'=>$bar,'version'=>(int)$g['version']];
361 367 }
@@ -1,7 +1,8 @@
1<?php
1<?php
2declare(strict_types=1);
2declare(strict_types=1);
3require_once __DIR__.'/Chess.php';
3require_once __DIR__.'/HexGrid.php';
4require_once __DIR__.'/MoveFeedback.php';
4require_once __DIR__.'/SynhexSim.php';
5require_once __DIR__.'/SynhexMatch.php';
5require_once __DIR__.'/Push.php';
6require_once __DIR__.'/Push.php';
6require_once __DIR__.'/PieceColors.php';
7require_once __DIR__.'/PieceColors.php';
7ini_set('display_errors','0');
8ini_set('display_errors','0');
@@ -15,7 +16,7 @@ header('Cache-Control: no-store');
15function db(): PDO {
16function db(): PDO {
16 static $db;
17 static $db;
17 if ($db) return $db;
18 if ($db) return $db;
18 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/microchess.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
19 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/synhex.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
19 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
20 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
20 $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
21 $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
21 CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
22 CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
@@ -161,7 +162,7 @@ function config(): array {
161 try {
162 try {
162 if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.');
163 if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.');
163 if (!file_exists($path)) {
164 if (!file_exists($path)) {
164 $template="<?php\n// Fill in these values on this server. Empty fields use environment variables.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
165 $template="<?php\n// Fill in OAuth values on this server. Empty fields use environment variables.\n// Game balance knobs live in lib/game-config.php; optional overrides of those keys may be added here.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
165 if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.');
166 if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.');
166 }
167 }
167 $values=require $path;
168 $values=require $path;
@@ -170,15 +171,28 @@ function config(): array {
170 flock($lock,LOCK_UN);
171 flock($lock,LOCK_UN);
171 fclose($lock);
172 fclose($lock);
172 }
173 }
173 foreach (['base_url'=>'MICROCHESS_BASE_URL','client_id'=>'MICROCHESS_CLIENT_ID','client_secret'=>'MICROCHESS_CLIENT_SECRET'] as $key=>$env) {
174 foreach (['base_url'=>'SYNHEX_BASE_URL','client_id'=>'SYNHEX_CLIENT_ID','client_secret'=>'SYNHEX_CLIENT_SECRET'] as $key=>$env) {
174 if (($values[$key]??'')==='') $values[$key]=getenv($env)?:'';
175 if (($values[$key]??'')==='') $values[$key]=getenv($env)?:'';
175 }
176 }
176 return $c=$values;
177 return $c=$values;
177}
178}
179function gameConfig(): array {
180 static $g;
181 if ($g !== null) return $g;
182 $path=__DIR__.'/game-config.php';
183 $defaults=require $path;
184 if (!is_array($defaults)) throw new RuntimeException('lib/game-config.php must return an array.');
185 $overlay=config();
186 foreach ($defaults as $key=>$value) {
187 if (in_array($key,['base_url','client_id','client_secret'],true)) continue;
188 if (array_key_exists($key,$overlay) && $overlay[$key]!=='' && $overlay[$key]!==null) $defaults[$key]=$overlay[$key];
189 }
190 return $g=$defaults;
191}
178function baseUrl(): string {
192function baseUrl(): string {
179 if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
193 if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
180 $base=rtrim(config()['base_url'],'/');
194 $base=rtrim(config()['base_url'],'/');
181 if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set MICROCHESS_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
195 if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set SYNHEX_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
182 return $base;
196 return $base;
183}
197}
184function assetVersion(): string {
198function assetVersion(): string {
@@ -189,7 +203,7 @@ function assetVersion(): string {
189 $hash=trim((string)file_get_contents($file));
203 $hash=trim((string)file_get_contents($file));
190 if ($hash!=='' && preg_match('/^[0-9a-f]{7,64}$/i',$hash)) return $v=$hash;
204 if ($hash!=='' && preg_match('/^[0-9a-f]{7,64}$/i',$hash)) return $v=$hash;
191 }
205 }
192 $env=getenv('CI_COMMIT_SHA')?:getenv('MICROCHESS_ASSET_VERSION')?:'';
206 $env=getenv('CI_COMMIT_SHA')?:getenv('SYNHEX_ASSET_VERSION')?:'';
193 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i',trim($env))) return $v=trim($env);
207 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i',trim($env))) return $v=trim($env);
194 $git=dirname(__DIR__,2).'/.git';
208 $git=dirname(__DIR__,2).'/.git';
195 if (is_dir($git)) {
209 if (is_dir($git)) {
@@ -206,7 +220,7 @@ function assetUrl(string $path): string {
206}
220}
207function authRequest(string $path,?array $form=null,?string $token=null): array {
221function authRequest(string $path,?array $form=null,?string $token=null): array {
208 $ch=curl_init('https://auth.timfalken.com'.$path);
222 $ch=curl_init('https://auth.timfalken.com'.$path);
209 $headers=['Accept: application/json','User-Agent: Microchess/1.0'];
223 $headers=['Accept: application/json','User-Agent: Synhex/1.0'];
210 if ($token) $headers[]='Authorization: Bearer '.$token;
224 if ($token) $headers[]='Authorization: Bearer '.$token;
211 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]);
225 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]);
212 if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]);
226 if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]);
@@ -223,7 +237,7 @@ function loginUser(string $id,string $name): void {
223}
237}
224// Generate the editable configuration on the first page request, including localhost.
238// Generate the editable configuration on the first page request, including localhost.
225config();
239config();
226session_name('microchess_session');
240session_name('synhex_session');
227ini_set('session.use_strict_mode','1');
241ini_set('session.use_strict_mode','1');
228$sessionLifetime=86400;
242$sessionLifetime=86400;
229$sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
243$sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
@@ -262,21 +276,10 @@ function befriend(string $a,string $b): void {
262 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
276 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
263 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
277 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
264}
278}
265// Two bytes per ply: source square, destination square and resulting piece (promotion included).
266// Only the initial board is stored in full; no repeated position snapshots.
267function saveReplay(int $result,string $white,array $s,string $skinWhite='White',string $skinBlack='Black'): void {
279function saveReplay(int $result,string $white,array $s,string $skinWhite='White',string $skinBlack='Black'): void {
268 $history=$s['history'];
280 $payload=json_encode(['version'=>1,'state'=>$s],JSON_THROW_ON_ERROR);
269 $packed=substr($history[0],0,21);
270 $pieces='.prnbqkPRNBQK';
271 for ($i=1;$i<count($history);$i++) {
272 $before=$history[$i-1];$after=$history[$i];$from=0;$to=0;
273 for ($j=0;$j<20;$j++) if ($before[$j]!==$after[$j]) {
274 if ($after[$j]==='.') $from=$j; else $to=$j;
275 }
276 $packed.=pack('n',($from*20+$to)*13+strpos($pieces,$after[$to]));
277 }
278 $q=db()->prepare('INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) VALUES(?,?,?,?,?)');
281 $q=db()->prepare('INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) VALUES(?,?,?,?,?)');
279 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$packed,PDO::PARAM_LOB);$q->bindValue(4,$skinWhite);$q->bindValue(5,$skinBlack);$q->execute();
282 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$payload,PDO::PARAM_LOB);$q->bindValue(4,$skinWhite);$q->bindValue(5,$skinBlack);$q->execute();
280 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
283 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
281}
284}
282function replayLink(int $id): string {
285function replayLink(int $id): string {
@@ -288,15 +291,9 @@ function replayPlayers(array $r): array {
288 return ['whiteName'=>profile($r['white'])['name'],'blackName'=>profile($black)['name']];
291 return ['whiteName'=>profile($r['white'])['name'],'blackName'=>profile($black)['name']];
289}
292}
290function replayPositions(string $packed): array {
293function replayPositions(string $packed): array {
291 $board=str_split(substr($packed,0,20));$turn=$packed[20];
294 $data=json_decode($packed,true);
292 $positions=[['board'=>$board,'turn'=>$turn,'ply'=>0,'last'=>null]];
295 if (!is_array($data) || (int)($data['version']??0)!==1 || !isset($data['state'])) return [];
293 for ($i=21;$i<strlen($packed);$i+=2) {
296 return SynhexMatch::replayFrames($data['state']);
294 $code=unpack('n',substr($packed,$i,2))[1];$piece='.prnbqkPRNBQK'[$code%13];
295 $squares=intdiv($code,13);$from=intdiv($squares,20);$to=$squares%20;
296 $board[$from]='.';$board[$to]=$piece;$turn=$turn==='w'?'b':'w';
297 $positions[]=['board'=>$board,'turn'=>$turn,'ply'=>count($positions),'last'=>['from'=>$from,'to'=>$to]];
298 }
299 return $positions;
300}
297}
301function finishGame(array $g,?string $winner,string $reason,array $s): void {
298function finishGame(array $g,?string $winner,string $reason,array $s): void {
302 $final=$s;$final['history']=[];
299 $final=$s;$final['history']=[];
@@ -337,7 +334,7 @@ function matchPlayers(bool $force=false): void {
337}
334}
338function startGame(string $a,string $b): int {
335function startGame(string $a,string $b): int {
339 $white=random_int(0,1)?$a:$b;
336 $white=random_int(0,1)?$a:$b;
340 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,$white,json_encode(Chess::initial()),time()]);
337 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,$white,json_encode(SynhexMatch::initial()),time()]);
341 $id=(int)db()->lastInsertId();
338 $id=(int)db()->lastInsertId();
342 assignGamePieceSkins($id,$white,$white===$a?$b:$a);
339 assignGamePieceSkins($id,$white,$white===$a?$b:$a);
343 pushGame($id);
340 pushGame($id);
@@ -351,11 +348,20 @@ function gameView(array $g,string $u): array {
351 $skins=gamePieceSkins($g);
348 $skins=gamePieceSkins($g);
352 $displayColor=$color==='w'?$skins['white']:$skins['black'];
349 $displayColor=$color==='w'?$skins['white']:$skins['black'];
353 $opponentDisplayColor=$color==='w'?$skins['black']:$skins['white'];
350 $opponentDisplayColor=$color==='w'?$skins['black']:$skins['white'];
351 $cfg=$s?gameConfig():[];
352 $view=$s?SynhexMatch::clientView($s,$color,$cfg):null;
353 if ($view && in_array($g['status'],['ended','stopped'],true)) {
354 $view['units']=array_map(static fn($u)=>$u+['hologram'=>false,'known'=>true],$s['units']??[]);
355 $view['phase']='ended';
356 $view['timeline']=$s['timeline']??($s['history'][count($s['history']??[])-1]??null);
357 }
358 $yourTurn=$g['status']==='active' && $s && SynhexMatch::isYourTurn($s,$color);
359 $bar=$s?SynhexMatch::unitBar($s):['w'=>0,'b'=>0];
354 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,'displayColor'=>$displayColor,'opponentDisplayColor'=>$opponentDisplayColor,'pieceSkinWhite'=>$skins['white'],'pieceSkinBlack'=>$skins['black'],
360 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,'displayColor'=>$displayColor,'opponentDisplayColor'=>$opponentDisplayColor,'pieceSkinWhite'=>$skins['white'],'pieceSkinBlack'=>$skins['black'],
355 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
361 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
356 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
362 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
357 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
363 'state'=>$view,'yourTurn'=>$yourTurn,'legal'=>[],
358 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
364 'check'=>false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
359 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
365 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
360 'claimable'=>$s?Chess::claimable($s):false,'version'=>(int)$g['version']];
366 'claimable'=>false,'strength'=>$bar,'version'=>(int)$g['version']];
361}
367}
web/lib/game-config.php added +78 −0
@@ -0,0 +1,78 @@
1 <?php
2 /**
3 * Synhex game balance and board tunables.
4 *
5 * OAuth secrets stay in the generated (gitignored) data/config.php.
6 * Keys here can be overridden by the same name in data/config.php.
7 *
8 * Board: odd-r offset coordinates, pointy-top hexes.
9 * Size 17 columns × 14 rows (238 hexes) — substantially larger than Microchess 4×5.
10 * Axial (q, r) is used internally: q = col - floor(row / 2), r = row.
11 */
12 return [
13 // --- Board ---
14 'grid_cols' => 17,
15 'grid_rows' => 14,
16 'hex_orientation' => 'pointy',
17 'hex_offset' => 'odd-r',
18 'wall_density' => 0.14,
19 'wall_clear_radius' => 2,
20 'wall_gen_attempts' => 24,
21
22 // --- Movement / time ---
23 'walk_range' => 5,
24 'act_duration_ms' => 3000,
25 'sim_tick_ms' => 50,
26
27 // --- Vision ---
28 // Forward hex direction + two adjacent directions, and hexes between them → 120° cone.
29 'vision_cone_half_deg' => 60,
30 'vision_range' => 18,
31 'see_enemies_at_match_start' => true,
32 'see_enemies_when_firing' => true,
33
34 // --- Combat ---
35 'base_accuracy' => 15,
36 'accuracy_cap' => 95,
37 'accuracy_bonus_shooter_stationary' => 8,
38 'accuracy_bonus_target_forward' => 12,
39 'accuracy_bonus_target_close' => 8,
40 'accuracy_bonus_shotgun_close_extra' => 8,
41 'accuracy_bonus_target_not_shooting_this' => 6,
42 'accuracy_bonus_still_previous_act' => 8,
43 'accuracy_bonus_same_or_no_target_previous_act' => 5,
44 'accuracy_bonus_friendly_focus_fire' => 10,
45 'accuracy_bonus_target_no_cover_wall' => 6,
46 'accuracy_bonus_target_stationary' => 8,
47 'accuracy_bonus_nobody_shooting_at_shooter' => 8,
48 'close_range_hexes' => 3,
49 'shot_range' => 18,
50 'friendly_fire' => true,
51
52 'weapon_pistol_rof_ms' => 1200,
53 'weapon_smg_rof_ms' => 350,
54 'weapon_shotgun_rof_ms' => 1100,
55 'weapon_shotgun_pellets' => 5,
56 'weapon_shotgun_spread' => 2,
57
58 // Strength shown on the tile bar (VIP is more valuable).
59 'unit_bar_vip' => 3,
60 'unit_bar_soldier' => 1,
61
62 // --- Spawns (odd-r col,row). White/west faces east (dir 0); Black/east faces west (dir 3). ---
63 // Directions: 0 E, 1 NE, 2 NW, 3 W, 4 SW, 5 SE.
64 'spawn' => [
65 'w' => [
66 ['id' => 'vip', 'role' => 'vip', 'weapon' => 'pistol', 'col' => 1, 'row' => 6, 'facing' => 0],
67 ['id' => 'smg-1', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 1, 'row' => 4, 'facing' => 0],
68 ['id' => 'smg-2', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 1, 'row' => 8, 'facing' => 0],
69 ['id' => 'shot', 'role' => 'soldier', 'weapon' => 'shotgun', 'col' => 2, 'row' => 6, 'facing' => 0],
70 ],
71 'b' => [
72 ['id' => 'vip', 'role' => 'vip', 'weapon' => 'pistol', 'col' => 15, 'row' => 6, 'facing' => 3],
73 ['id' => 'smg-1', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 15, 'row' => 4, 'facing' => 3],
74 ['id' => 'smg-2', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 15, 'row' => 8, 'facing' => 3],
75 ['id' => 'shot', 'role' => 'soldier', 'weapon' => 'shotgun', 'col' => 14, 'row' => 6, 'facing' => 3],
76 ],
77 ],
78 ];
@@ -0,0 +1,78 @@
1<?php
2/**
3 * Synhex game balance and board tunables.
4 *
5 * OAuth secrets stay in the generated (gitignored) data/config.php.
6 * Keys here can be overridden by the same name in data/config.php.
7 *
8 * Board: odd-r offset coordinates, pointy-top hexes.
9 * Size 17 columns × 14 rows (238 hexes) — substantially larger than Microchess 4×5.
10 * Axial (q, r) is used internally: q = col - floor(row / 2), r = row.
11 */
12return [
13 // --- Board ---
14 'grid_cols' => 17,
15 'grid_rows' => 14,
16 'hex_orientation' => 'pointy',
17 'hex_offset' => 'odd-r',
18 'wall_density' => 0.14,
19 'wall_clear_radius' => 2,
20 'wall_gen_attempts' => 24,
21
22 // --- Movement / time ---
23 'walk_range' => 5,
24 'act_duration_ms' => 3000,
25 'sim_tick_ms' => 50,
26
27 // --- Vision ---
28 // Forward hex direction + two adjacent directions, and hexes between them → 120° cone.
29 'vision_cone_half_deg' => 60,
30 'vision_range' => 18,
31 'see_enemies_at_match_start' => true,
32 'see_enemies_when_firing' => true,
33
34 // --- Combat ---
35 'base_accuracy' => 15,
36 'accuracy_cap' => 95,
37 'accuracy_bonus_shooter_stationary' => 8,
38 'accuracy_bonus_target_forward' => 12,
39 'accuracy_bonus_target_close' => 8,
40 'accuracy_bonus_shotgun_close_extra' => 8,
41 'accuracy_bonus_target_not_shooting_this' => 6,
42 'accuracy_bonus_still_previous_act' => 8,
43 'accuracy_bonus_same_or_no_target_previous_act' => 5,
44 'accuracy_bonus_friendly_focus_fire' => 10,
45 'accuracy_bonus_target_no_cover_wall' => 6,
46 'accuracy_bonus_target_stationary' => 8,
47 'accuracy_bonus_nobody_shooting_at_shooter' => 8,
48 'close_range_hexes' => 3,
49 'shot_range' => 18,
50 'friendly_fire' => true,
51
52 'weapon_pistol_rof_ms' => 1200,
53 'weapon_smg_rof_ms' => 350,
54 'weapon_shotgun_rof_ms' => 1100,
55 'weapon_shotgun_pellets' => 5,
56 'weapon_shotgun_spread' => 2,
57
58 // Strength shown on the tile bar (VIP is more valuable).
59 'unit_bar_vip' => 3,
60 'unit_bar_soldier' => 1,
61
62 // --- Spawns (odd-r col,row). White/west faces east (dir 0); Black/east faces west (dir 3). ---
63 // Directions: 0 E, 1 NE, 2 NW, 3 W, 4 SW, 5 SE.
64 'spawn' => [
65 'w' => [
66 ['id' => 'vip', 'role' => 'vip', 'weapon' => 'pistol', 'col' => 1, 'row' => 6, 'facing' => 0],
67 ['id' => 'smg-1', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 1, 'row' => 4, 'facing' => 0],
68 ['id' => 'smg-2', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 1, 'row' => 8, 'facing' => 0],
69 ['id' => 'shot', 'role' => 'soldier', 'weapon' => 'shotgun', 'col' => 2, 'row' => 6, 'facing' => 0],
70 ],
71 'b' => [
72 ['id' => 'vip', 'role' => 'vip', 'weapon' => 'pistol', 'col' => 15, 'row' => 6, 'facing' => 3],
73 ['id' => 'smg-1', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 15, 'row' => 4, 'facing' => 3],
74 ['id' => 'smg-2', 'role' => 'soldier', 'weapon' => 'smg', 'col' => 15, 'row' => 8, 'facing' => 3],
75 ['id' => 'shot', 'role' => 'soldier', 'weapon' => 'shotgun', 'col' => 14, 'row' => 6, 'facing' => 3],
76 ],
77 ],
78];
web/manifest.webmanifest +3 −3
@@ -1,8 +1,8 @@
1 1 {
2 2 "id": "./",
3 "name": "Microchess",
4 "short_name": "Microchess",
5 "description": "Small board. Big game. Play chess with friends, one move at a time.",
3 "name": "Synhex",
4 "short_name": "Synhex",
5 "description": "Simultaneous-turn hex tactics. Plan together. Fire together.",
6 6 "lang": "en",
7 7 "start_url": "./",
8 8 "scope": "./",
@@ -1,8 +1,8 @@
1{
1{
2 "id": "./",
2 "id": "./",
3 "name": "Microchess",
3 "name": "Synhex",
4 "short_name": "Microchess",
4 "short_name": "Synhex",
5 "description": "Small board. Big game. Play chess with friends, one move at a time.",
5 "description": "Simultaneous-turn hex tactics. Plan together. Fire together.",
6 "lang": "en",
6 "lang": "en",
7 "start_url": "./",
7 "start_url": "./",
8 "scope": "./",
8 "scope": "./",
web/sw.js +3 −3
@@ -9,13 +9,13 @@ self.addEventListener('push', event =>
9 9 const game = Number.isSafeInteger(data.game) && data.game > 0 ? data.game : null;
10 10 event.waitUntil((async () =>
11 11 {
12 // Skip OS notifications while the player is already looking at Microchess.
12 // Skip OS notifications while the player is already looking at Synhex.
13 13 const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
14 14 if (windows.some(client => client.visibilityState === 'visible')) return;
15 await self.registration.showNotification('Microchess', {
15 await self.registration.showNotification('Synhex', {
16 16 body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.',
17 17 icon: new URL('assets/app-icon-192.png', self.registration.scope).href,
18 tag: game ? `game-${game}` : 'microchess',
18 tag: game ? `game-${game}` : 'synhex',
19 19 data: { game }
20 20 });
21 21 })());
@@ -9,13 +9,13 @@ self.addEventListener('push', event =>
9 const game = Number.isSafeInteger(data.game) && data.game > 0 ? data.game : null;
9 const game = Number.isSafeInteger(data.game) && data.game > 0 ? data.game : null;
10 event.waitUntil((async () =>
10 event.waitUntil((async () =>
11 {
11 {
12 // Skip OS notifications while the player is already looking at Microchess.
12 // Skip OS notifications while the player is already looking at Synhex.
13 const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
13 const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
14 if (windows.some(client => client.visibilityState === 'visible')) return;
14 if (windows.some(client => client.visibilityState === 'visible')) return;
15 await self.registration.showNotification('Microchess', {
15 await self.registration.showNotification('Synhex', {
16 body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.',
16 body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.',
17 icon: new URL('assets/app-icon-192.png', self.registration.scope).href,
17 icon: new URL('assets/app-icon-192.png', self.registration.scope).href,
18 tag: game ? `game-${game}` : 'microchess',
18 tag: game ? `game-${game}` : 'synhex',
19 data: { game }
19 data: { game }
20 });
20 });
21 })());
21 })());
web/tests/browser.mjs +25 −124
@@ -115,125 +115,41 @@ try{
115 115 await a.locator('.notification-highlight').waitFor({state:'detached'});
116 116 const manifest=await (await fetch(`${base}/manifest.webmanifest`)).json();
117 117 assert.equal(manifest.start_url,'./','Manifest supports deployment in a subdirectory');
118 assert.equal(manifest.name,'Synhex','PWA is branded Synhex');
118 119 assert(await a.evaluate(async()=>!!(await navigator.serviceWorker.ready).active),'Service worker activates');
119 120 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
120 await white.locator(`[data-game="${id}"] [data-square="15"]`).click();
121 assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot');
122 await white.locator(`[data-game="${id}"] [data-square="11"]`).click();
123 const held=white.locator(`#your-games [data-game="${id}"]`);
124 await held.locator('[data-square="11"]:disabled').waitFor();
125 const heldAt=Date.now(),heldRect=await held.boundingBox();
126 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
127 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
128 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
129 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
130 await white.waitForTimeout(2200);
131 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
132 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
133 await white.evaluate(()=>renderGames());
134 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
135 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
136 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
137 await relocated.waitFor({state:'attached'});
138 assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating');
139 assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid');
140 await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));
141 await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor();
142 assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert');
143 // Actual pointer drag.
144 const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox();
145 const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox();
146 await black.mouse.move(from.x+from.width/2,from.y+from.height/2);await black.mouse.down();await black.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:8});await black.mouse.up();
147 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
148 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
149 // Real tactical evaluations, using board fixtures only in this disposable game database.
150 async function tacticalFixture(pieces){
151 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
152 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
153 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(position),String(id)]);
154 await white.evaluate(()=>refresh(true));
155 }
156 for(const [quality,pieces,reduced] of [
157 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
158 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
159 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
160 ]){
161 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
162 await tacticalFixture(pieces);
163 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
164 const started=Date.now();
165 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
166 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
167 await pulse.waitFor({state:'attached'});
168 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
169 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
170 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
171 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
172 if(reduced){
173 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
174 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
175 }
176 else{
177 await white.evaluate(()=>renderGames());
178 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
179 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
180 await white.waitForTimeout(250);
181 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
182 }
183 await pulse.waitFor({state:'detached'});
184 const expected=quality==='good'?1:9/14;
185 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
186 await black.evaluate(()=>refresh(true));
187 assert.equal(await black.locator(`[data-game="${id}"] .material-bar`).getAttribute('data-share'),await bar.getAttribute('data-share'),'Polling uses the same White-left ratio for Black');
188 await white.evaluate(()=>renderGames());
189 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
190 }
191 await white.emulateMedia({reducedMotion:'no-preference'});
192 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
193 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
121 await white.locator(`[data-game="${id}"] .hex-board`).waitFor();
122 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting strength gives 50/50');
123 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Strength orientation is the same for Black');
124 await white.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
125 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
126 assert.equal(await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).count(),1,'Opponent can still lock after the first plan');
127 await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
128 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
129 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
130 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
131 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
194 132 await white.evaluate(() => {
195 133 window.savedFlights = 0;
196 134 const original = Element.prototype.animate;
197 135 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
198 136 });
199 // Fixture a legal promotion position in the isolated database.
200 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
201 fixture.history=[fixture.board.join('')+'w'];
202 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(fixture),String(id)]);
203 await white.waitForTimeout(3000);
204 await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click();
205 assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options');
206 await white.locator('[data-promotion="n"]').click();
207 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
208 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
137 await white.locator(`[data-game="${id}"] [data-game-action="options"]`).click();
138 await white.getByRole('button',{name:'Resign…'}).click();
139 await white.getByRole('button',{name:'Resign',exact:true}).click();
140 await white.getByRole('heading',{name:/You won|You lost|A game well matched/}).waitFor();
209 141 for(const page of [white,black]){
210 142 await page.locator('.end-content').waitFor();
211 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
212 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
213 await page.mouse.move(0,0);
214 await page.waitForTimeout(850);
215 assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent');
216 await page.locator('.end-content').hover();await page.waitForTimeout(850);
217 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
143 assert.equal(await page.locator('.ended-board .hex-board').count(),1,'Final hex board remains visible for both players');
218 144 }
219 assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once');
220 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),1,'Finished game stays in Your Turn');
221 assert.equal(await black.locator(`#your-games [data-game="${id}"]`).count(),1,'Opponent finished game also stays in Your Turn');
222 145 await white.locator('#history-button').click();
223 146 await white.locator('.history-entry').waitFor();
224 147 await white.locator('.history-entry').first().click();
225 148 await white.locator('#replay-card .board').waitFor();
226 assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion');
227 149 assert.equal(await white.locator('.replay-controls button').count(),5,'Replay has start, step, play, step and end controls');
228 150 await white.locator('[data-replay-control="end"]').click();
229 assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion');
230 151 await white.locator('[data-replay-control="start"]').click();
231 assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Jump to start returns to beginning');
232 await white.locator('[data-replay-control="play"]').click();
233 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Pause','Play becomes pause');
234 await white.waitForTimeout(600);
235 assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end');
236 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Play','Autoplay stops at end');
152 assert.match(await white.locator('#replay-progress').innerText(),/^0 \//,'Jump to start returns to beginning');
237 153 assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar');
238 154 assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player');
239 155 assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player');
@@ -247,7 +163,7 @@ try{
247 163 await guest.locator('#replay-card .board').waitFor();
248 164 assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players');
249 165 assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation');
250 assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Microchess ↗','Public replay links to the home page');
166 assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Synhex ↗','Public replay links to the home page');
251 167 assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI');
252 168 await guest.keyboard.press('Escape');
253 169 await guest.locator('#replay-card .board').waitFor();
@@ -258,9 +174,6 @@ try{
258 174 await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')});
259 175 await guest.reload();
260 176 await guest.locator('#replay-card .board').waitFor();
261
262 await guest.locator('[data-replay-control="end"]').click();
263 assert.match(await guest.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Shared replay plays the same promotion');
264 177 await guestContext.close();
265 178 await black.goto(replayUrl);
266 179 await black.locator('#replay-card .board').waitFor();
@@ -271,7 +184,6 @@ try{
271 184 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
272 185 await white.locator('#modal-close').click();
273 186 await white.evaluate(()=>refresh(true));
274 assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat');
275 187 await white.getByRole('button',{name:'Rematch',exact:true}).click();
276 188 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
277 189 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),0,'Requested rematch leaves Your Turn');
@@ -284,14 +196,14 @@ try{
284 196 for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});}
285 197 await a.reload();await a.locator('.game-card').nth(3).waitFor();
286 198 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
287 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
199 assert(await a.locator('.hex-board image').count()>0,'Hex units render');
288 200 await a.setViewportSize({width:1440,height:640});
289 201 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
290 202 const sidebar=await a.locator('#sidebar').boundingBox();
291 203 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
292 204 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
293 205 const staleId=(await state(a)).games[0].id;
294 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/microchess.sqlite'),String(staleId)]);
206 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/synhex.sqlite'),String(staleId)]);
295 207 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
296 208 await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
297 209 await a.getByRole('button',{name:'Cancel',exact:true}).click();
@@ -320,20 +232,9 @@ try{
320 232 const owner=sa.games.some(g=>g.yourTurn)?a:b;
321 233 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
322 234 const touch=await mobileContext.newPage();await touch.goto(base);
323 const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0];
324 const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`);
325 await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox();
326 const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox();
327 const cdp=await mobileContext.newCDPSession(touch);
328 await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]});
329 for(let i=1;i<=8;i++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:fb.x+fb.width/2+(tb.x-fb.x)*i/8,y:fb.y+fb.height/2+(tb.y-fb.y)*i/8}]});
330 await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
331 await touch.waitForTimeout(500);
332 assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved');
333 assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place');
334 const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`);
335 await mobileWaiting.waitFor({state:'attached'});
336 assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');
235 const tg=(await state(touch)).games.find(g=>g.yourTurn);
236 await touch.locator(`[data-game="${tg.id}"] [data-game-action="commit"]`).click();
237 await touch.locator(`#waiting-games [data-game="${tg.id}"]`).waitFor();
337 238 await mobileContext.close();
338 239 // New game offers matchmaking below the link, with persistent cancellation.
339 240 await a.setViewportSize({width:1440,height:1080});
@@ -392,7 +293,7 @@ try{
392 293 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
393 294 await a.locator('#modal-close').click();
394 295 assert.deepEqual(errors,[],'No browser errors');
395 console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');
296 console.log('Browser: friendship, challenge, hex plan/playback, rematch, desktop and mobile checks passed.');
396 297 }finally{
397 298 await browser?.close();if(server.exitCode===null && server.signalCode===null){const exited=new Promise(r=>server.once('exit',r));server.kill();await exited;}await rm(root,{recursive:true,force:true});
398 299 }
@@ -115,125 +115,41 @@ try{
115 await a.locator('.notification-highlight').waitFor({state:'detached'});
115 await a.locator('.notification-highlight').waitFor({state:'detached'});
116 const manifest=await (await fetch(`${base}/manifest.webmanifest`)).json();
116 const manifest=await (await fetch(`${base}/manifest.webmanifest`)).json();
117 assert.equal(manifest.start_url,'./','Manifest supports deployment in a subdirectory');
117 assert.equal(manifest.start_url,'./','Manifest supports deployment in a subdirectory');
118 assert.equal(manifest.name,'Synhex','PWA is branded Synhex');
118 assert(await a.evaluate(async()=>!!(await navigator.serviceWorker.ready).active),'Service worker activates');
119 assert(await a.evaluate(async()=>!!(await navigator.serviceWorker.ready).active),'Service worker activates');
119 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
120 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
120 await white.locator(`[data-game="${id}"] [data-square="15"]`).click();
121 await white.locator(`[data-game="${id}"] .hex-board`).waitFor();
121 assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot');
122 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting strength gives 50/50');
122 await white.locator(`[data-game="${id}"] [data-square="11"]`).click();
123 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Strength orientation is the same for Black');
123 const held=white.locator(`#your-games [data-game="${id}"]`);
124 await white.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
124 await held.locator('[data-square="11"]:disabled').waitFor();
125 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
125 const heldAt=Date.now(),heldRect=await held.boundingBox();
126 assert.equal(await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).count(),1,'Opponent can still lock after the first plan');
126 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
127 await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
127 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
128 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
128 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
129 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
129 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
130 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
130 await white.waitForTimeout(2200);
131 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
131 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
132 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
133 await white.evaluate(()=>renderGames());
134 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
135 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
136 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
137 await relocated.waitFor({state:'attached'});
138 assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating');
139 assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid');
140 await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));
141 await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor();
142 assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert');
143 // Actual pointer drag.
144 const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox();
145 const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox();
146 await black.mouse.move(from.x+from.width/2,from.y+from.height/2);await black.mouse.down();await black.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:8});await black.mouse.up();
147 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
148 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
149 // Real tactical evaluations, using board fixtures only in this disposable game database.
150 async function tacticalFixture(pieces){
151 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
152 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
153 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(position),String(id)]);
154 await white.evaluate(()=>refresh(true));
155 }
156 for(const [quality,pieces,reduced] of [
157 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
158 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
159 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
160 ]){
161 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
162 await tacticalFixture(pieces);
163 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
164 const started=Date.now();
165 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
166 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
167 await pulse.waitFor({state:'attached'});
168 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
169 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
170 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
171 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
172 if(reduced){
173 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
174 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
175 }
176 else{
177 await white.evaluate(()=>renderGames());
178 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
179 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
180 await white.waitForTimeout(250);
181 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
182 }
183 await pulse.waitFor({state:'detached'});
184 const expected=quality==='good'?1:9/14;
185 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
186 await black.evaluate(()=>refresh(true));
187 assert.equal(await black.locator(`[data-game="${id}"] .material-bar`).getAttribute('data-share'),await bar.getAttribute('data-share'),'Polling uses the same White-left ratio for Black');
188 await white.evaluate(()=>renderGames());
189 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
190 }
191 await white.emulateMedia({reducedMotion:'no-preference'});
192 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
193 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
194 await white.evaluate(() => {
132 await white.evaluate(() => {
195 window.savedFlights = 0;
133 window.savedFlights = 0;
196 const original = Element.prototype.animate;
134 const original = Element.prototype.animate;
197 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
135 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
198 });
136 });
199 // Fixture a legal promotion position in the isolated database.
137 await white.locator(`[data-game="${id}"] [data-game-action="options"]`).click();
200 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
138 await white.getByRole('button',{name:'Resign…'}).click();
201 fixture.history=[fixture.board.join('')+'w'];
139 await white.getByRole('button',{name:'Resign',exact:true}).click();
202 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(fixture),String(id)]);
140 await white.getByRole('heading',{name:/You won|You lost|A game well matched/}).waitFor();
203 await white.waitForTimeout(3000);
204 await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click();
205 assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options');
206 await white.locator('[data-promotion="n"]').click();
207 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
208 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
209 for(const page of [white,black]){
141 for(const page of [white,black]){
210 await page.locator('.end-content').waitFor();
142 await page.locator('.end-content').waitFor();
211 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
143 assert.equal(await page.locator('.ended-board .hex-board').count(),1,'Final hex board remains visible for both players');
212 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
213 await page.mouse.move(0,0);
214 await page.waitForTimeout(850);
215 assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent');
216 await page.locator('.end-content').hover();await page.waitForTimeout(850);
217 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
218 }
144 }
219 assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once');
220 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),1,'Finished game stays in Your Turn');
221 assert.equal(await black.locator(`#your-games [data-game="${id}"]`).count(),1,'Opponent finished game also stays in Your Turn');
222 await white.locator('#history-button').click();
145 await white.locator('#history-button').click();
223 await white.locator('.history-entry').waitFor();
146 await white.locator('.history-entry').waitFor();
224 await white.locator('.history-entry').first().click();
147 await white.locator('.history-entry').first().click();
225 await white.locator('#replay-card .board').waitFor();
148 await white.locator('#replay-card .board').waitFor();
226 assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion');
227 assert.equal(await white.locator('.replay-controls button').count(),5,'Replay has start, step, play, step and end controls');
149 assert.equal(await white.locator('.replay-controls button').count(),5,'Replay has start, step, play, step and end controls');
228 await white.locator('[data-replay-control="end"]').click();
150 await white.locator('[data-replay-control="end"]').click();
229 assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion');
230 await white.locator('[data-replay-control="start"]').click();
151 await white.locator('[data-replay-control="start"]').click();
231 assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Jump to start returns to beginning');
152 assert.match(await white.locator('#replay-progress').innerText(),/^0 \//,'Jump to start returns to beginning');
232 await white.locator('[data-replay-control="play"]').click();
233 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Pause','Play becomes pause');
234 await white.waitForTimeout(600);
235 assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end');
236 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Play','Autoplay stops at end');
237 assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar');
153 assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar');
238 assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player');
154 assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player');
239 assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player');
155 assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player');
@@ -247,7 +163,7 @@ try{
247 await guest.locator('#replay-card .board').waitFor();
163 await guest.locator('#replay-card .board').waitFor();
248 assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players');
164 assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players');
249 assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation');
165 assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation');
250 assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Microchess ↗','Public replay links to the home page');
166 assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Synhex ↗','Public replay links to the home page');
251 assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI');
167 assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI');
252 await guest.keyboard.press('Escape');
168 await guest.keyboard.press('Escape');
253 await guest.locator('#replay-card .board').waitFor();
169 await guest.locator('#replay-card .board').waitFor();
@@ -258,9 +174,6 @@ try{
258 await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')});
174 await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')});
259 await guest.reload();
175 await guest.reload();
260 await guest.locator('#replay-card .board').waitFor();
176 await guest.locator('#replay-card .board').waitFor();
261
262 await guest.locator('[data-replay-control="end"]').click();
263 assert.match(await guest.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Shared replay plays the same promotion');
264 await guestContext.close();
177 await guestContext.close();
265 await black.goto(replayUrl);
178 await black.goto(replayUrl);
266 await black.locator('#replay-card .board').waitFor();
179 await black.locator('#replay-card .board').waitFor();
@@ -271,7 +184,6 @@ try{
271 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
184 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
272 await white.locator('#modal-close').click();
185 await white.locator('#modal-close').click();
273 await white.evaluate(()=>refresh(true));
186 await white.evaluate(()=>refresh(true));
274 assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat');
275 await white.getByRole('button',{name:'Rematch',exact:true}).click();
187 await white.getByRole('button',{name:'Rematch',exact:true}).click();
276 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
188 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
277 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),0,'Requested rematch leaves Your Turn');
189 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),0,'Requested rematch leaves Your Turn');
@@ -284,14 +196,14 @@ try{
284 for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});}
196 for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});}
285 await a.reload();await a.locator('.game-card').nth(3).waitFor();
197 await a.reload();await a.locator('.game-card').nth(3).waitFor();
286 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
198 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
287 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
199 assert(await a.locator('.hex-board image').count()>0,'Hex units render');
288 await a.setViewportSize({width:1440,height:640});
200 await a.setViewportSize({width:1440,height:640});
289 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
201 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
290 const sidebar=await a.locator('#sidebar').boundingBox();
202 const sidebar=await a.locator('#sidebar').boundingBox();
291 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
203 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
292 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
204 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
293 const staleId=(await state(a)).games[0].id;
205 const staleId=(await state(a)).games[0].id;
294 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/microchess.sqlite'),String(staleId)]);
206 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/synhex.sqlite'),String(staleId)]);
295 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
207 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
296 await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
208 await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
297 await a.getByRole('button',{name:'Cancel',exact:true}).click();
209 await a.getByRole('button',{name:'Cancel',exact:true}).click();
@@ -320,20 +232,9 @@ try{
320 const owner=sa.games.some(g=>g.yourTurn)?a:b;
232 const owner=sa.games.some(g=>g.yourTurn)?a:b;
321 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
233 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
322 const touch=await mobileContext.newPage();await touch.goto(base);
234 const touch=await mobileContext.newPage();await touch.goto(base);
323 const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0];
235 const tg=(await state(touch)).games.find(g=>g.yourTurn);
324 const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`);
236 await touch.locator(`[data-game="${tg.id}"] [data-game-action="commit"]`).click();
325 await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox();
237 await touch.locator(`#waiting-games [data-game="${tg.id}"]`).waitFor();
326 const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox();
327 const cdp=await mobileContext.newCDPSession(touch);
328 await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]});
329 for(let i=1;i<=8;i++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:fb.x+fb.width/2+(tb.x-fb.x)*i/8,y:fb.y+fb.height/2+(tb.y-fb.y)*i/8}]});
330 await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
331 await touch.waitForTimeout(500);
332 assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved');
333 assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place');
334 const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`);
335 await mobileWaiting.waitFor({state:'attached'});
336 assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');
337 await mobileContext.close();
238 await mobileContext.close();
338 // New game offers matchmaking below the link, with persistent cancellation.
239 // New game offers matchmaking below the link, with persistent cancellation.
339 await a.setViewportSize({width:1440,height:1080});
240 await a.setViewportSize({width:1440,height:1080});
@@ -392,7 +293,7 @@ try{
392 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
293 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
393 await a.locator('#modal-close').click();
294 await a.locator('#modal-close').click();
394 assert.deepEqual(errors,[],'No browser errors');
295 assert.deepEqual(errors,[],'No browser errors');
395 console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');
296 console.log('Browser: friendship, challenge, hex plan/playback, rematch, desktop and mobile checks passed.');
396}finally{
297}finally{
397 await browser?.close();if(server.exitCode===null && server.signalCode===null){const exited=new Promise(r=>server.once('exit',r));server.kill();await exited;}await rm(root,{recursive:true,force:true});
298 await browser?.close();if(server.exitCode===null && server.signalCode===null){const exited=new Promise(r=>server.once('exit',r));server.kill();await exited;}await rm(root,{recursive:true,force:true});
398}
299}
web/tests/chess.php deleted +0 −52
@@ -1,52 +0,0 @@
1 <?php
2 declare(strict_types=1);
3 require dirname(__DIR__).'/lib/Chess.php';
4 $checks=0;
5 function check(bool $condition,string $label): void {global $checks;$checks++;if(!$condition)throw new RuntimeException($label);}
6 function position(array $pieces,string $turn='w'): array {$s=Chess::initial();$s['board']=array_fill(0,20,'.');foreach($pieces as $sq=>$p){$i=(5-(int)$sq[1])*4+ord($sq[0])-97;$s['board'][$i]=$p;}$s['turn']=$turn;$s['history']=[Chess::key($s)];return $s;}
7 function sq(string $s): int {return (5-(int)$s[1])*4+ord($s[0])-97;}
8 function has(array $s,string $from,string $to,?string $p=null): bool {return in_array(['from'=>sq($from),'to'=>sq($to),'promotion'=>$p],Chess::legal($s),true);}
9 function rejects(callable $fn,string $label): void {try{$fn();}catch(DomainException){check(true,$label);return;}check(false,$label);}
10 $s=Chess::initial();
11 check(count($s['board'])===20,'20 squares');check($s['board'][15]==='P'&&$s['board'][4]==='p','Pawn start squares');
12 check(!Chess::check($s),'Initial king safe');check(Chess::result($s)===null,'Initial position playable');
13 check(has($s,'d2','d3'),'Single pawn step');check(!has($s,'d2','d4'),'No double step');
14 check(!has($s,'a1','a5'),'Rook cannot pass pawn');
15 check(has($s,'c1','b3'),'Knight jumps');
16 $s=position(['d1'=>'K','a5'=>'k','b2'=>'P','a3'=>'n','c3'=>'b']);
17 check(has($s,'b2','a3')&&has($s,'b2','c3'),'Pawn captures diagonally');
18 check(!has($s,'b2','a2')&&!has($s,'b2','b1'),'Pawn cannot move sideways/backwards');
19 $s=position(['a1'=>'K','d5'=>'k','b4'=>'P']);
20 foreach(['q','r','b','n']as$p){check(has($s,'b4','b5',$p),'Promotion '.$p);$next=Chess::move($s,sq('b4'),sq('b5'),$p);check($next['board'][sq('b5')]===strtoupper($p),'Promoted piece '.$p);}
21 rejects(fn()=>Chess::move($s,sq('b4'),sq('b5')),'Promotion required');
22 rejects(fn()=>Chess::move($s,sq('b4'),sq('b5'),'k'),'Cannot promote to king');
23 $s=position(['a1'=>'K','d5'=>'k','b2'=>'p'],'b');check(has($s,'b2','b1','q'),'Black promotion');
24 $s=position(['a1'=>'K','a2'=>'R','a5'=>'r','d5'=>'k']);
25 check(!has($s,'a2','b2'),'Pinned rook cannot expose king');check(has($s,'a2','a5'),'Pinned rook can capture attacker');
26 $s=position(['a1'=>'K','c2'=>'k']);check(!has($s,'a1','b1')&&!has($s,'a1','b2'),'Kings cannot touch');
27 $s=position(['a1'=>'K','d5'=>'k','c2'=>'p']);check(!has($s,'a1','b1'),'King cannot enter pawn attack');
28 $s=position(['a5'=>'k','b4'=>'Q','c3'=>'K'],'b');check(Chess::result($s)===['winner'=>'w','reason'=>'Checkmate'],'Checkmate');
29 $s=position(['a5'=>'k','c4'=>'Q','c3'=>'K'],'b');check(Chess::result($s)===['winner'=>null,'reason'=>'Stalemate'],'Stalemate');
30 foreach([['a1'=>'K','d5'=>'k'],['a1'=>'K','d5'=>'k','b2'=>'B'],['a1'=>'K','d5'=>'k','b2'=>'N'],['a1'=>'K','d5'=>'k','b2'=>'B','c3'=>'b']] as $pieces)check(Chess::dead(position($pieces)),'Insufficient mating material');
31 check(!Chess::dead(position(['a1'=>'K','d5'=>'k','b2'=>'B','b3'=>'b'])),'Opposite-color bishops not automatically dead');
32 check(!Chess::dead(position(['a1'=>'K','d5'=>'k','b2'=>'N','b3'=>'N'])),'Two knights not automatically dead');
33 $s=Chess::initial();$s['halfmove']=100;check(Chess::claimable($s),'50 moves claimable');check(Chess::result($s)===null,'50 moves not automatic');
34 $s['halfmove']=150;check(Chess::result($s)['reason']==='75-move rule','75 moves automatic');
35 $s=Chess::initial();$s['history']=array_fill(0,3,Chess::key($s));check(Chess::claimable($s),'Threefold claimable');check(Chess::result($s)===null,'Threefold not automatic');
36 $s['history']=array_fill(0,5,Chess::key($s));check(Chess::result($s)['reason']==='Fivefold repetition','Fivefold automatic');
37 $s=position(['a5'=>'k','b4'=>'Q','c3'=>'K'],'b');$s['halfmove']=150;check(Chess::result($s)['reason']==='Checkmate','Mate overrides 75 moves');
38 $s=Chess::initial();$s['halfmove']=99;$s=Chess::move($s,15,11);check($s['halfmove']===0,'Pawn resets halfmove');
39 rejects(fn()=>Chess::move(Chess::initial(),4,8),'Cannot move opponent piece');
40 // Exercise complete random games: no legal move may leave its own king in check.
41 mt_srand(24);
42 for($game=0;$game<15;$game++){
43 $s=Chess::initial();
44 for($ply=0;$ply<120;$ply++){
45 if(Chess::result($s))break;
46 $moves=Chess::legal($s);$m=$moves[mt_rand(0,count($moves)-1)];$color=$s['turn'];
47 $s=Chess::move($s,$m['from'],$m['to'],$m['promotion']);
48 check(!Chess::check($s,$color),'Legal move protects own king');
49 check(count(array_filter($s['board'],fn($p)=>strtolower($p)==='k'))===2,'Kings never captured');
50 }
51 }
52 echo "Chess: $checks assertions passed.\n";
@@ -1,52 +0,0 @@
1<?php
2declare(strict_types=1);
3require dirname(__DIR__).'/lib/Chess.php';
4$checks=0;
5function check(bool $condition,string $label): void {global $checks;$checks++;if(!$condition)throw new RuntimeException($label);}
6function position(array $pieces,string $turn='w'): array {$s=Chess::initial();$s['board']=array_fill(0,20,'.');foreach($pieces as $sq=>$p){$i=(5-(int)$sq[1])*4+ord($sq[0])-97;$s['board'][$i]=$p;}$s['turn']=$turn;$s['history']=[Chess::key($s)];return $s;}
7function sq(string $s): int {return (5-(int)$s[1])*4+ord($s[0])-97;}
8function has(array $s,string $from,string $to,?string $p=null): bool {return in_array(['from'=>sq($from),'to'=>sq($to),'promotion'=>$p],Chess::legal($s),true);}
9function rejects(callable $fn,string $label): void {try{$fn();}catch(DomainException){check(true,$label);return;}check(false,$label);}
10$s=Chess::initial();
11check(count($s['board'])===20,'20 squares');check($s['board'][15]==='P'&&$s['board'][4]==='p','Pawn start squares');
12check(!Chess::check($s),'Initial king safe');check(Chess::result($s)===null,'Initial position playable');
13check(has($s,'d2','d3'),'Single pawn step');check(!has($s,'d2','d4'),'No double step');
14check(!has($s,'a1','a5'),'Rook cannot pass pawn');
15check(has($s,'c1','b3'),'Knight jumps');
16$s=position(['d1'=>'K','a5'=>'k','b2'=>'P','a3'=>'n','c3'=>'b']);
17check(has($s,'b2','a3')&&has($s,'b2','c3'),'Pawn captures diagonally');
18check(!has($s,'b2','a2')&&!has($s,'b2','b1'),'Pawn cannot move sideways/backwards');
19$s=position(['a1'=>'K','d5'=>'k','b4'=>'P']);
20foreach(['q','r','b','n']as$p){check(has($s,'b4','b5',$p),'Promotion '.$p);$next=Chess::move($s,sq('b4'),sq('b5'),$p);check($next['board'][sq('b5')]===strtoupper($p),'Promoted piece '.$p);}
21rejects(fn()=>Chess::move($s,sq('b4'),sq('b5')),'Promotion required');
22rejects(fn()=>Chess::move($s,sq('b4'),sq('b5'),'k'),'Cannot promote to king');
23$s=position(['a1'=>'K','d5'=>'k','b2'=>'p'],'b');check(has($s,'b2','b1','q'),'Black promotion');
24$s=position(['a1'=>'K','a2'=>'R','a5'=>'r','d5'=>'k']);
25check(!has($s,'a2','b2'),'Pinned rook cannot expose king');check(has($s,'a2','a5'),'Pinned rook can capture attacker');
26$s=position(['a1'=>'K','c2'=>'k']);check(!has($s,'a1','b1')&&!has($s,'a1','b2'),'Kings cannot touch');
27$s=position(['a1'=>'K','d5'=>'k','c2'=>'p']);check(!has($s,'a1','b1'),'King cannot enter pawn attack');
28$s=position(['a5'=>'k','b4'=>'Q','c3'=>'K'],'b');check(Chess::result($s)===['winner'=>'w','reason'=>'Checkmate'],'Checkmate');
29$s=position(['a5'=>'k','c4'=>'Q','c3'=>'K'],'b');check(Chess::result($s)===['winner'=>null,'reason'=>'Stalemate'],'Stalemate');
30foreach([['a1'=>'K','d5'=>'k'],['a1'=>'K','d5'=>'k','b2'=>'B'],['a1'=>'K','d5'=>'k','b2'=>'N'],['a1'=>'K','d5'=>'k','b2'=>'B','c3'=>'b']] as $pieces)check(Chess::dead(position($pieces)),'Insufficient mating material');
31check(!Chess::dead(position(['a1'=>'K','d5'=>'k','b2'=>'B','b3'=>'b'])),'Opposite-color bishops not automatically dead');
32check(!Chess::dead(position(['a1'=>'K','d5'=>'k','b2'=>'N','b3'=>'N'])),'Two knights not automatically dead');
33$s=Chess::initial();$s['halfmove']=100;check(Chess::claimable($s),'50 moves claimable');check(Chess::result($s)===null,'50 moves not automatic');
34$s['halfmove']=150;check(Chess::result($s)['reason']==='75-move rule','75 moves automatic');
35$s=Chess::initial();$s['history']=array_fill(0,3,Chess::key($s));check(Chess::claimable($s),'Threefold claimable');check(Chess::result($s)===null,'Threefold not automatic');
36$s['history']=array_fill(0,5,Chess::key($s));check(Chess::result($s)['reason']==='Fivefold repetition','Fivefold automatic');
37$s=position(['a5'=>'k','b4'=>'Q','c3'=>'K'],'b');$s['halfmove']=150;check(Chess::result($s)['reason']==='Checkmate','Mate overrides 75 moves');
38$s=Chess::initial();$s['halfmove']=99;$s=Chess::move($s,15,11);check($s['halfmove']===0,'Pawn resets halfmove');
39rejects(fn()=>Chess::move(Chess::initial(),4,8),'Cannot move opponent piece');
40// Exercise complete random games: no legal move may leave its own king in check.
41mt_srand(24);
42for($game=0;$game<15;$game++){
43 $s=Chess::initial();
44 for($ply=0;$ply<120;$ply++){
45 if(Chess::result($s))break;
46 $moves=Chess::legal($s);$m=$moves[mt_rand(0,count($moves)-1)];$color=$s['turn'];
47 $s=Chess::move($s,$m['from'],$m['to'],$m['promotion']);
48 check(!Chess::check($s,$color),'Legal move protects own king');
49 check(count(array_filter($s['board'],fn($p)=>strtolower($p)==='k'))===2,'Kings never captured');
50 }
51}
52echo "Chess: $checks assertions passed.\n";
web/tests/feedback.php deleted +0 −47
@@ -1,47 +0,0 @@
1 <?php
2 declare(strict_types=1);
3 require dirname(__DIR__).'/lib/MoveFeedback.php';
4 $checks=0;
5 function verify(bool $ok,string $label): void {global $checks;$checks++;if(!$ok)throw new RuntimeException($label);}
6 function setup(array $pieces,string $turn='w'): array {
7 $s=Chess::initial();$s['board']=array_fill(0,20,'.');foreach($pieces as $i=>$p)$s['board'][$i]=$p;
8 $s['turn']=$turn;$s['history']=[Chess::key($s)];return $s;
9 }
10 $cases=[
11 'quiet opening'=>[Chess::initial(),15,11,null,null],
12 'free queen'=>[setup([19=>'K',3=>'k',12=>'R',8=>'q']),12,8,null,'good'],
13 'poisoned pawn'=>[setup([19=>'K',1=>'k',12=>'Q',8=>'p',0=>'r']),12,8,null,'poor'],
14 'equal rook exchange'=>[setup([19=>'K',3=>'k',12=>'R',8=>'r',0=>'r']),12,8,null,null],
15 'checkmate'=>[setup([10=>'K',0=>'k',6=>'Q']),6,5,null,'good'],
16 'allows mate in one'=>[setup([16=>'K',10=>'k',14=>'q',3=>'R']),3,7,null,'poor'],
17 'promotion'=>[setup([16=>'K',3=>'k',5=>'P']),5,1,'q','good'],
18 'underpromotion draw'=>[setup([16=>'K',3=>'k',5=>'P']),5,1,'n',null],
19 ];
20 foreach($cases as $name=>[$s,$from,$to,$promotion,$quality]){
21 verify(!Chess::check($s,Chess::opposite($s['turn'])),"Legal fixture: $name");
22 $next=Chess::move($s,$from,$to,$promotion);$result=(new MoveFeedback())->rate($s,$next);
23 echo "$name: ".json_encode($result)."\n";
24 verify($result['quality']===$quality,"$name quality");
25 verify($result['elapsed_ms']<500,"$name stays comfortably inside feedback window");
26 verify(Chess::afterLegal($s,$next['last'])===$next,"Shared transition: $name");
27 // Same tactical verdict with colors swapped and board rotated.
28 $mirror=$s;$mirror['board']=array_map(fn($p)=>$p==='.'?'.':(ctype_upper($p)?strtolower($p):strtoupper($p)),array_reverse($s['board']));$mirror['turn']='b';$mirror['history']=[Chess::key($mirror)];
29 $next=Chess::move($mirror,19-$from,19-$to,$promotion);
30 verify((new MoveFeedback())->rate($mirror,$next)['quality']===$quality,"Black perspective: $name");
31 }
32 $s=Chess::initial();$next=Chess::move($s,15,11);
33 foreach([new MoveFeedback(0),new MoveFeedback(200,1)] as $engine){$r=$engine->rate($s,$next);verify($r['quality']===null&&$r['reason']==='inconclusive','Budget exhaustion is silent, not a false verdict');}
34 $s=setup([19=>'K',3=>'k',12=>'R',8=>'q']);$s['halfmove']=100;
35 verify((new MoveFeedback())->rate($s,Chess::move($s,12,8))['quality']===null,'Existing draw claim suppresses move-only grading');
36 $s=setup([10=>'K',0=>'k',6=>'Q']);$s['halfmove']=149;
37 verify((new MoveFeedback())->rate($s,Chess::move($s,6,5))['quality']==='good','Mate takes precedence over automatic move-count draw');
38 $s=setup([10=>'K',0=>'k',6=>'Q']);$next=Chess::move($s,6,7);$next['history']=array_fill(0,5,Chess::key($next));
39 verify((new MoveFeedback())->rate($s,$next)['reason']==='draw','Fivefold repetition respected');
40 // Small reproducible sample exercises realistic positions without any exhaustive search.
41 mt_srand(17);$s=Chess::initial();$worst=0;$total=0;$silent=0;
42 for($i=0;$i<30;$i++){
43 if(Chess::result($s))$s=Chess::initial();$moves=Chess::legal($s);$m=$moves[mt_rand(0,count($moves)-1)];$next=Chess::afterLegal($s,$m);
44 $r=(new MoveFeedback())->rate($s,$next);$worst=max($worst,$r['elapsed_ms']);$total+=$r['elapsed_ms'];$silent+=$r['reason']==='inconclusive'?1:0;$s=$next;
45 verify(in_array($r['quality'],[null,'good','poor'],true),'Only supported pulse values');
46 }
47 echo "$checks feedback checks passed. Sample: mean ".round($total/30,2)." ms, max $worst ms, $silent budget/horizon abstentions / 30 moves.\n";
@@ -1,47 +0,0 @@
1<?php
2declare(strict_types=1);
3require dirname(__DIR__).'/lib/MoveFeedback.php';
4$checks=0;
5function verify(bool $ok,string $label): void {global $checks;$checks++;if(!$ok)throw new RuntimeException($label);}
6function setup(array $pieces,string $turn='w'): array {
7 $s=Chess::initial();$s['board']=array_fill(0,20,'.');foreach($pieces as $i=>$p)$s['board'][$i]=$p;
8 $s['turn']=$turn;$s['history']=[Chess::key($s)];return $s;
9}
10$cases=[
11 'quiet opening'=>[Chess::initial(),15,11,null,null],
12 'free queen'=>[setup([19=>'K',3=>'k',12=>'R',8=>'q']),12,8,null,'good'],
13 'poisoned pawn'=>[setup([19=>'K',1=>'k',12=>'Q',8=>'p',0=>'r']),12,8,null,'poor'],
14 'equal rook exchange'=>[setup([19=>'K',3=>'k',12=>'R',8=>'r',0=>'r']),12,8,null,null],
15 'checkmate'=>[setup([10=>'K',0=>'k',6=>'Q']),6,5,null,'good'],
16 'allows mate in one'=>[setup([16=>'K',10=>'k',14=>'q',3=>'R']),3,7,null,'poor'],
17 'promotion'=>[setup([16=>'K',3=>'k',5=>'P']),5,1,'q','good'],
18 'underpromotion draw'=>[setup([16=>'K',3=>'k',5=>'P']),5,1,'n',null],
19];
20foreach($cases as $name=>[$s,$from,$to,$promotion,$quality]){
21 verify(!Chess::check($s,Chess::opposite($s['turn'])),"Legal fixture: $name");
22 $next=Chess::move($s,$from,$to,$promotion);$result=(new MoveFeedback())->rate($s,$next);
23 echo "$name: ".json_encode($result)."\n";
24 verify($result['quality']===$quality,"$name quality");
25 verify($result['elapsed_ms']<500,"$name stays comfortably inside feedback window");
26 verify(Chess::afterLegal($s,$next['last'])===$next,"Shared transition: $name");
27 // Same tactical verdict with colors swapped and board rotated.
28 $mirror=$s;$mirror['board']=array_map(fn($p)=>$p==='.'?'.':(ctype_upper($p)?strtolower($p):strtoupper($p)),array_reverse($s['board']));$mirror['turn']='b';$mirror['history']=[Chess::key($mirror)];
29 $next=Chess::move($mirror,19-$from,19-$to,$promotion);
30 verify((new MoveFeedback())->rate($mirror,$next)['quality']===$quality,"Black perspective: $name");
31}
32$s=Chess::initial();$next=Chess::move($s,15,11);
33foreach([new MoveFeedback(0),new MoveFeedback(200,1)] as $engine){$r=$engine->rate($s,$next);verify($r['quality']===null&&$r['reason']==='inconclusive','Budget exhaustion is silent, not a false verdict');}
34$s=setup([19=>'K',3=>'k',12=>'R',8=>'q']);$s['halfmove']=100;
35verify((new MoveFeedback())->rate($s,Chess::move($s,12,8))['quality']===null,'Existing draw claim suppresses move-only grading');
36$s=setup([10=>'K',0=>'k',6=>'Q']);$s['halfmove']=149;
37verify((new MoveFeedback())->rate($s,Chess::move($s,6,5))['quality']==='good','Mate takes precedence over automatic move-count draw');
38$s=setup([10=>'K',0=>'k',6=>'Q']);$next=Chess::move($s,6,7);$next['history']=array_fill(0,5,Chess::key($next));
39verify((new MoveFeedback())->rate($s,$next)['reason']==='draw','Fivefold repetition respected');
40// Small reproducible sample exercises realistic positions without any exhaustive search.
41mt_srand(17);$s=Chess::initial();$worst=0;$total=0;$silent=0;
42for($i=0;$i<30;$i++){
43 if(Chess::result($s))$s=Chess::initial();$moves=Chess::legal($s);$m=$moves[mt_rand(0,count($moves)-1)];$next=Chess::afterLegal($s,$m);
44 $r=(new MoveFeedback())->rate($s,$next);$worst=max($worst,$r['elapsed_ms']);$total+=$r['elapsed_ms'];$silent+=$r['reason']==='inconclusive'?1:0;$s=$next;
45 verify(in_array($r['quality'],[null,'good','poor'],true),'Only supported pulse values');
46}
47echo "$checks feedback checks passed. Sample: mean ".round($total/30,2)." ms, max $worst ms, $silent budget/horizon abstentions / 30 moves.\n";
web/tests/integration.py +36 −35
@@ -86,7 +86,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
86 86 check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte')
87 87 loaded=subprocess.check_output(['php','-r',
88 88 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')],
89 env={**os.environ,'MICROCHESS_BASE_URL':'https://example.test','MICROCHESS_CLIENT_ID':'environment-client','MICROCHESS_CLIENT_SECRET':'fixture-secret'},text=True)
89 env={**os.environ,'SYNHEX_BASE_URL':'https://example.test','SYNHEX_CLIENT_ID':'environment-client','SYNHEX_CLIENT_SECRET':'fixture-secret'},text=True)
90 90 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
91 91 b.state(); b.post('switch_user', user='test_user_2'); b.state()
92 92 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
@@ -106,12 +106,12 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
106 106 subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}
107 107 a.post('push_subscribe',subscription=subscription)
108 108 a.post('push_subscribe',subscription=subscription)
109 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
109 with sqlite3.connect(root/'data/synhex.sqlite') as push_db:
110 110 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Repeated device registration does not duplicate')
111 111 old_csrf=a.csrf;a.csrf='wrong';a.post('push_subscribe',subscription=subscription,expected=403);a.csrf=old_csrf
112 112 a.post('push_subscribe',subscription={**subscription,'endpoint':'https://127.0.0.1/private'},expected=409)
113 113 b.post('push_unsubscribe',endpoint=subscription['endpoint'])
114 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
114 with sqlite3.connect(root/'data/synhex.sqlite') as push_db:
115 115 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Unsubscribe requires owning account')
116 116 a.post('push_unsubscribe',endpoint=subscription['endpoint'])
117 117 check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')
@@ -177,24 +177,26 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
177 177 check(ga['pieceSkinWhite']=='White' and ga['pieceSkinBlack']=='Red','Custom White as black rules yields to Red vs default White')
178 178 a.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
179 179 b.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
180 check(push_events()[-1]['kind']=='turn' and push_events()[-1]['user']==('local:test_user_1' if ga['yourTurn'] else 'local:test_user_2'),'Acceptance notifies first player')
181 check(ga['color'] != gb['color'] and ga['yourTurn'] != gb['yourTurn'], 'Opposite colors and one turn')
180 turn_events=[e for e in push_events() if e['kind']=='turn' and e['game']==id]
181 check(len(turn_events)==2,'Acceptance notifies both players to plan')
182 check(ga['color'] != gb['color'] and ga['yourTurn'] and gb['yourTurn'], 'Opposite colors and simultaneous planning')
183 check(ga['state']['phase']=='planning' and ga['state']['grid']['cols']==17,'Hex board is the playable tile')
184 check(len(ga['state']['units'])>=4,'Each viewer sees their operatives')
182 185 white, black = (a,b) if ga['color']=='w' else (b,a)
183 black.game_action('move', id, from_=4, to=8, expected=409)
186 black.game_action('ack_playback', id, expected=409)
184 187 current = white.game(id)
185 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
186 move = current['legal'][0]
188 white.post('commit_plan', game=id, version=current['version']-1, plan={'units':{}}, expected=409)
187 189 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
188 response = white.post('move', game=id, version=current['version'], **move)
189 check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate')
190 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
191 event=push_events()[-1]
192 check(event['kind']=='turn' and event['game']==id and event['user']==black.state()['user']['id'],'Move notifies opponent')
190 white.game_action('commit_plan', id, plan={'units':{}})
191 check(not white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'First lock waits for opponent')
193 192 notification_count=len(push_events())
194 white.post('move', game=id, version=current['version'], **move, expected=409)
195 check(len(push_events())==notification_count,'Stale duplicate move does not notify twice')
196 check(black.game(id)['yourTurn'], 'Turn passes')
197 check(black.game(id)['turnOrder']>current['turnOrder'],'New turn receives a later persistent queue position')
193 white.game_action('commit_plan', id, plan={'units':{}}, expected=409)
194 check(len(push_events())==notification_count,'Stale duplicate commit does not notify twice')
195 black.game_action('commit_plan', id, plan={'units':{}})
196 check(white.game(id)['state']['phase']=='playback','Both locks simulate an act')
197 check(white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'Playback is both players turn')
198 check(white.game(id)['state']['timeline']['durationMs']==3000,'Server stores a 3s playback timeline')
199 check(black.game(id)['turnOrder']>current['turnOrder'],'Simulated act receives a later persistent queue position')
198 200 black.game_action('resign', id)
199 201 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
200 202 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
@@ -205,7 +207,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
205 207 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
206 208 saved_id=archive[0]['id']
207 209 saved=white.get(f'/api.php?action=replay&id={saved_id}')
208 check(len(saved['positions'])==2 and saved['positions'][-1]['board']==white.game(id)['state']['board'],'Replay reconstructs opening and final board')
210 check(len(saved['positions'])>=1 and saved['positions'][0]['grid']['cols']==17,'Replay reconstructs the hex board')
209 211 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
210 212 check(saved['color']=='w','Replay retains player orientation')
211 213 check(saved['whiteName']==white.state()['user']['name'] and saved['blackName']==black.state()['user']['name'],'Replay identifies both colors')
@@ -230,10 +232,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
230 232 a.game_action('rematch', id)
231 233 check(b.game(id)['opponentRematch'], 'Rematch notification')
232 234 b.game_action('rematch', id)
233 check(a.game(id)['color'] != old_color and a.game(id)['state']['ply']==0, 'Rematch swaps sides, same tile')
235 check(a.game(id)['color'] != old_color and a.game(id)['state']['act']==0, 'Rematch swaps sides, same tile')
234 236 turn = a if a.game(id)['yourTurn'] else b
235 237 turn.game_action('offer_draw', id)
236 move = turn.game(id)['legal'][0]; turn.game_action('move',id,**move)
237 238 other = b if turn is a else a
238 239 other.game_action('accept_draw', id)
239 240 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
@@ -262,18 +263,16 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
262 263 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
263 264 statuses=list(pool.map(race_accept,range(2)))
264 265 check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game')
265 con=sqlite3.connect(root/'data/microchess.sqlite')
266 con=sqlite3.connect(root/'data/synhex.sqlite')
266 267 expired = a.post('create_link',kind='match')['url'].split('=')[1]
267 268 con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit()
268 269 b.post('accept_link',token=expired,expected=409)
269 # Server-side claim with an intended move: no requirement to play it first.
270 id=a.state()['games'][0]['id'];g=a.game(id)
271 raw=json.loads(con.execute('SELECT state FROM games WHERE id=?',(id,)).fetchone()[0]);raw['halfmove']=99
272 con.execute('UPDATE games SET state=? WHERE id=?',(json.dumps(raw),id));con.commit()
273 turn=a if g['yourTurn'] else b
274 move=next(m for m in turn.game(id)['legal'] if m['from']==18)
275 turn.game_action('claim_draw',id,**move)
276 check(a.game(id)['reason']=='50-move rule','Intended move draw claim')
270 id=a.state()['games'][0]['id']
271 turn=a if a.game(id)['yourTurn'] else b
272 turn.game_action('offer_draw',id)
273 other=b if turn is a else a
274 other.game_action('accept_draw',id)
275 check(a.game(id)['reason']=='Draw by agreement','Draw by agreement')
277 276 a.post('remove_friend',friend='local:test_user_2')
278 277 check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal')
279 278 a.post('challenge',friend='local:test_user_2',expected=409)
@@ -281,7 +280,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
281 280 check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results')
282 281 check('token' not in exported['profile'],'No auth token in export')
283 282 check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference')
284 for path in ['/data/microchess.sqlite','/lib/bootstrap.php','/tests/chess.php','/data%2fmicrochess.sqlite','/.htaccess']:
283 for path in ['/data/synhex.sqlite','/lib/bootstrap.php','/tests/synhex.php','/data%2fsynhex.sqlite','/.htaccess']:
285 284 try:
286 285 urllib.request.urlopen(base+path)
287 286 check(False,'Protected '+path)
@@ -301,9 +300,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
301 300 old=a.game(inactive_id)
302 301 check(old['inactiveDays']==8,'Eight inactive days shown')
303 302 turn=a if old['yourTurn'] else b
304 turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0])
303 turn.game_action('save_plan',inactive_id,plan={'units':{}})
305 304 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
306 check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity')
305 check(a.game(inactive_id)['inactiveDays']==0,'Plan save resets inactivity')
307 306 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
308 307 a.game_action('stop_inactive',inactive_id)
309 308 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
@@ -391,7 +390,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
391 390 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
392 391 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
393 392 con.close()
394 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
393 with sqlite3.connect(root/'data/synhex.sqlite') as archive_db:
395 394 private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid
396 395 archive_db.execute("INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) SELECT ?, 'queue:oldest', moves, piece_skin_white, piece_skin_black FROM replays WHERE result_id=?",(private_id,saved_id))
397 396 outsider_token=os.urandom(24).hex()
@@ -403,8 +402,10 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
403 402 check(False,'Other players replay unavailable')
404 403 except urllib.error.HTTPError as e:
405 404 check(e.code==404,'Other players replay unavailable')
406 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
407 check(archive_db.execute('SELECT length(moves) FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]==23,'One move uses two bytes plus initial position')
405 with sqlite3.connect(root/'data/synhex.sqlite') as archive_db:
406 blob=archive_db.execute('SELECT moves FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]
407 if isinstance(blob,(bytes,memoryview)): blob=bytes(blob).decode()
408 check(str(blob).startswith('{"version":1'),'Replay stores JSON act history')
408 409 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
409 410 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
410 411 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
@@ -86,7 +86,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
86 check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte')
86 check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte')
87 loaded=subprocess.check_output(['php','-r',
87 loaded=subprocess.check_output(['php','-r',
88 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')],
88 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')],
89 env={**os.environ,'MICROCHESS_BASE_URL':'https://example.test','MICROCHESS_CLIENT_ID':'environment-client','MICROCHESS_CLIENT_SECRET':'fixture-secret'},text=True)
89 env={**os.environ,'SYNHEX_BASE_URL':'https://example.test','SYNHEX_CLIENT_ID':'environment-client','SYNHEX_CLIENT_SECRET':'fixture-secret'},text=True)
90 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
90 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
91 b.state(); b.post('switch_user', user='test_user_2'); b.state()
91 b.state(); b.post('switch_user', user='test_user_2'); b.state()
92 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
92 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
@@ -106,12 +106,12 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
106 subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}
106 subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}
107 a.post('push_subscribe',subscription=subscription)
107 a.post('push_subscribe',subscription=subscription)
108 a.post('push_subscribe',subscription=subscription)
108 a.post('push_subscribe',subscription=subscription)
109 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
109 with sqlite3.connect(root/'data/synhex.sqlite') as push_db:
110 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Repeated device registration does not duplicate')
110 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Repeated device registration does not duplicate')
111 old_csrf=a.csrf;a.csrf='wrong';a.post('push_subscribe',subscription=subscription,expected=403);a.csrf=old_csrf
111 old_csrf=a.csrf;a.csrf='wrong';a.post('push_subscribe',subscription=subscription,expected=403);a.csrf=old_csrf
112 a.post('push_subscribe',subscription={**subscription,'endpoint':'https://127.0.0.1/private'},expected=409)
112 a.post('push_subscribe',subscription={**subscription,'endpoint':'https://127.0.0.1/private'},expected=409)
113 b.post('push_unsubscribe',endpoint=subscription['endpoint'])
113 b.post('push_unsubscribe',endpoint=subscription['endpoint'])
114 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
114 with sqlite3.connect(root/'data/synhex.sqlite') as push_db:
115 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Unsubscribe requires owning account')
115 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Unsubscribe requires owning account')
116 a.post('push_unsubscribe',endpoint=subscription['endpoint'])
116 a.post('push_unsubscribe',endpoint=subscription['endpoint'])
117 check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')
117 check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')
@@ -177,24 +177,26 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
177 check(ga['pieceSkinWhite']=='White' and ga['pieceSkinBlack']=='Red','Custom White as black rules yields to Red vs default White')
177 check(ga['pieceSkinWhite']=='White' and ga['pieceSkinBlack']=='Red','Custom White as black rules yields to Red vs default White')
178 a.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
178 a.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
179 b.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
179 b.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black')
180 check(push_events()[-1]['kind']=='turn' and push_events()[-1]['user']==('local:test_user_1' if ga['yourTurn'] else 'local:test_user_2'),'Acceptance notifies first player')
180 turn_events=[e for e in push_events() if e['kind']=='turn' and e['game']==id]
181 check(ga['color'] != gb['color'] and ga['yourTurn'] != gb['yourTurn'], 'Opposite colors and one turn')
181 check(len(turn_events)==2,'Acceptance notifies both players to plan')
182 check(ga['color'] != gb['color'] and ga['yourTurn'] and gb['yourTurn'], 'Opposite colors and simultaneous planning')
183 check(ga['state']['phase']=='planning' and ga['state']['grid']['cols']==17,'Hex board is the playable tile')
184 check(len(ga['state']['units'])>=4,'Each viewer sees their operatives')
182 white, black = (a,b) if ga['color']=='w' else (b,a)
185 white, black = (a,b) if ga['color']=='w' else (b,a)
183 black.game_action('move', id, from_=4, to=8, expected=409)
186 black.game_action('ack_playback', id, expected=409)
184 current = white.game(id)
187 current = white.game(id)
185 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
188 white.post('commit_plan', game=id, version=current['version']-1, plan={'units':{}}, expected=409)
186 move = current['legal'][0]
187 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
189 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
188 response = white.post('move', game=id, version=current['version'], **move)
190 white.game_action('commit_plan', id, plan={'units':{}})
189 check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate')
191 check(not white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'First lock waits for opponent')
190 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
191 event=push_events()[-1]
192 check(event['kind']=='turn' and event['game']==id and event['user']==black.state()['user']['id'],'Move notifies opponent')
193 notification_count=len(push_events())
192 notification_count=len(push_events())
194 white.post('move', game=id, version=current['version'], **move, expected=409)
193 white.game_action('commit_plan', id, plan={'units':{}}, expected=409)
195 check(len(push_events())==notification_count,'Stale duplicate move does not notify twice')
194 check(len(push_events())==notification_count,'Stale duplicate commit does not notify twice')
196 check(black.game(id)['yourTurn'], 'Turn passes')
195 black.game_action('commit_plan', id, plan={'units':{}})
197 check(black.game(id)['turnOrder']>current['turnOrder'],'New turn receives a later persistent queue position')
196 check(white.game(id)['state']['phase']=='playback','Both locks simulate an act')
197 check(white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'Playback is both players turn')
198 check(white.game(id)['state']['timeline']['durationMs']==3000,'Server stores a 3s playback timeline')
199 check(black.game(id)['turnOrder']>current['turnOrder'],'Simulated act receives a later persistent queue position')
198 black.game_action('resign', id)
200 black.game_action('resign', id)
199 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
201 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
200 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
202 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
@@ -205,7 +207,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
205 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
207 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
206 saved_id=archive[0]['id']
208 saved_id=archive[0]['id']
207 saved=white.get(f'/api.php?action=replay&id={saved_id}')
209 saved=white.get(f'/api.php?action=replay&id={saved_id}')
208 check(len(saved['positions'])==2 and saved['positions'][-1]['board']==white.game(id)['state']['board'],'Replay reconstructs opening and final board')
210 check(len(saved['positions'])>=1 and saved['positions'][0]['grid']['cols']==17,'Replay reconstructs the hex board')
209 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
211 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
210 check(saved['color']=='w','Replay retains player orientation')
212 check(saved['color']=='w','Replay retains player orientation')
211 check(saved['whiteName']==white.state()['user']['name'] and saved['blackName']==black.state()['user']['name'],'Replay identifies both colors')
213 check(saved['whiteName']==white.state()['user']['name'] and saved['blackName']==black.state()['user']['name'],'Replay identifies both colors')
@@ -230,10 +232,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
230 a.game_action('rematch', id)
232 a.game_action('rematch', id)
231 check(b.game(id)['opponentRematch'], 'Rematch notification')
233 check(b.game(id)['opponentRematch'], 'Rematch notification')
232 b.game_action('rematch', id)
234 b.game_action('rematch', id)
233 check(a.game(id)['color'] != old_color and a.game(id)['state']['ply']==0, 'Rematch swaps sides, same tile')
235 check(a.game(id)['color'] != old_color and a.game(id)['state']['act']==0, 'Rematch swaps sides, same tile')
234 turn = a if a.game(id)['yourTurn'] else b
236 turn = a if a.game(id)['yourTurn'] else b
235 turn.game_action('offer_draw', id)
237 turn.game_action('offer_draw', id)
236 move = turn.game(id)['legal'][0]; turn.game_action('move',id,**move)
237 other = b if turn is a else a
238 other = b if turn is a else a
238 other.game_action('accept_draw', id)
239 other.game_action('accept_draw', id)
239 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
240 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
@@ -262,18 +263,16 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
262 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
263 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
263 statuses=list(pool.map(race_accept,range(2)))
264 statuses=list(pool.map(race_accept,range(2)))
264 check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game')
265 check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game')
265 con=sqlite3.connect(root/'data/microchess.sqlite')
266 con=sqlite3.connect(root/'data/synhex.sqlite')
266 expired = a.post('create_link',kind='match')['url'].split('=')[1]
267 expired = a.post('create_link',kind='match')['url'].split('=')[1]
267 con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit()
268 con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit()
268 b.post('accept_link',token=expired,expected=409)
269 b.post('accept_link',token=expired,expected=409)
269 # Server-side claim with an intended move: no requirement to play it first.
270 id=a.state()['games'][0]['id']
270 id=a.state()['games'][0]['id'];g=a.game(id)
271 turn=a if a.game(id)['yourTurn'] else b
271 raw=json.loads(con.execute('SELECT state FROM games WHERE id=?',(id,)).fetchone()[0]);raw['halfmove']=99
272 turn.game_action('offer_draw',id)
272 con.execute('UPDATE games SET state=? WHERE id=?',(json.dumps(raw),id));con.commit()
273 other=b if turn is a else a
273 turn=a if g['yourTurn'] else b
274 other.game_action('accept_draw',id)
274 move=next(m for m in turn.game(id)['legal'] if m['from']==18)
275 check(a.game(id)['reason']=='Draw by agreement','Draw by agreement')
275 turn.game_action('claim_draw',id,**move)
276 check(a.game(id)['reason']=='50-move rule','Intended move draw claim')
277 a.post('remove_friend',friend='local:test_user_2')
276 a.post('remove_friend',friend='local:test_user_2')
278 check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal')
277 check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal')
279 a.post('challenge',friend='local:test_user_2',expected=409)
278 a.post('challenge',friend='local:test_user_2',expected=409)
@@ -281,7 +280,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
281 check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results')
280 check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results')
282 check('token' not in exported['profile'],'No auth token in export')
281 check('token' not in exported['profile'],'No auth token in export')
283 check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference')
282 check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference')
284 for path in ['/data/microchess.sqlite','/lib/bootstrap.php','/tests/chess.php','/data%2fmicrochess.sqlite','/.htaccess']:
283 for path in ['/data/synhex.sqlite','/lib/bootstrap.php','/tests/synhex.php','/data%2fsynhex.sqlite','/.htaccess']:
285 try:
284 try:
286 urllib.request.urlopen(base+path)
285 urllib.request.urlopen(base+path)
287 check(False,'Protected '+path)
286 check(False,'Protected '+path)
@@ -301,9 +300,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
301 old=a.game(inactive_id)
300 old=a.game(inactive_id)
302 check(old['inactiveDays']==8,'Eight inactive days shown')
301 check(old['inactiveDays']==8,'Eight inactive days shown')
303 turn=a if old['yourTurn'] else b
302 turn=a if old['yourTurn'] else b
304 turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0])
303 turn.game_action('save_plan',inactive_id,plan={'units':{}})
305 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
304 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
306 check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity')
305 check(a.game(inactive_id)['inactiveDays']==0,'Plan save resets inactivity')
307 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
306 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
308 a.game_action('stop_inactive',inactive_id)
307 a.game_action('stop_inactive',inactive_id)
309 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
308 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
@@ -391,7 +390,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
391 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
390 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
392 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
391 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
393 con.close()
392 con.close()
394 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
393 with sqlite3.connect(root/'data/synhex.sqlite') as archive_db:
395 private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid
394 private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid
396 archive_db.execute("INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) SELECT ?, 'queue:oldest', moves, piece_skin_white, piece_skin_black FROM replays WHERE result_id=?",(private_id,saved_id))
395 archive_db.execute("INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) SELECT ?, 'queue:oldest', moves, piece_skin_white, piece_skin_black FROM replays WHERE result_id=?",(private_id,saved_id))
397 outsider_token=os.urandom(24).hex()
396 outsider_token=os.urandom(24).hex()
@@ -403,8 +402,10 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
403 check(False,'Other players replay unavailable')
402 check(False,'Other players replay unavailable')
404 except urllib.error.HTTPError as e:
403 except urllib.error.HTTPError as e:
405 check(e.code==404,'Other players replay unavailable')
404 check(e.code==404,'Other players replay unavailable')
406 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
405 with sqlite3.connect(root/'data/synhex.sqlite') as archive_db:
407 check(archive_db.execute('SELECT length(moves) FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]==23,'One move uses two bytes plus initial position')
406 blob=archive_db.execute('SELECT moves FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]
407 if isinstance(blob,(bytes,memoryview)): blob=bytes(blob).decode()
408 check(str(blob).startswith('{"version":1'),'Replay stores JSON act history')
408 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
409 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
409 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
410 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
410 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
411 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
web/tests/push.php +10 −7
@@ -1,12 +1,13 @@
1 1 <?php
2 2 // Isolated database and real Web Push encryption, with an in-memory HTTP transport.
3 3 declare(strict_types=1);
4 $root=sys_get_temp_dir().'/microchess-push-'.bin2hex(random_bytes(6));
4 $root=sys_get_temp_dir().'/synhex-push-'.bin2hex(random_bytes(6));
5 5 mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
6 foreach (['bootstrap.php','Chess.php','MoveFeedback.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
6 foreach (['bootstrap.php','HexGrid.php','SynhexSim.php','SynhexMatch.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
7 copy(__DIR__.'/../lib/game-config.php',$root.'/lib/game-config.php');
7 8 symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
8 9 copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
9 $_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/microchess/api.php'];
10 $_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/synhex/api.php'];
10 11 require $root.'/lib/bootstrap.php';
11 12 use Minishlink\WebPush\WebPush;
12 13 use Minishlink\WebPush\VAPID;
@@ -35,13 +36,15 @@ try {
35 36 $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
36 37 $GLOBALS['push_events']=[];pushGame($id);
37 38 $events=$GLOBALS['push_events'];
38 check(count($events)===1 && array_values($events)[0]['user']===$v,'Notify player whose turn starts');
39 $users=array_column(array_values($events),'user');
40 check(count($events)===2 && in_array($u,$users,true) && in_array($v,$users,true),'Notify both players when planning starts');
39 41 pushSubscribe($v,['subscription'=>$sub]);
40 42 check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
41 43 $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
42 44 $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
43 45 $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
44 pushDeliver($events,$sender);
46 $one=[array_values($events)[0]];
47 pushDeliver($one,$sender);
45 48 check(count($history)===1,'Sends through HTTP transport');
46 49 $request=$history[0]['request'];
47 50 check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
@@ -49,8 +52,8 @@ try {
49 52 check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
50 53 check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
51 54 query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
52 pushDeliver($events,$sender);check(count($history)===1,'Skip superseded event');
53 $GLOBALS['push_events']=[];pushGame($id);pushDeliver($GLOBALS['push_events'],$sender);
55 pushDeliver($one,$sender);check(count($history)===1,'Skip superseded event');
56 $GLOBALS['push_events']=[];pushGame($id);pushDeliver([array_values($GLOBALS['push_events'])[0]],$sender);
54 57 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
55 58 $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
56 59 check(!$GLOBALS['push_events'],'No turn notification after game ends');
@@ -1,12 +1,13 @@
1<?php
1<?php
2// Isolated database and real Web Push encryption, with an in-memory HTTP transport.
2// Isolated database and real Web Push encryption, with an in-memory HTTP transport.
3declare(strict_types=1);
3declare(strict_types=1);
4$root=sys_get_temp_dir().'/microchess-push-'.bin2hex(random_bytes(6));
4$root=sys_get_temp_dir().'/synhex-push-'.bin2hex(random_bytes(6));
5mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
5mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
6foreach (['bootstrap.php','Chess.php','MoveFeedback.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
6foreach (['bootstrap.php','HexGrid.php','SynhexSim.php','SynhexMatch.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
7copy(__DIR__.'/../lib/game-config.php',$root.'/lib/game-config.php');
7symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
8symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
8copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
9copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
9$_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/microchess/api.php'];
10$_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/synhex/api.php'];
10require $root.'/lib/bootstrap.php';
11require $root.'/lib/bootstrap.php';
11use Minishlink\WebPush\WebPush;
12use Minishlink\WebPush\WebPush;
12use Minishlink\WebPush\VAPID;
13use Minishlink\WebPush\VAPID;
@@ -35,13 +36,15 @@ try {
35 $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
36 $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
36 $GLOBALS['push_events']=[];pushGame($id);
37 $GLOBALS['push_events']=[];pushGame($id);
37 $events=$GLOBALS['push_events'];
38 $events=$GLOBALS['push_events'];
38 check(count($events)===1 && array_values($events)[0]['user']===$v,'Notify player whose turn starts');
39 $users=array_column(array_values($events),'user');
40 check(count($events)===2 && in_array($u,$users,true) && in_array($v,$users,true),'Notify both players when planning starts');
39 pushSubscribe($v,['subscription'=>$sub]);
41 pushSubscribe($v,['subscription'=>$sub]);
40 check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
42 check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
41 $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
43 $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
42 $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
44 $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
43 $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
45 $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
44 pushDeliver($events,$sender);
46 $one=[array_values($events)[0]];
47 pushDeliver($one,$sender);
45 check(count($history)===1,'Sends through HTTP transport');
48 check(count($history)===1,'Sends through HTTP transport');
46 $request=$history[0]['request'];
49 $request=$history[0]['request'];
47 check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
50 check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
@@ -49,8 +52,8 @@ try {
49 check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
52 check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
50 check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
53 check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
51 query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
54 query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
52 pushDeliver($events,$sender);check(count($history)===1,'Skip superseded event');
55 pushDeliver($one,$sender);check(count($history)===1,'Skip superseded event');
53 $GLOBALS['push_events']=[];pushGame($id);pushDeliver($GLOBALS['push_events'],$sender);
56 $GLOBALS['push_events']=[];pushGame($id);pushDeliver([array_values($GLOBALS['push_events'])[0]],$sender);
54 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
57 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
55 $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
58 $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
56 check(!$GLOBALS['push_events'],'No turn notification after game ends');
59 check(!$GLOBALS['push_events'],'No turn notification after game ends');
web/tests/pwa.mjs +2 −2
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
3 3 import { readFile } from 'node:fs/promises';
4 4 import vm from 'node:vm';
5 5 const handlers = {}, shown = [], opened = [], navigated = [];
6 const scope = 'https://example.test/microchess/';
6 const scope = 'https://example.test/synhex/';
7 7 let windows = [], focused = false;
8 8 const self = {
9 9 addEventListener: (name, handler) => { handlers[name] = handler; },
@@ -23,7 +23,7 @@ assert.equal(shown[0].icon, scope + 'assets/app-icon-192.png');
23 23 assert.equal(shown[0].data.game, 42);
24 24 windows = [{ url: scope, visibilityState: 'visible' }];
25 25 await dispatch('push', { data: { json: () => ({ game: 99, body: 'Should stay silent.' }) } });
26 assert.equal(shown.length, 1, 'Visible Microchess tab suppresses OS notification');
26 assert.equal(shown.length, 1, 'Visible Synhex tab suppresses OS notification');
27 27 windows = [{ url: scope, visibilityState: 'hidden' }];
28 28 await dispatch('push', { data: { json: () => ({ game: 100, body: 'Background tab still notifies.' }) } });
29 29 assert.equal(shown.length, 2, 'Hidden tab still shows a notification');
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
3import { readFile } from 'node:fs/promises';
3import { readFile } from 'node:fs/promises';
4import vm from 'node:vm';
4import vm from 'node:vm';
5const handlers = {}, shown = [], opened = [], navigated = [];
5const handlers = {}, shown = [], opened = [], navigated = [];
6const scope = 'https://example.test/microchess/';
6const scope = 'https://example.test/synhex/';
7let windows = [], focused = false;
7let windows = [], focused = false;
8const self = {
8const self = {
9 addEventListener: (name, handler) => { handlers[name] = handler; },
9 addEventListener: (name, handler) => { handlers[name] = handler; },
@@ -23,7 +23,7 @@ assert.equal(shown[0].icon, scope + 'assets/app-icon-192.png');
23assert.equal(shown[0].data.game, 42);
23assert.equal(shown[0].data.game, 42);
24windows = [{ url: scope, visibilityState: 'visible' }];
24windows = [{ url: scope, visibilityState: 'visible' }];
25await dispatch('push', { data: { json: () => ({ game: 99, body: 'Should stay silent.' }) } });
25await dispatch('push', { data: { json: () => ({ game: 99, body: 'Should stay silent.' }) } });
26assert.equal(shown.length, 1, 'Visible Microchess tab suppresses OS notification');
26assert.equal(shown.length, 1, 'Visible Synhex tab suppresses OS notification');
27windows = [{ url: scope, visibilityState: 'hidden' }];
27windows = [{ url: scope, visibilityState: 'hidden' }];
28await dispatch('push', { data: { json: () => ({ game: 100, body: 'Background tab still notifies.' }) } });
28await dispatch('push', { data: { json: () => ({ game: 100, body: 'Background tab still notifies.' }) } });
29assert.equal(shown.length, 2, 'Hidden tab still shows a notification');
29assert.equal(shown.length, 2, 'Hidden tab still shows a notification');
web/tests/startup.py +1 −1
@@ -20,7 +20,7 @@ with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
20 20 log = root / 'data/php-errors.log'
21 21 assert not log.exists() or not log.read_text(), 'Startup emitted PHP errors'
22 22 startup()
23 con = sqlite3.connect(root / 'data/microchess.sqlite')
23 con = sqlite3.connect(root / 'data/synhex.sqlite')
24 24 con.executescript("""
25 25 INSERT INTO users VALUES('a','Alice'),('b','Bob');
26 26 INSERT INTO games(a,b,status,created) VALUES('a','b','active',123);
@@ -20,7 +20,7 @@ with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
20 log = root / 'data/php-errors.log'
20 log = root / 'data/php-errors.log'
21 assert not log.exists() or not log.read_text(), 'Startup emitted PHP errors'
21 assert not log.exists() or not log.read_text(), 'Startup emitted PHP errors'
22 startup()
22 startup()
23 con = sqlite3.connect(root / 'data/microchess.sqlite')
23 con = sqlite3.connect(root / 'data/synhex.sqlite')
24 con.executescript("""
24 con.executescript("""
25 INSERT INTO users VALUES('a','Alice'),('b','Bob');
25 INSERT INTO users VALUES('a','Alice'),('b','Bob');
26 INSERT INTO games(a,b,status,created) VALUES('a','b','active',123);
26 INSERT INTO games(a,b,status,created) VALUES('a','b','active',123);
web/tests/synhex.php added +90 −0
@@ -0,0 +1,90 @@
1 <?php
2 declare(strict_types=1);
3 require dirname(__DIR__).'/lib/HexGrid.php';
4 require dirname(__DIR__).'/lib/SynhexSim.php';
5 require dirname(__DIR__).'/lib/SynhexMatch.php';
6 $checks=0;
7 function check(bool $ok,string $label): void {global $checks;$checks++;if(!$ok)throw new RuntimeException($label);}
8
9 $cfg=SynhexMatch::config();
10 check($cfg['grid_cols']===17 && $cfg['grid_rows']===14,'Documented 17×14 odd-r board');
11 check($cfg['walk_range']===5 && $cfg['act_duration_ms']===3000,'Walk 5 hexes / 3s act');
12 check($cfg['base_accuracy']===15,'Base accuracy 15%');
13 check($cfg['weapon_shotgun_pellets']>=2,'Shotgun fires multiple pellets');
14 check($cfg['vision_cone_half_deg']===60,'120° cone (half-angle 60)');
15 check(count($cfg['spawn']['w'])===4 && count($cfg['spawn']['b'])===4,'Four units per side');
16 check($cfg['spawn']['w'][0]['role']==='vip' && $cfg['spawn']['w'][0]['weapon']==='pistol','VIP pistol');
17 $weapons=array_column($cfg['spawn']['w'],'weapon');
18 check($weapons===['pistol','smg','smg','shotgun'],'VIP + 2 SMG + shotgun');
19
20 check(HexGrid::distance(0,0,1,0)===1,'East neighbor is 1');
21 check(HexGrid::distance(0,0,-1,0)===1,'West neighbor is 1');
22 [$q,$r]=HexGrid::axial(3,4);[$c,$row]=HexGrid::offset($q,$r);
23 check($c===3 && $row===4,'Offset/axial round-trip');
24 check(HexGrid::inCone(0,0,0,2,0,60),'Forward hex is in cone');
25 check(!HexGrid::inCone(0,0,0,-2,0,60),'Rear hex is outside cone');
26 $walls=[HexGrid::key(1,0)=>true];
27 check(!HexGrid::los(0,0,2,0,$walls),'Wall blocks LoS');
28 check(HexGrid::los(0,0,0,1,[]),'Open LoS');
29 $walk=HexGrid::allHexes(8,6);
30 unset($walk[HexGrid::key(...HexGrid::axial(3,2))]);
31 [$q1,$r1]=HexGrid::axial(0,2);[$q2,$r2]=HexGrid::axial(6,2);
32 $path=HexGrid::path($q1,$r1,$q2,$r2,$walk);
33 check($path!==null && count($path)>2,'A* walks around a wall');
34
35 $s=SynhexMatch::initial(24,$cfg);
36 check(count($s['units'])===8,'Eight operatives');
37 check($s['grid']['cols']===17 && $s['phase']==='planning','Planning on configured grid');
38 check(count(array_filter($s['units'],fn($u)=>$u['role']==='vip'))===2,'Two VIPs');
39 check(SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'Both plan at once');
40 foreach ($s['walls'] as $key) check(is_string($key) && str_contains($key,','),'Walls stored as q,r keys');
41
42 $s=SynhexMatch::commit($s,'w',['units'=>[]],$cfg);
43 check(!SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'First lock waits for opponent');
44 $s=SynhexMatch::commit($s,'b',['units'=>[]],$cfg);
45 check(($s['phase']??'')==='playback','Both locks run the act');
46 check((int)$s['timeline']['durationMs']===3000,'Playback lasts one act');
47 check(isset($s['timeline']['snapshots'][0]['units']),'Timeline has snapshots');
48 $again=SynhexMatch::initial(24,$cfg);
49 $again=SynhexMatch::commit($again,'w',['units'=>[]],$cfg);
50 $again=SynhexMatch::commit($again,'b',['units'=>[]],$cfg);
51 check($again['timeline']['shots']===$s['timeline']['shots'],'Same seed is deterministic');
52
53 $s=SynhexMatch::ackPlayback($s,'w');
54 check(!SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'Playback ack waits for opponent');
55 $s=SynhexMatch::ackPlayback($s,'b');
56 check($s['phase']==='planning' || $s['phase']==='ended','After both Play, next plan or ended');
57
58 $tiny=$cfg;
59 $tiny['grid_cols']=7;$tiny['grid_rows']=5;$tiny['wall_density']=0;$tiny['wall_gen_attempts']=1;
60 $tiny['spawn']=['w'=>[['id'=>'vip','role'=>'vip','weapon'=>'pistol','col'=>1,'row'=>2,'facing'=>0]],'b'=>[['id'=>'vip','role'=>'vip','weapon'=>'pistol','col'=>5,'row'=>2,'facing'=>3]]];
61 $tiny['base_accuracy']=100;$tiny['accuracy_cap']=100;$tiny['shot_range']=10;$tiny['vision_range']=10;
62 $duel=SynhexMatch::initial(7,$tiny);
63 $duel=SynhexMatch::commit($duel,'w',['units'=>[]],$tiny);
64 $duel=SynhexMatch::commit($duel,'b',['units'=>[]],$tiny);
65 check($duel['timeline']['shots']!==[],'Facing VIPs fire when accuracy is certain');
66 check($duel['result']!==null,'VIP death produces a result after the act');
67
68 $shotCfg=$cfg;$shotCfg['weapon_shotgun_pellets']=5;
69 $st=SynhexMatch::initial(3,$shotCfg);
70 $shot=null;
71 foreach ($st['units'] as $u) if ($u['weapon']==='shotgun') $shot=$u;
72 check($shot!==null,'Shotgun unit exists');
73 $alive=array_values(array_filter($st['units'],fn($u)=>$u['team']!==$shot['team']));
74 $target=$alive[0];
75 $aims=new ReflectionClass(SynhexSim::class);
76 $m=$aims->getMethod('pelletAims');
77 $m->setAccessible(true);
78 $points=$m->invoke(null,$shot,$target,5,(int)$shotCfg['weapon_shotgun_spread']);
79 check(count($points)===5,'Shotgun volley has five rays');
80
81 $bad=SynhexMatch::initial(1,$cfg);
82 try {SynhexMatch::sanitizePlan($bad,'w',['units'=>['w-vip'=>['path'=>[['q'=>99,'r'=>99]]]]],$cfg);check(false,'Rejects illegal path');}
83 catch (DomainException) {check(true,'Rejects illegal path');}
84
85 $view=SynhexMatch::clientView($st,'w',$cfg);
86 check(isset($view['grid'],$view['units'],$view['rules']['walkRange']),'Client view exposes board + tunables');
87 $own=array_filter($view['units'],fn($u)=>$u['team']==='w' && empty($u['hologram']));
88 check(count($own)===4,'Viewer always sees own units');
89
90 echo "Synhex: $checks assertions passed.\n";
@@ -0,0 +1,90 @@
1<?php
2declare(strict_types=1);
3require dirname(__DIR__).'/lib/HexGrid.php';
4require dirname(__DIR__).'/lib/SynhexSim.php';
5require dirname(__DIR__).'/lib/SynhexMatch.php';
6$checks=0;
7function check(bool $ok,string $label): void {global $checks;$checks++;if(!$ok)throw new RuntimeException($label);}
8
9$cfg=SynhexMatch::config();
10check($cfg['grid_cols']===17 && $cfg['grid_rows']===14,'Documented 17×14 odd-r board');
11check($cfg['walk_range']===5 && $cfg['act_duration_ms']===3000,'Walk 5 hexes / 3s act');
12check($cfg['base_accuracy']===15,'Base accuracy 15%');
13check($cfg['weapon_shotgun_pellets']>=2,'Shotgun fires multiple pellets');
14check($cfg['vision_cone_half_deg']===60,'120° cone (half-angle 60)');
15check(count($cfg['spawn']['w'])===4 && count($cfg['spawn']['b'])===4,'Four units per side');
16check($cfg['spawn']['w'][0]['role']==='vip' && $cfg['spawn']['w'][0]['weapon']==='pistol','VIP pistol');
17$weapons=array_column($cfg['spawn']['w'],'weapon');
18check($weapons===['pistol','smg','smg','shotgun'],'VIP + 2 SMG + shotgun');
19
20check(HexGrid::distance(0,0,1,0)===1,'East neighbor is 1');
21check(HexGrid::distance(0,0,-1,0)===1,'West neighbor is 1');
22[$q,$r]=HexGrid::axial(3,4);[$c,$row]=HexGrid::offset($q,$r);
23check($c===3 && $row===4,'Offset/axial round-trip');
24check(HexGrid::inCone(0,0,0,2,0,60),'Forward hex is in cone');
25check(!HexGrid::inCone(0,0,0,-2,0,60),'Rear hex is outside cone');
26$walls=[HexGrid::key(1,0)=>true];
27check(!HexGrid::los(0,0,2,0,$walls),'Wall blocks LoS');
28check(HexGrid::los(0,0,0,1,[]),'Open LoS');
29$walk=HexGrid::allHexes(8,6);
30unset($walk[HexGrid::key(...HexGrid::axial(3,2))]);
31[$q1,$r1]=HexGrid::axial(0,2);[$q2,$r2]=HexGrid::axial(6,2);
32$path=HexGrid::path($q1,$r1,$q2,$r2,$walk);
33check($path!==null && count($path)>2,'A* walks around a wall');
34
35$s=SynhexMatch::initial(24,$cfg);
36check(count($s['units'])===8,'Eight operatives');
37check($s['grid']['cols']===17 && $s['phase']==='planning','Planning on configured grid');
38check(count(array_filter($s['units'],fn($u)=>$u['role']==='vip'))===2,'Two VIPs');
39check(SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'Both plan at once');
40foreach ($s['walls'] as $key) check(is_string($key) && str_contains($key,','),'Walls stored as q,r keys');
41
42$s=SynhexMatch::commit($s,'w',['units'=>[]],$cfg);
43check(!SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'First lock waits for opponent');
44$s=SynhexMatch::commit($s,'b',['units'=>[]],$cfg);
45check(($s['phase']??'')==='playback','Both locks run the act');
46check((int)$s['timeline']['durationMs']===3000,'Playback lasts one act');
47check(isset($s['timeline']['snapshots'][0]['units']),'Timeline has snapshots');
48$again=SynhexMatch::initial(24,$cfg);
49$again=SynhexMatch::commit($again,'w',['units'=>[]],$cfg);
50$again=SynhexMatch::commit($again,'b',['units'=>[]],$cfg);
51check($again['timeline']['shots']===$s['timeline']['shots'],'Same seed is deterministic');
52
53$s=SynhexMatch::ackPlayback($s,'w');
54check(!SynhexMatch::isYourTurn($s,'w') && SynhexMatch::isYourTurn($s,'b'),'Playback ack waits for opponent');
55$s=SynhexMatch::ackPlayback($s,'b');
56check($s['phase']==='planning' || $s['phase']==='ended','After both Play, next plan or ended');
57
58$tiny=$cfg;
59$tiny['grid_cols']=7;$tiny['grid_rows']=5;$tiny['wall_density']=0;$tiny['wall_gen_attempts']=1;
60$tiny['spawn']=['w'=>[['id'=>'vip','role'=>'vip','weapon'=>'pistol','col'=>1,'row'=>2,'facing'=>0]],'b'=>[['id'=>'vip','role'=>'vip','weapon'=>'pistol','col'=>5,'row'=>2,'facing'=>3]]];
61$tiny['base_accuracy']=100;$tiny['accuracy_cap']=100;$tiny['shot_range']=10;$tiny['vision_range']=10;
62$duel=SynhexMatch::initial(7,$tiny);
63$duel=SynhexMatch::commit($duel,'w',['units'=>[]],$tiny);
64$duel=SynhexMatch::commit($duel,'b',['units'=>[]],$tiny);
65check($duel['timeline']['shots']!==[],'Facing VIPs fire when accuracy is certain');
66check($duel['result']!==null,'VIP death produces a result after the act');
67
68$shotCfg=$cfg;$shotCfg['weapon_shotgun_pellets']=5;
69$st=SynhexMatch::initial(3,$shotCfg);
70$shot=null;
71foreach ($st['units'] as $u) if ($u['weapon']==='shotgun') $shot=$u;
72check($shot!==null,'Shotgun unit exists');
73$alive=array_values(array_filter($st['units'],fn($u)=>$u['team']!==$shot['team']));
74$target=$alive[0];
75$aims=new ReflectionClass(SynhexSim::class);
76$m=$aims->getMethod('pelletAims');
77$m->setAccessible(true);
78$points=$m->invoke(null,$shot,$target,5,(int)$shotCfg['weapon_shotgun_spread']);
79check(count($points)===5,'Shotgun volley has five rays');
80
81$bad=SynhexMatch::initial(1,$cfg);
82try {SynhexMatch::sanitizePlan($bad,'w',['units'=>['w-vip'=>['path'=>[['q'=>99,'r'=>99]]]]],$cfg);check(false,'Rejects illegal path');}
83catch (DomainException) {check(true,'Rejects illegal path');}
84
85$view=SynhexMatch::clientView($st,'w',$cfg);
86check(isset($view['grid'],$view['units'],$view['rules']['walkRange']),'Client view exposes board + tunables');
87$own=array_filter($view['units'],fn($u)=>$u['team']==='w' && empty($u['hologram']));
88check(count($own)===4,'Viewer always sees own units');
89
90echo "Synhex: $checks assertions passed.\n";