BlueGit

projects-timfalken-com microchess

effects

timfa Tim Falken · pushed by timfa

Authored 2026-09-08 · 2 months ago

Hash
d82deb2fb78a66fbd629aa96183909c67461f7f0
Parent
b6d76156
14 files changed +1929 −205
.gitignore +5 −0
@@ -5,3 +5,8 @@
5 5 /web/tests/artifacts/
6 6 __pycache__/
7 7 *.py[cod]
8
9 # Keep data from the previous offline analysis experiment local.
10 /.tablebase/
11
12 /web/lib/tablebase/
@@ -5,3 +5,8 @@
5/web/tests/artifacts/
5/web/tests/artifacts/
6__pycache__/
6__pycache__/
7*.py[cod]
7*.py[cod]
8
9# Keep data from the previous offline analysis experiment local.
10/.tablebase/
11
12/web/lib/tablebase/
.gitlab-ci.yml +1 −0
@@ -12,6 +12,7 @@ php_tests:
12 12 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
13 13 - php -r 'foreach (["pdo_sqlite", "curl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
14 14 - php web/tests/chess.php
15 - php web/tests/feedback.php
15 16 - python3 web/tests/startup.py
16 17 - python3 web/tests/integration.py
17 18
@@ -12,6 +12,7 @@ php_tests:
12 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
12 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
13 - php -r 'foreach (["pdo_sqlite", "curl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
13 - php -r 'foreach (["pdo_sqlite", "curl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
14 - php web/tests/chess.php
14 - php web/tests/chess.php
15 - php web/tests/feedback.php
15 - python3 web/tests/startup.py
16 - python3 web/tests/startup.py
16 - python3 web/tests/integration.py
17 - python3 web/tests/integration.py
17
18
README.md +2 −0
@@ -10,6 +10,8 @@ php -S 127.0.0.1:8080 -t web web/router.php
10 10
11 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.
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).
14
13 15 ## GitLab CI/CD
14 16
15 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.
@@ -10,6 +10,8 @@ php -S 127.0.0.1:8080 -t web web/router.php
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, including when served through Apache. See [`web/README.md`](web/README.md) for setup, OAuth configuration, 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).
14
13## GitLab CI/CD
15## GitLab CI/CD
14
16
15The 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.
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.
web/README.md +32 −0
@@ -81,6 +81,7 @@ From the repository root:
81 81 ```sh
82 82 find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
83 83 php web/tests/chess.php
84 php web/tests/feedback.php
84 85 python3 web/tests/startup.py
85 86 python3 web/tests/integration.py
86 87 node --check web/assets/app.js
@@ -105,3 +106,34 @@ Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [
105 106 ## Inactive games and final positions
106 107
107 108 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.
109
110 ## Move feedback
111
112 Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:
113
114 ```sh
115 php -S 127.0.0.1:8080 -t web web/router.php
116 ```
117
118 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.
119
120 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.
121
122 `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.
123
124 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.
125
126 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.
127
128 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.
129
130 Checks:
131
132 ```sh
133 php web/tests/chess.php
134 php web/tests/feedback.php
135 python3 web/tests/integration.py
136 node web/tests/browser.mjs
137 ```
138
139 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.
@@ -81,6 +81,7 @@ From the repository root:
81```sh
81```sh
82find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
82find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
83php web/tests/chess.php
83php web/tests/chess.php
84php web/tests/feedback.php
84python3 web/tests/startup.py
85python3 web/tests/startup.py
85python3 web/tests/integration.py
86python3 web/tests/integration.py
86node --check web/assets/app.js
87node --check web/assets/app.js
@@ -105,3 +106,34 @@ Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [
105## Inactive games and final positions
106## Inactive games and final positions
106
107
107Ended 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.
108Ended 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.
109
110## Move feedback
111
112Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:
113
114```sh
115php -S 127.0.0.1:8080 -t web web/router.php
116```
117
118After 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.
119
120The 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.
121
122`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.
123
124Values 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.
125
126Analysis 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.
127
128Previous 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.
129
130Checks:
131
132```sh
133php web/tests/chess.php
134php web/tests/feedback.php
135python3 web/tests/integration.py
136node web/tests/browser.mjs
137```
138
139The 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.
web/api.php +11 −1
@@ -110,7 +110,9 @@ try {
110 110 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
111 111 if ($action==='move') {
112 112 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
113 $before=$s;
113 114 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
115 $feedbackStates=[$before,$s];
114 116 $r=Chess::result($s);
115 117 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
116 118 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']]);
@@ -129,7 +131,15 @@ try {
129 131 else throw new DomainException('Unknown action.');
130 132 }
131 133 }
132 db()->exec('COMMIT');jsonOut($out);
134 db()->exec('COMMIT');
135 if (isset($feedbackStates)) {
136 // Release game/session writes before optional computation. Analysis can never undo a saved move.
137 session_write_close();
138 $out['feedback']=null;
139 try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
140 catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
141 }
142 jsonOut($out);
133 143 } catch (Throwable $e) {
134 144 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
135 145 if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
@@ -110,7 +110,9 @@ try {
110 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
110 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
111 if ($action==='move') {
111 if ($action==='move') {
112 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
112 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
113 $before=$s;
113 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
114 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
115 $feedbackStates=[$before,$s];
114 $r=Chess::result($s);
116 $r=Chess::result($s);
115 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
117 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
116 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']]);
118 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']]);
@@ -129,7 +131,15 @@ try {
129 else throw new DomainException('Unknown action.');
131 else throw new DomainException('Unknown action.');
130 }
132 }
131 }
133 }
132 db()->exec('COMMIT');jsonOut($out);
134 db()->exec('COMMIT');
135 if (isset($feedbackStates)) {
136 // Release game/session writes before optional computation. Analysis can never undo a saved move.
137 session_write_close();
138 $out['feedback']=null;
139 try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
140 catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
141 }
142 jsonOut($out);
133} catch (Throwable $e) {
143} catch (Throwable $e) {
134 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
144 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
135 if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
145 if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
web/assets/app.css +1388 −10
@@ -1,13 +1,1391 @@
1 :root{--bg:#f5f3ed;--paper:#fffefb;--ink:#24352d;--muted:#7a8178;--green:#365d45;--line:#dedfd5;--lime:#d6e6a4;--dark-square:#8caa8c;--light-square:#e9edde}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,a,input{-webkit-tap-highlight-color:transparent}button,.button{font:inherit;cursor:pointer;border:0;border-radius:8px;padding:11px 16px;font-weight:600;transition:background .15s,transform .15s}button:hover,.button:hover{filter:brightness(.95)}button:disabled{cursor:default;opacity:.55}button:focus-visible,a:focus-visible,input:focus-visible{outline:3px solid #c19042;outline-offset:3px}a{color:inherit}h1,h2,h3,p{margin:0}h1{font-size:44px;letter-spacing:-2px;font-weight:650;line-height:1.2}h2{font-size:18px;letter-spacing:-.4px}h3{font-size:18px}.brand-dot{color:#789254}.topbar{height:88px;border-bottom:1px solid var(--line);display:flex;align-items:center;padding:0 44px;gap:38px;background:var(--paper)}.brand{display:flex;align-items:center;text-decoration:none;font-size:25px;font-weight:750;letter-spacing:-1.2px}.brandmark{background:var(--green);color:#fff;border-radius:10px;width:38px;height:38px;line-height:34px;text-align:center;margin-right:12px;font-family:Georgia,serif;font-size:30px;font-weight:700;position:relative}.brandmark span{font:14px system-ui;position:absolute;right:2px;top:0;color:var(--lime)}.tagline{font-size:13px;color:var(--muted)}.account-nav{margin-left:auto;display:flex;align-items:center;gap:8px}.quiet{background:transparent;color:var(--muted)}.layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;min-height:calc(100vh - 88px)}main{padding:44px;min-width:0}.page-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:43px}.eyebrow{font-size:10px;font-weight:750;letter-spacing:2px;color:var(--green);display:block;margin-bottom:12px}.page-heading p{color:var(--muted);margin-top:11px;font-size:14px}.primary,.button.primary{background:var(--green);color:white;box-shadow:0 2px 3px #24352d12;text-decoration:none;white-space:nowrap}.section-heading{display:flex;justify-content:space-between;align-items:center;margin:0 0 19px;gap:12px}.section-heading h2{display:flex;align-items:center;gap:10px}.section-heading>span{font-size:11px;color:var(--muted)}.status-dot{width:7px;height:7px;border-radius:50%;background:#688447;box-shadow:0 0 0 4px #6884470c}.muted-dot{background:#a7ada1}.count{font-size:11px;border:1px solid var(--line);border-radius:6px;padding:1px 7px;color:var(--muted);font-weight:500}.game-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:22px}.game-card{background:var(--paper);border:1px solid #dbdfd3;border-radius:13px;overflow:hidden;box-shadow:0 3px 5px #24352d04;min-width:0}.card-header{display:flex;align-items:center;gap:9px;padding:14px 16px;border-bottom:1px solid #e4e6dc}.avatar{width:31px;height:31px;display:grid;place-items:center;border-radius:50%;background:#e8ecdf;color:#56634b;font-size:11px;font-weight:750;flex-shrink:0}.card-header strong{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.color-tag{margin-left:auto;font-size:10px;display:flex;align-items:center;gap:5px;color:var(--muted)}.color-disc{width:9px;height:9px;border-radius:50%;background:white;border:1px solid #8d978b}.color-disc.black{background:#28382e;border-color:#28382e}.board-wrap{padding:15px;position:relative}.board{display:grid;grid-template-columns:repeat(4,1fr);border-radius:5px;overflow:hidden;aspect-ratio:4/5;touch-action:pan-y}.square{position:relative;aspect-ratio:1;background:var(--light-square);display:grid;place-items:center;border:0;border-radius:0;padding:0;min-width:0;touch-action:none}.square.dark{background:var(--dark-square)}.square:disabled{opacity:1;cursor:default}.square:hover{filter:none}.square img{width:82%;height:82%;pointer-events:none;user-select:none;filter:drop-shadow(0 2px 1px #00000016)}.square.selected{background:#d6d98b}.square.last:after{content:"";position:absolute;inset:0;background:#e6df5350;pointer-events:none}.square.selected:after{background:transparent}.square.legal:before{content:"";width:23%;height:23%;background:#294d4560;border-radius:50%;position:absolute;z-index:2;pointer-events:none}.square.legal.occupied:before{width:90%;height:90%;border:5px solid #294d4560;background:transparent}.square.checked{background:#ce8e77}.coordinate{position:absolute;bottom:2px;right:4px;font-size:9px;font-weight:600;color:#38543c;z-index:1;line-height:1}.rank{top:4px;left:4px;bottom:auto;right:auto}.card-footer{padding:0 16px 14px;display:flex;justify-content:space-between;align-items:center;gap:5px;color:var(--muted);font-size:11px}.card-footer .turn-label{color:var(--green);font-weight:600}.text-button{background:transparent;color:var(--green);padding:3px 0;font-size:12px}.waiting-heading{border-top:1px solid var(--line);padding-top:30px;margin-top:34px}.waiting .board{filter:saturate(.62)}.empty{grid-column:1/-1;min-height:200px;border:1px dashed #ced4c5;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:28px;color:var(--muted);gap:10px}.empty .empty-icon{font:40px Georgia;color:#859673}.empty h3{color:var(--ink);font-size:16px}.empty p{font-size:13px;max-width:340px}.pending-content,.end-content{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:15px;min-height:300px;padding:24px}.pending-content .big-icon,.end-content .big-icon{font-size:48px;font-family:Georgia;color:#759160}.pending-content p,.end-content p{font-size:13px;color:var(--muted)}.actions{display:flex;gap:10px;flex-wrap:wrap;justify-content:center}.secondary{background:#eaece3;color:var(--ink)}.danger{color:#9c4c3a;background:#f4e9e2}.end-content{min-height:0;aspect-ratio:4/5}.rematch-note{background:#edf2df;padding:8px;border-radius:7px}.promotion{position:absolute;inset:0;background:#fffefbf5;z-index:4;display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:18px;gap:15px}.promotion-options{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;width:100%}.promotion-options button{background:#edf0e5;display:flex;align-items:center;flex-direction:column;font-size:11px}.promotion-options img{height:54px;width:54px}.promotion p{font-size:12px;color:var(--muted)}aside{border-left:1px solid var(--line);padding:39px 25px;display:flex;flex-direction:column;background:#f0f0e8}.sidebar-heading{display:flex;align-items:center;justify-content:space-between}.sidebar-heading h2{font-size:22px;letter-spacing:-.8px}.sidebar-intro{font-size:12px;color:var(--muted);margin:8px 0 23px}.invite-friend{background:transparent;border:1px solid #cbd1bf;color:var(--green);text-align:left;font-size:12px;width:100%}.invite-friend span{float:right}.friends-label{font-size:10px;font-weight:700;letter-spacing:1.5px;margin:30px 0 15px;color:#858c7f;display:flex;justify-content:space-between}.friend{display:flex;gap:10px;align-items:center;width:100%;background:transparent;padding:11px 0;text-align:left;border-radius:6px}.friend .avatar{width:35px;height:35px}.friend strong{font-size:12px;display:block;max-width:165px;overflow:hidden;text-overflow:ellipsis}.friend small{display:block;font-size:10px;color:var(--muted);font-weight:400;margin-top:2px}.friend>span:last-child{margin-left:auto;color:#9aa38d}.sidebar-note{margin:auto 0 0;padding:65px 0 35px;text-align:center}.sidebar-note>span{font-size:46px;color:#879777}.sidebar-note h3{font-size:14px;margin:9px 0}.sidebar-note p{font-size:12px;color:var(--muted);line-height:1.8}#account-summary{border-top:1px solid var(--line);padding-top:18px;display:flex;align-items:center;gap:10px;font-size:12px}#account-summary small{display:block;font-size:10px;color:var(--muted)}footer{display:flex;align-items:center;gap:10px;color:#969b8f;font-size:10px;margin-top:40px}footer button{margin-left:auto}.mobile-friends,#friends-close{display:none}dialog{border:1px solid var(--line);border-radius:16px;background:var(--paper);color:var(--ink);padding:36px;width:min(460px,calc(100% - 32px));box-shadow:0 25px 80px #15231830}dialog::backdrop{background:#25352c66;backdrop-filter:blur(3px)}dialog h2{font-size:25px;margin-bottom:13px;letter-spacing:-1px}dialog p{font-size:14px;color:var(--muted);margin-bottom:20px}dialog .actions{justify-content:flex-start;margin-top:20px}.modal-close{position:absolute;right:8px;top:6px}dialog input{width:100%;border:1px solid var(--line);border-radius:6px;padding:12px;background:#f5f5ee;color:var(--ink)}.stats{display:grid;grid-template-columns:repeat(3,1fr);background:#eff1e7;border-radius:10px;padding:20px;margin:22px 0;text-align:center}.stats strong{display:block;font-size:27px}.stats span{font-size:11px;color:var(--muted)}.settings-actions{display:flex;flex-direction:column;gap:10px}.settings-actions a{text-align:center;text-decoration:none}#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);background:var(--ink);color:white;padding:13px 20px;border-radius:9px;z-index:20;max-width:calc(100% - 30px);font-size:13px;box-shadow:0 5px 25px #0002;display:none}#toast.visible{display:block}.login{max-width:900px;margin:10vh auto}.login h1{font-size:70px;line-height:1.05;margin:20px 0}.login p{font-size:18px;color:var(--muted);max-width:500px;margin-bottom:32px}.login .button{display:inline-flex;gap:25px}.login small{display:block;margin-top:16px;color:var(--muted)}.drag-ghost{position:fixed;width:65px;height:65px;pointer-events:none;z-index:50;transform:translate(-50%,-50%)}.rules-list{padding-left:20px;font-size:14px;color:var(--muted)}.rules-list li{margin-bottom:8px}.inline-note{font-size:11px;color:var(--muted)}
2 @media(min-width:1450px){.layout{grid-template-columns:minmax(0,1fr) 330px}main{padding:48px 60px}.game-grid{grid-template-columns:repeat(auto-fill,minmax(260px,1fr))}}
3 @media(max-width:1050px){main{padding:30px 25px}.topbar{padding:0 25px}.layout{grid-template-columns:minmax(0,1fr) 260px}aside{padding:30px 20px}.game-grid{gap:16px;grid-template-columns:repeat(auto-fill,minmax(210px,1fr))}.section-heading>span{display:none}}
4 @media(max-width:760px){.topbar{height:70px;padding:0 20px;position:sticky;top:0;z-index:7}.brand{font-size:22px}.brandmark{width:32px;height:32px;font-size:26px;line-height:29px;margin-right:9px}.tagline{display:none}.account-nav>.quiet{font-size:11px;padding:8px}.mobile-friends{display:block;background:#e7ecde;color:var(--green);font-size:12px;padding:9px 10px}.mobile-friends span{margin-left:5px}.layout{display:block}main{padding:30px 20px}h1{font-size:36px}.page-heading{align-items:flex-start;margin-bottom:30px;gap:10px}.page-heading>.primary{font-size:12px;padding:10px 12px;margin-top:27px}.page-heading p{font-size:12px;max-width:200px}.eyebrow{font-size:9px;letter-spacing:1.6px}.game-grid{grid-template-columns:minmax(0,1fr);gap:20px}.game-card{max-width:460px;width:100%;justify-self:center}.board-wrap{padding:18px}.card-header{padding:15px 18px}.card-header strong{font-size:14px}.card-footer{padding:0 18px 16px}.layout aside{position:fixed;right:0;top:0;bottom:0;width:min(320px,90vw);z-index:12;transform:translateX(100%);transition:transform .2s;overflow-y:auto}.layout aside.open{transform:translateX(0)}#friends-close{display:block}#sidebar-backdrop:not([hidden]){display:block;position:fixed;inset:0;background:#25352c66;z-index:11}footer{flex-wrap:wrap;font-size:9px}.login{padding:45px 25px;margin:4vh auto}.login h1{font-size:52px}.login p{font-size:16px}.sidebar-note{padding-top:40px}.section-heading h2{font-size:16px}.square img{max-width:90px}.end-content{aspect-ratio:auto;min-height:340px}}
5 @media(prefers-reduced-motion:reduce){*{transition:none!important}}
1 :root {
2 --bg: #f5f3ed;
3 --paper: #fffefb;
4 --ink: #24352d;
5 --muted: #7a8178;
6 --green: #365d45;
7 --line: #dedfd5;
8 --lime: #d6e6a4;
9 --dark-square: #8caa8c;
10 --light-square: #e9edde
11 }
6 12
7 @media(max-width:760px){body.sidebar-open{overflow:hidden}}
13 * {
14 box-sizing: border-box
15 }
8 16
9 .avatar img{width:90%;height:90%;object-fit:contain}#avatar-button{padding:0;color:inherit;outline-offset:4px;flex-shrink:0}#avatar-button:hover{background:#dce6cb;box-shadow:0 0 0 3px #dce6cb}dialog.avatar-picker{width:min(700px,calc(100% - 28px));max-height:calc(100dvh - 32px);overflow-y:auto}.avatar-filters{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:20px 0}.avatar-tabs{display:flex;gap:5px}.avatar-tabs button{font-size:12px;padding:8px 12px}.avatar-tabs button[aria-pressed=true]{background:var(--green);color:white}#avatar-color{font:inherit;font-size:12px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:7px;padding:8px;max-width:100%}.avatar-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(88px,1fr));gap:10px;max-height:390px;overflow-y:auto;padding:4px}.avatar-choice{display:flex;align-items:center;flex-direction:column;justify-content:center;gap:7px;min-height:108px;padding:9px 5px;background:#eff1e7;border:2px solid transparent;font-size:10px;line-height:1.3;font-weight:500}.avatar-choice img{width:54px;height:54px;object-fit:contain}.avatar-choice[aria-pressed=true]{border-color:var(--green);background:#dde8cc}.avatar-picker-footer{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-top:18px}dialog .avatar-credits{font-size:10px;margin:16px 0 0;line-height:1.6}.avatar-no-results{grid-column:1/-1;padding:25px 10px;text-align:center}#avatar-color:focus-visible{outline:3px solid #c19042;outline-offset:3px}@media(max-width:760px){dialog.avatar-picker{padding:30px 20px 22px}.avatar-choices{grid-template-columns:repeat(3,minmax(0,1fr));max-height:42dvh}.avatar-tabs button{padding:8px 10px;font-size:11px}}
17 body {
18 margin: 0;
19 background: var(--bg);
20 color: var(--ink);
21 font: 15px/1.5 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif
22 }
10 23
11 .ended-board{position:relative}.ended-board .end-content{position:absolute;left:15px;right:15px;top:50%;transform:translateY(-50%);min-height:0;aspect-ratio:auto;padding:12px 8px;display:flex;flex-direction:row;justify-content:space-between;gap:8px;text-align:left;background:rgb(255 254 251 / 12%);opacity:.22;transition:opacity .18s,background .18s}.end-content:hover,.end-content:focus-within{background:rgb(255 254 251 / 94%);opacity:1}.end-status{min-width:0}.end-status h3{font-size:13px;line-height:1.3}.end-status small{display:block;font-size:10px}.end-content .actions{flex-wrap:nowrap;gap:4px}.end-content button{font-size:10px;padding:8px 6px}.stop-inactive{margin-left:auto;background:#b73535;color:white;font-size:22px;line-height:1;padding:3px 7px;flex-shrink:0}.card-header:has(.stop-inactive) .color-tag{margin-left:auto}.card-header:has(.stop-inactive){gap:6px}
12 @media(hover:none){.ended-board .end-content{opacity:1;background:rgb(255 254 251 / 82%)}}
13 @media(min-width:761px){#sidebar{position:sticky;top:0;align-self:start;height:100dvh;overflow-y:auto;padding-top:24px;padding-bottom:105px}#sidebar>*{flex-shrink:0}#friend-list{flex:1 1 auto;min-height:60px;overflow-y:auto}.sidebar-note{padding:18px 0}.sidebar-note>span{font-size:30px}}
24 button,
25 a,
26 input {
27 -webkit-tap-highlight-color: transparent
28 }
29
30 button,
31 .button {
32 font: inherit;
33 cursor: pointer;
34 border: 0;
35 border-radius: 8px;
36 padding: 11px 16px;
37 font-weight: 600;
38 transition: background .15s, transform .15s
39 }
40
41 button:hover,
42 .button:hover {
43 filter: brightness(.95)
44 }
45
46 button:disabled {
47 cursor: default;
48 opacity: .55
49 }
50
51 button:focus-visible,
52 a:focus-visible,
53 input:focus-visible {
54 outline: 3px solid #c19042;
55 outline-offset: 3px
56 }
57
58 a {
59 color: inherit
60 }
61
62 h1,
63 h2,
64 h3,
65 p {
66 margin: 0
67 }
68
69 h1 {
70 font-size: 44px;
71 letter-spacing: -2px;
72 font-weight: 650;
73 line-height: 1.2
74 }
75
76 h2 {
77 font-size: 18px;
78 letter-spacing: -.4px
79 }
80
81 h3 {
82 font-size: 18px
83 }
84
85 .brand-dot {
86 color: #789254
87 }
88
89 .topbar {
90 height: 88px;
91 border-bottom: 1px solid var(--line);
92 display: flex;
93 align-items: center;
94 padding: 0 44px;
95 gap: 38px;
96 background: var(--paper)
97 }
98
99 .brand {
100 display: flex;
101 align-items: center;
102 text-decoration: none;
103 font-size: 25px;
104 font-weight: 750;
105 letter-spacing: -1.2px
106 }
107
108 .brandmark {
109 background: var(--green);
110 color: #fff;
111 border-radius: 10px;
112 width: 38px;
113 height: 38px;
114 line-height: 34px;
115 text-align: center;
116 margin-right: 12px;
117 font-family: Georgia, serif;
118 font-size: 30px;
119 font-weight: 700;
120 position: relative
121 }
122
123 .brandmark span {
124 font: 14px system-ui;
125 position: absolute;
126 right: 2px;
127 top: 0;
128 color: var(--lime)
129 }
130
131 .tagline {
132 font-size: 13px;
133 color: var(--muted)
134 }
135
136 .account-nav {
137 margin-left: auto;
138 display: flex;
139 align-items: center;
140 gap: 8px
141 }
142
143 .quiet {
144 background: transparent;
145 color: var(--muted)
146 }
147
148 .layout {
149 display: grid;
150 grid-template-columns: minmax(0, 1fr) 300px;
151 min-height: calc(100vh - 88px)
152 }
153
154 main {
155 padding: 44px;
156 min-width: 0
157 }
158
159 .page-heading {
160 display: flex;
161 justify-content: space-between;
162 align-items: center;
163 gap: 20px;
164 margin-bottom: 43px
165 }
166
167 .eyebrow {
168 font-size: 10px;
169 font-weight: 750;
170 letter-spacing: 2px;
171 color: var(--green);
172 display: block;
173 margin-bottom: 12px
174 }
175
176 .page-heading p {
177 color: var(--muted);
178 margin-top: 11px;
179 font-size: 14px
180 }
181
182 .primary,
183 .button.primary {
184 background: var(--green);
185 color: white;
186 box-shadow: 0 2px 3px #24352d12;
187 text-decoration: none;
188 white-space: nowrap
189 }
190
191 .section-heading {
192 display: flex;
193 justify-content: space-between;
194 align-items: center;
195 margin: 0 0 19px;
196 gap: 12px
197 }
198
199 .section-heading h2 {
200 display: flex;
201 align-items: center;
202 gap: 10px
203 }
204
205 .section-heading>span {
206 font-size: 11px;
207 color: var(--muted)
208 }
209
210 .status-dot {
211 width: 7px;
212 height: 7px;
213 border-radius: 50%;
214 background: #688447;
215 box-shadow: 0 0 0 4px #6884470c
216 }
217
218 .muted-dot {
219 background: #a7ada1
220 }
221
222 .count {
223 font-size: 11px;
224 border: 1px solid var(--line);
225 border-radius: 6px;
226 padding: 1px 7px;
227 color: var(--muted);
228 font-weight: 500
229 }
230
231 .game-grid {
232 display: grid;
233 grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
234 gap: 22px
235 }
236
237 .game-card {
238 background: var(--paper);
239 border: 1px solid #dbdfd3;
240 border-radius: 13px;
241 overflow: hidden;
242 box-shadow: 0 3px 5px #24352d04;
243 min-width: 0
244 }
245
246 .card-header {
247 display: flex;
248 align-items: center;
249 gap: 9px;
250 padding: 14px 16px;
251 border-bottom: 1px solid #e4e6dc
252 }
253
254 .avatar {
255 width: 31px;
256 height: 31px;
257 display: grid;
258 place-items: center;
259 border-radius: 50%;
260 background: #e8ecdf;
261 color: #56634b;
262 font-size: 11px;
263 font-weight: 750;
264 flex-shrink: 0
265 }
266
267 .card-header strong {
268 font-size: 13px;
269 overflow: hidden;
270 text-overflow: ellipsis;
271 white-space: nowrap
272 }
273
274 .color-tag {
275 margin-left: auto;
276 font-size: 10px;
277 display: flex;
278 align-items: center;
279 gap: 5px;
280 color: var(--muted)
281 }
282
283 .color-disc {
284 width: 9px;
285 height: 9px;
286 border-radius: 50%;
287 background: white;
288 border: 1px solid #8d978b
289 }
290
291 .color-disc.black {
292 background: #28382e;
293 border-color: #28382e
294 }
295
296 .board-wrap {
297 padding: 15px;
298 position: relative
299 }
300
301 .board {
302 display: grid;
303 grid-template-columns: repeat(4, 1fr);
304 border-radius: 5px;
305 overflow: hidden;
306 aspect-ratio: 4/5;
307 touch-action: pan-y
308 }
309
310 .square {
311 position: relative;
312 aspect-ratio: 1;
313 background: var(--light-square);
314 display: grid;
315 place-items: center;
316 border: 0;
317 border-radius: 0;
318 padding: 0;
319 min-width: 0;
320 touch-action: none
321 }
322
323 .square.dark {
324 background: var(--dark-square)
325 }
326
327 .square:disabled {
328 opacity: 1;
329 cursor: default
330 }
331
332 .square:hover {
333 filter: none
334 }
335
336 .square img {
337 width: 82%;
338 height: 82%;
339 pointer-events: none;
340 user-select: none;
341 filter: drop-shadow(0 2px 1px #00000016)
342 }
343
344 .square.selected {
345 background: #d6d98b
346 }
347
348 .square.last:after {
349 content: "";
350 position: absolute;
351 inset: 0;
352 background: #e6df5350;
353 pointer-events: none
354 }
355
356 .square.selected:after {
357 background: transparent
358 }
359
360 .square.legal:before {
361 content: "";
362 width: 23%;
363 height: 23%;
364 background: #294d4560;
365 border-radius: 50%;
366 position: absolute;
367 z-index: 2;
368 pointer-events: none
369 }
370
371 .square.legal.occupied:before {
372 width: 90%;
373 height: 90%;
374 border: 5px solid #294d4560;
375 background: transparent
376 }
377
378 .square.checked {
379 background: #ce8e77
380 }
381
382 .coordinate {
383 position: absolute;
384 bottom: 2px;
385 right: 4px;
386 font-size: 9px;
387 font-weight: 600;
388 color: #38543c;
389 z-index: 1;
390 line-height: 1
391 }
392
393 .rank {
394 top: 4px;
395 left: 4px;
396 bottom: auto;
397 right: auto
398 }
399
400 .card-footer {
401 padding: 0 16px 14px;
402 display: flex;
403 justify-content: space-between;
404 align-items: center;
405 gap: 5px;
406 color: var(--muted);
407 font-size: 11px
408 }
409
410 .card-footer .turn-label {
411 color: var(--green);
412 font-weight: 600
413 }
414
415 .text-button {
416 background: transparent;
417 color: var(--green);
418 padding: 3px 0;
419 font-size: 12px
420 }
421
422 .waiting-heading {
423 border-top: 1px solid var(--line);
424 padding-top: 30px;
425 margin-top: 34px
426 }
427
428 .waiting .board {
429 filter: saturate(.62)
430 }
431
432 .empty {
433 grid-column: 1/-1;
434 min-height: 200px;
435 border: 1px dashed #ced4c5;
436 border-radius: 12px;
437 display: flex;
438 flex-direction: column;
439 align-items: center;
440 justify-content: center;
441 text-align: center;
442 padding: 28px;
443 color: var(--muted);
444 gap: 10px
445 }
446
447 .empty .empty-icon {
448 font: 40px Georgia;
449 color: #859673
450 }
451
452 .empty h3 {
453 color: var(--ink);
454 font-size: 16px
455 }
456
457 .empty p {
458 font-size: 13px;
459 max-width: 340px
460 }
461
462 .pending-content,
463 .end-content {
464 display: flex;
465 flex-direction: column;
466 align-items: center;
467 justify-content: center;
468 text-align: center;
469 gap: 15px;
470 min-height: 300px;
471 padding: 24px
472 }
473
474 .pending-content .big-icon,
475 .end-content .big-icon {
476 font-size: 48px;
477 font-family: Georgia;
478 color: #759160
479 }
480
481 .pending-content p,
482 .end-content p {
483 font-size: 13px;
484 color: var(--muted)
485 }
486
487 .actions {
488 display: flex;
489 gap: 10px;
490 flex-wrap: wrap;
491 justify-content: center
492 }
493
494 .secondary {
495 background: #eaece3;
496 color: var(--ink)
497 }
498
499 .danger {
500 color: #9c4c3a;
501 background: #f4e9e2
502 }
503
504 .end-content {
505 min-height: 0;
506 aspect-ratio: 4/5
507 }
508
509 .rematch-note {
510 background: #edf2df;
511 padding: 8px;
512 border-radius: 7px
513 }
514
515 .promotion {
516 position: absolute;
517 inset: 0;
518 background: #fffefbf5;
519 z-index: 4;
520 display: flex;
521 align-items: center;
522 justify-content: center;
523 flex-direction: column;
524 text-align: center;
525 padding: 18px;
526 gap: 15px
527 }
528
529 .promotion-options {
530 display: grid;
531 grid-template-columns: repeat(2, 1fr);
532 gap: 10px;
533 width: 100%
534 }
535
536 .promotion-options button {
537 background: #edf0e5;
538 display: flex;
539 align-items: center;
540 flex-direction: column;
541 font-size: 11px
542 }
543
544 .promotion-options img {
545 height: 54px;
546 width: 54px
547 }
548
549 .promotion p {
550 font-size: 12px;
551 color: var(--muted)
552 }
553
554 aside {
555 border-left: 1px solid var(--line);
556 padding: 39px 25px;
557 display: flex;
558 flex-direction: column;
559 background: #f0f0e8
560 }
561
562 .sidebar-heading {
563 display: flex;
564 align-items: center;
565 justify-content: space-between
566 }
567
568 .sidebar-heading h2 {
569 font-size: 22px;
570 letter-spacing: -.8px
571 }
572
573 .sidebar-intro {
574 font-size: 12px;
575 color: var(--muted);
576 margin: 8px 0 23px
577 }
578
579 .invite-friend {
580 background: transparent;
581 border: 1px solid #cbd1bf;
582 color: var(--green);
583 text-align: left;
584 font-size: 12px;
585 width: 100%
586 }
587
588 .invite-friend span {
589 float: right
590 }
591
592 .friends-label {
593 font-size: 10px;
594 font-weight: 700;
595 letter-spacing: 1.5px;
596 margin: 30px 0 15px;
597 color: #858c7f;
598 display: flex;
599 justify-content: space-between
600 }
601
602 .friend {
603 display: flex;
604 gap: 10px;
605 align-items: center;
606 width: 100%;
607 background: transparent;
608 padding: 11px 0;
609 text-align: left;
610 border-radius: 6px
611 }
612
613 .friend .avatar {
614 width: 35px;
615 height: 35px
616 }
617
618 .friend strong {
619 font-size: 12px;
620 display: block;
621 max-width: 165px;
622 overflow: hidden;
623 text-overflow: ellipsis
624 }
625
626 .friend small {
627 display: block;
628 font-size: 10px;
629 color: var(--muted);
630 font-weight: 400;
631 margin-top: 2px
632 }
633
634 .friend>span:last-child {
635 margin-left: auto;
636 color: #9aa38d
637 }
638
639 .sidebar-note {
640 margin: auto 0 0;
641 padding: 65px 0 35px;
642 text-align: center
643 }
644
645 .sidebar-note>span {
646 font-size: 46px;
647 color: #879777
648 }
649
650 .sidebar-note h3 {
651 font-size: 14px;
652 margin: 9px 0
653 }
654
655 .sidebar-note p {
656 font-size: 12px;
657 color: var(--muted);
658 line-height: 1.8
659 }
660
661 #account-summary {
662 border-top: 1px solid var(--line);
663 padding-top: 18px;
664 display: flex;
665 align-items: center;
666 gap: 10px;
667 font-size: 12px
668 }
669
670 #account-summary small {
671 display: block;
672 font-size: 10px;
673 color: var(--muted)
674 }
675
676 footer {
677 display: flex;
678 align-items: center;
679 gap: 10px;
680 color: #969b8f;
681 font-size: 10px;
682 margin-top: 40px
683 }
684
685 footer button {
686 margin-left: auto
687 }
688
689 .mobile-friends,
690 #friends-close {
691 display: none
692 }
693
694 dialog {
695 border: 1px solid var(--line);
696 border-radius: 16px;
697 background: var(--paper);
698 color: var(--ink);
699 padding: 36px;
700 width: min(460px, calc(100% - 32px));
701 box-shadow: 0 25px 80px #15231830
702 }
703
704 dialog::backdrop {
705 background: #25352c66;
706 backdrop-filter: blur(3px)
707 }
708
709 dialog h2 {
710 font-size: 25px;
711 margin-bottom: 13px;
712 letter-spacing: -1px
713 }
714
715 dialog p {
716 font-size: 14px;
717 color: var(--muted);
718 margin-bottom: 20px
719 }
720
721 dialog .actions {
722 justify-content: flex-start;
723 margin-top: 20px
724 }
725
726 .modal-close {
727 position: absolute;
728 right: 8px;
729 top: 6px
730 }
731
732 dialog input {
733 width: 100%;
734 border: 1px solid var(--line);
735 border-radius: 6px;
736 padding: 12px;
737 background: #f5f5ee;
738 color: var(--ink)
739 }
740
741 .stats {
742 display: grid;
743 grid-template-columns: repeat(3, 1fr);
744 background: #eff1e7;
745 border-radius: 10px;
746 padding: 20px;
747 margin: 22px 0;
748 text-align: center
749 }
750
751 .stats strong {
752 display: block;
753 font-size: 27px
754 }
755
756 .stats span {
757 font-size: 11px;
758 color: var(--muted)
759 }
760
761 .settings-actions {
762 display: flex;
763 flex-direction: column;
764 gap: 10px
765 }
766
767 .settings-actions a {
768 text-align: center;
769 text-decoration: none
770 }
771
772 #toast {
773 position: fixed;
774 bottom: 22px;
775 left: 50%;
776 transform: translateX(-50%);
777 background: var(--ink);
778 color: white;
779 padding: 13px 20px;
780 border-radius: 9px;
781 z-index: 20;
782 max-width: calc(100% - 30px);
783 font-size: 13px;
784 box-shadow: 0 5px 25px #0002;
785 display: none
786 }
787
788 #toast.visible {
789 display: block
790 }
791
792 .login {
793 max-width: 900px;
794 margin: 10vh auto
795 }
796
797 .login h1 {
798 font-size: 70px;
799 line-height: 1.05;
800 margin: 20px 0
801 }
802
803 .login p {
804 font-size: 18px;
805 color: var(--muted);
806 max-width: 500px;
807 margin-bottom: 32px
808 }
809
810 .login .button {
811 display: inline-flex;
812 gap: 25px
813 }
814
815 .login small {
816 display: block;
817 margin-top: 16px;
818 color: var(--muted)
819 }
820
821 .drag-ghost {
822 position: fixed;
823 width: 65px;
824 height: 65px;
825 pointer-events: none;
826 z-index: 50;
827 transform: translate(-50%, -50%)
828 }
829
830 .rules-list {
831 padding-left: 20px;
832 font-size: 14px;
833 color: var(--muted)
834 }
835
836 .rules-list li {
837 margin-bottom: 8px
838 }
839
840 .inline-note {
841 font-size: 11px;
842 color: var(--muted)
843 }
844
845 @media(min-width:1450px) {
846 .layout {
847 grid-template-columns: minmax(0, 1fr) 330px
848 }
849
850 main {
851 padding: 48px 60px
852 }
853
854 .game-grid {
855 grid-template-columns: repeat(auto-fill, minmax(260px, 1fr))
856 }
857 }
858
859 @media(max-width:1050px) {
860 main {
861 padding: 30px 25px
862 }
863
864 .topbar {
865 padding: 0 25px
866 }
867
868 .layout {
869 grid-template-columns: minmax(0, 1fr) 260px
870 }
871
872 aside {
873 padding: 30px 20px
874 }
875
876 .game-grid {
877 gap: 16px;
878 grid-template-columns: repeat(auto-fill, minmax(210px, 1fr))
879 }
880
881 .section-heading>span {
882 display: none
883 }
884 }
885
886 @media(max-width:760px) {
887 .topbar {
888 height: 70px;
889 padding: 0 20px;
890 position: sticky;
891 top: 0;
892 z-index: 7
893 }
894
895 .brand {
896 font-size: 22px
897 }
898
899 .brandmark {
900 width: 32px;
901 height: 32px;
902 font-size: 26px;
903 line-height: 29px;
904 margin-right: 9px
905 }
906
907 .tagline {
908 display: none
909 }
910
911 .account-nav>.quiet {
912 font-size: 11px;
913 padding: 8px
914 }
915
916 .mobile-friends {
917 display: block;
918 background: #e7ecde;
919 color: var(--green);
920 font-size: 12px;
921 padding: 9px 10px
922 }
923
924 .mobile-friends span {
925 margin-left: 5px
926 }
927
928 .layout {
929 display: block
930 }
931
932 main {
933 padding: 30px 20px
934 }
935
936 h1 {
937 font-size: 36px
938 }
939
940 .page-heading {
941 align-items: flex-start;
942 margin-bottom: 30px;
943 gap: 10px
944 }
945
946 .page-heading>.primary {
947 font-size: 12px;
948 padding: 10px 12px;
949 margin-top: 27px
950 }
951
952 .page-heading p {
953 font-size: 12px;
954 max-width: 200px
955 }
956
957 .eyebrow {
958 font-size: 9px;
959 letter-spacing: 1.6px
960 }
961
962 .game-grid {
963 grid-template-columns: minmax(0, 1fr);
964 gap: 20px
965 }
966
967 .game-card {
968 max-width: 460px;
969 width: 100%;
970 justify-self: center
971 }
972
973 .board-wrap {
974 padding: 18px
975 }
976
977 .card-header {
978 padding: 15px 18px
979 }
980
981 .card-header strong {
982 font-size: 14px
983 }
984
985 .card-footer {
986 padding: 0 18px 16px
987 }
988
989 .layout aside {
990 position: fixed;
991 right: 0;
992 top: 0;
993 bottom: 0;
994 width: min(320px, 90vw);
995 z-index: 12;
996 transform: translateX(100%);
997 transition: transform .2s;
998 overflow-y: auto
999 }
1000
1001 .layout aside.open {
1002 transform: translateX(0)
1003 }
1004
1005 #friends-close {
1006 display: block
1007 }
1008
1009 #sidebar-backdrop:not([hidden]) {
1010 display: block;
1011 position: fixed;
1012 inset: 0;
1013 background: #25352c66;
1014 z-index: 11
1015 }
1016
1017 footer {
1018 flex-wrap: wrap;
1019 font-size: 9px
1020 }
1021
1022 .login {
1023 padding: 45px 25px;
1024 margin: 4vh auto
1025 }
1026
1027 .login h1 {
1028 font-size: 52px
1029 }
1030
1031 .login p {
1032 font-size: 16px
1033 }
1034
1035 .sidebar-note {
1036 padding-top: 40px
1037 }
1038
1039 .section-heading h2 {
1040 font-size: 16px
1041 }
1042
1043 .square img {
1044 max-width: 90px
1045 }
1046
1047 .end-content {
1048 aspect-ratio: auto;
1049 min-height: 340px
1050 }
1051 }
1052
1053 @media(prefers-reduced-motion:reduce) {
1054 * {
1055 transition: none !important
1056 }
1057 }
1058
1059 @media(max-width:760px) {
1060 body.sidebar-open {
1061 overflow: hidden
1062 }
1063 }
1064
1065 .avatar img {
1066 width: 90%;
1067 height: 90%;
1068 object-fit: contain
1069 }
1070
1071 #avatar-button {
1072 padding: 0;
1073 color: inherit;
1074 outline-offset: 4px;
1075 flex-shrink: 0
1076 }
1077
1078 #avatar-button:hover {
1079 background: #dce6cb;
1080 box-shadow: 0 0 0 3px #dce6cb
1081 }
1082
1083 dialog.avatar-picker {
1084 width: min(700px, calc(100% - 28px));
1085 max-height: calc(100dvh - 32px);
1086 overflow-y: auto
1087 }
1088
1089 .avatar-filters {
1090 display: flex;
1091 align-items: center;
1092 justify-content: space-between;
1093 gap: 12px;
1094 flex-wrap: wrap;
1095 margin: 20px 0
1096 }
1097
1098 .avatar-tabs {
1099 display: flex;
1100 gap: 5px
1101 }
1102
1103 .avatar-tabs button {
1104 font-size: 12px;
1105 padding: 8px 12px
1106 }
1107
1108 .avatar-tabs button[aria-pressed=true] {
1109 background: var(--green);
1110 color: white
1111 }
1112
1113 #avatar-color {
1114 font: inherit;
1115 font-size: 12px;
1116 color: var(--ink);
1117 background: var(--paper);
1118 border: 1px solid var(--line);
1119 border-radius: 7px;
1120 padding: 8px;
1121 max-width: 100%
1122 }
1123
1124 .avatar-choices {
1125 display: grid;
1126 grid-template-columns: repeat(auto-fill, minmax(88px, 1fr));
1127 gap: 10px;
1128 max-height: 390px;
1129 overflow-y: auto;
1130 padding: 4px
1131 }
1132
1133 .avatar-choice {
1134 display: flex;
1135 align-items: center;
1136 flex-direction: column;
1137 justify-content: center;
1138 gap: 7px;
1139 min-height: 108px;
1140 padding: 9px 5px;
1141 background: #eff1e7;
1142 border: 2px solid transparent;
1143 font-size: 10px;
1144 line-height: 1.3;
1145 font-weight: 500
1146 }
1147
1148 .avatar-choice img {
1149 width: 54px;
1150 height: 54px;
1151 object-fit: contain
1152 }
1153
1154 .avatar-choice[aria-pressed=true] {
1155 border-color: var(--green);
1156 background: #dde8cc
1157 }
1158
1159 .avatar-picker-footer {
1160 display: flex;
1161 justify-content: space-between;
1162 align-items: center;
1163 gap: 15px;
1164 margin-top: 18px
1165 }
1166
1167 dialog .avatar-credits {
1168 font-size: 10px;
1169 margin: 16px 0 0;
1170 line-height: 1.6
1171 }
1172
1173 .avatar-no-results {
1174 grid-column: 1/-1;
1175 padding: 25px 10px;
1176 text-align: center
1177 }
1178
1179 #avatar-color:focus-visible {
1180 outline: 3px solid #c19042;
1181 outline-offset: 3px
1182 }
1183
1184 @media(max-width:760px) {
1185 dialog.avatar-picker {
1186 padding: 30px 20px 22px
1187 }
1188
1189 .avatar-choices {
1190 grid-template-columns: repeat(3, minmax(0, 1fr));
1191 max-height: 42dvh
1192 }
1193
1194 .avatar-tabs button {
1195 padding: 8px 10px;
1196 font-size: 11px
1197 }
1198 }
1199
1200 .ended-board {
1201 position: relative
1202 }
1203
1204 .ended-board .end-content {
1205 position: absolute;
1206 left: 15px;
1207 right: 15px;
1208 top: 50%;
1209 transform: translateY(-50%);
1210 min-height: 0;
1211 aspect-ratio: auto;
1212 padding: 12px 8px;
1213 display: flex;
1214 flex-direction: row;
1215 justify-content: space-between;
1216 gap: 8px;
1217 text-align: left;
1218 background: rgb(255 254 251 / 82%);
1219 opacity: .72;
1220 transition: opacity .72s, background .18s
1221 }
1222
1223 .end-content:hover,
1224 .end-content:focus-within {
1225 background: rgb(255 254 251 / 94%);
1226 opacity: 1
1227 }
1228
1229 .end-status {
1230 min-width: 0
1231 }
1232
1233 .end-status h3 {
1234 font-size: 13px;
1235 line-height: 1.3
1236 }
1237
1238 .end-status small {
1239 display: block;
1240 font-size: 10px
1241 }
1242
1243 .end-content .actions {
1244 flex-wrap: nowrap;
1245 gap: 4px
1246 }
1247
1248 .end-content button {
1249 font-size: 10px;
1250 padding: 8px 6px
1251 }
1252
1253 .stop-inactive {
1254 margin-left: auto;
1255 background: #b73535;
1256 color: white;
1257 font-size: 22px;
1258 line-height: 1;
1259 padding: 3px 7px;
1260 flex-shrink: 0
1261 }
1262
1263 .card-header:has(.stop-inactive) .color-tag {
1264 margin-left: auto
1265 }
1266
1267 .card-header:has(.stop-inactive) {
1268 gap: 6px
1269 }
1270
1271 @media(hover:none) {
1272 .ended-board .end-content {
1273 opacity: 1;
1274 background: rgb(255 254 251 / 82%)
1275 }
1276 }
1277
1278 @media(min-width:761px) {
1279 #sidebar {
1280 position: sticky;
1281 top: 0;
1282 align-self: start;
1283 height: 100dvh;
1284 overflow-y: auto;
1285 padding-top: 24px;
1286 padding-bottom: 105px
1287 }
1288
1289 #sidebar>* {
1290 flex-shrink: 0
1291 }
1292
1293 #friend-list {
1294 flex: 1 1 auto;
1295 min-height: 60px;
1296 overflow-y: auto
1297 }
1298
1299 .sidebar-note {
1300 padding: 18px 0
1301 }
1302
1303 .sidebar-note>span {
1304 font-size: 30px
1305 }
1306 }
1307
1308 /* One-time tactical move feedback. */
1309 .game-card {
1310 position: relative
1311 }
1312
1313 .move-feedback {
1314 position: absolute;
1315 inset: 0;
1316 z-index: 5;
1317 pointer-events: none;
1318 border-radius: 12px;
1319 border: 3px solid var(--feedback);
1320 box-shadow: inset 0 0 38px var(--feedback-glow);
1321 background: var(--feedback-tint);
1322 opacity: 0
1323 }
1324
1325 .move-feedback.good {
1326 --feedback: #3188ea;
1327 --feedback-glow: #3188ea77;
1328 --feedback-tint: #3188ea16
1329 }
1330
1331 .move-feedback.poor {
1332 --feedback: #d94a48;
1333 --feedback-glow: #d94a4890;
1334 --feedback-tint: #d94a4818
1335 }
1336
1337 .move-quality {
1338 position: absolute;
1339 bottom: 38px;
1340 right: 10px;
1341 padding: 6px 10px;
1342 border-radius: 7px;
1343 background: var(--paper);
1344 border-left: 4px solid var(--feedback);
1345 color: var(--ink);
1346 font-size: 12px;
1347 font-weight: 700;
1348 box-shadow: 0 2px 12px #0002
1349 }
1350
1351 .move-quality small {
1352 display: block;
1353 font-size: 9px;
1354 font-weight: 400;
1355 color: var(--muted)
1356 }
1357
1358 /* Remaining material, with White always on the left. */
1359 .opponent-info {
1360 flex: 1;
1361 min-width: 0
1362 }
1363
1364 .opponent-info strong {
1365 display: block
1366 }
1367
1368 .material-bar {
1369 height: 7px;
1370 max-width: 160px;
1371 margin-top: 5px;
1372 border: 1px solid #879187;
1373 border-radius: 5px;
1374 background: #202823;
1375 overflow: hidden;
1376 direction: ltr
1377 }
1378
1379 .material-white {
1380 display: block;
1381 width: 100%;
1382 height: 100%;
1383 background: #fffefb;
1384 transform: scaleX(.5);
1385 transform-origin: left center
1386 }
1387
1388 .material-bar:focus-visible {
1389 outline: 2px solid #c19042;
1390 outline-offset: 3px
1391 }
@@ -1,13 +1,1391 @@
1:root{--bg:#f5f3ed;--paper:#fffefb;--ink:#24352d;--muted:#7a8178;--green:#365d45;--line:#dedfd5;--lime:#d6e6a4;--dark-square:#8caa8c;--light-square:#e9edde}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,a,input{-webkit-tap-highlight-color:transparent}button,.button{font:inherit;cursor:pointer;border:0;border-radius:8px;padding:11px 16px;font-weight:600;transition:background .15s,transform .15s}button:hover,.button:hover{filter:brightness(.95)}button:disabled{cursor:default;opacity:.55}button:focus-visible,a:focus-visible,input:focus-visible{outline:3px solid #c19042;outline-offset:3px}a{color:inherit}h1,h2,h3,p{margin:0}h1{font-size:44px;letter-spacing:-2px;font-weight:650;line-height:1.2}h2{font-size:18px;letter-spacing:-.4px}h3{font-size:18px}.brand-dot{color:#789254}.topbar{height:88px;border-bottom:1px solid var(--line);display:flex;align-items:center;padding:0 44px;gap:38px;background:var(--paper)}.brand{display:flex;align-items:center;text-decoration:none;font-size:25px;font-weight:750;letter-spacing:-1.2px}.brandmark{background:var(--green);color:#fff;border-radius:10px;width:38px;height:38px;line-height:34px;text-align:center;margin-right:12px;font-family:Georgia,serif;font-size:30px;font-weight:700;position:relative}.brandmark span{font:14px system-ui;position:absolute;right:2px;top:0;color:var(--lime)}.tagline{font-size:13px;color:var(--muted)}.account-nav{margin-left:auto;display:flex;align-items:center;gap:8px}.quiet{background:transparent;color:var(--muted)}.layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;min-height:calc(100vh - 88px)}main{padding:44px;min-width:0}.page-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:43px}.eyebrow{font-size:10px;font-weight:750;letter-spacing:2px;color:var(--green);display:block;margin-bottom:12px}.page-heading p{color:var(--muted);margin-top:11px;font-size:14px}.primary,.button.primary{background:var(--green);color:white;box-shadow:0 2px 3px #24352d12;text-decoration:none;white-space:nowrap}.section-heading{display:flex;justify-content:space-between;align-items:center;margin:0 0 19px;gap:12px}.section-heading h2{display:flex;align-items:center;gap:10px}.section-heading>span{font-size:11px;color:var(--muted)}.status-dot{width:7px;height:7px;border-radius:50%;background:#688447;box-shadow:0 0 0 4px #6884470c}.muted-dot{background:#a7ada1}.count{font-size:11px;border:1px solid var(--line);border-radius:6px;padding:1px 7px;color:var(--muted);font-weight:500}.game-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:22px}.game-card{background:var(--paper);border:1px solid #dbdfd3;border-radius:13px;overflow:hidden;box-shadow:0 3px 5px #24352d04;min-width:0}.card-header{display:flex;align-items:center;gap:9px;padding:14px 16px;border-bottom:1px solid #e4e6dc}.avatar{width:31px;height:31px;display:grid;place-items:center;border-radius:50%;background:#e8ecdf;color:#56634b;font-size:11px;font-weight:750;flex-shrink:0}.card-header strong{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.color-tag{margin-left:auto;font-size:10px;display:flex;align-items:center;gap:5px;color:var(--muted)}.color-disc{width:9px;height:9px;border-radius:50%;background:white;border:1px solid #8d978b}.color-disc.black{background:#28382e;border-color:#28382e}.board-wrap{padding:15px;position:relative}.board{display:grid;grid-template-columns:repeat(4,1fr);border-radius:5px;overflow:hidden;aspect-ratio:4/5;touch-action:pan-y}.square{position:relative;aspect-ratio:1;background:var(--light-square);display:grid;place-items:center;border:0;border-radius:0;padding:0;min-width:0;touch-action:none}.square.dark{background:var(--dark-square)}.square:disabled{opacity:1;cursor:default}.square:hover{filter:none}.square img{width:82%;height:82%;pointer-events:none;user-select:none;filter:drop-shadow(0 2px 1px #00000016)}.square.selected{background:#d6d98b}.square.last:after{content:"";position:absolute;inset:0;background:#e6df5350;pointer-events:none}.square.selected:after{background:transparent}.square.legal:before{content:"";width:23%;height:23%;background:#294d4560;border-radius:50%;position:absolute;z-index:2;pointer-events:none}.square.legal.occupied:before{width:90%;height:90%;border:5px solid #294d4560;background:transparent}.square.checked{background:#ce8e77}.coordinate{position:absolute;bottom:2px;right:4px;font-size:9px;font-weight:600;color:#38543c;z-index:1;line-height:1}.rank{top:4px;left:4px;bottom:auto;right:auto}.card-footer{padding:0 16px 14px;display:flex;justify-content:space-between;align-items:center;gap:5px;color:var(--muted);font-size:11px}.card-footer .turn-label{color:var(--green);font-weight:600}.text-button{background:transparent;color:var(--green);padding:3px 0;font-size:12px}.waiting-heading{border-top:1px solid var(--line);padding-top:30px;margin-top:34px}.waiting .board{filter:saturate(.62)}.empty{grid-column:1/-1;min-height:200px;border:1px dashed #ced4c5;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:28px;color:var(--muted);gap:10px}.empty .empty-icon{font:40px Georgia;color:#859673}.empty h3{color:var(--ink);font-size:16px}.empty p{font-size:13px;max-width:340px}.pending-content,.end-content{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:15px;min-height:300px;padding:24px}.pending-content .big-icon,.end-content .big-icon{font-size:48px;font-family:Georgia;color:#759160}.pending-content p,.end-content p{font-size:13px;color:var(--muted)}.actions{display:flex;gap:10px;flex-wrap:wrap;justify-content:center}.secondary{background:#eaece3;color:var(--ink)}.danger{color:#9c4c3a;background:#f4e9e2}.end-content{min-height:0;aspect-ratio:4/5}.rematch-note{background:#edf2df;padding:8px;border-radius:7px}.promotion{position:absolute;inset:0;background:#fffefbf5;z-index:4;display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:18px;gap:15px}.promotion-options{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;width:100%}.promotion-options button{background:#edf0e5;display:flex;align-items:center;flex-direction:column;font-size:11px}.promotion-options img{height:54px;width:54px}.promotion p{font-size:12px;color:var(--muted)}aside{border-left:1px solid var(--line);padding:39px 25px;display:flex;flex-direction:column;background:#f0f0e8}.sidebar-heading{display:flex;align-items:center;justify-content:space-between}.sidebar-heading h2{font-size:22px;letter-spacing:-.8px}.sidebar-intro{font-size:12px;color:var(--muted);margin:8px 0 23px}.invite-friend{background:transparent;border:1px solid #cbd1bf;color:var(--green);text-align:left;font-size:12px;width:100%}.invite-friend span{float:right}.friends-label{font-size:10px;font-weight:700;letter-spacing:1.5px;margin:30px 0 15px;color:#858c7f;display:flex;justify-content:space-between}.friend{display:flex;gap:10px;align-items:center;width:100%;background:transparent;padding:11px 0;text-align:left;border-radius:6px}.friend .avatar{width:35px;height:35px}.friend strong{font-size:12px;display:block;max-width:165px;overflow:hidden;text-overflow:ellipsis}.friend small{display:block;font-size:10px;color:var(--muted);font-weight:400;margin-top:2px}.friend>span:last-child{margin-left:auto;color:#9aa38d}.sidebar-note{margin:auto 0 0;padding:65px 0 35px;text-align:center}.sidebar-note>span{font-size:46px;color:#879777}.sidebar-note h3{font-size:14px;margin:9px 0}.sidebar-note p{font-size:12px;color:var(--muted);line-height:1.8}#account-summary{border-top:1px solid var(--line);padding-top:18px;display:flex;align-items:center;gap:10px;font-size:12px}#account-summary small{display:block;font-size:10px;color:var(--muted)}footer{display:flex;align-items:center;gap:10px;color:#969b8f;font-size:10px;margin-top:40px}footer button{margin-left:auto}.mobile-friends,#friends-close{display:none}dialog{border:1px solid var(--line);border-radius:16px;background:var(--paper);color:var(--ink);padding:36px;width:min(460px,calc(100% - 32px));box-shadow:0 25px 80px #15231830}dialog::backdrop{background:#25352c66;backdrop-filter:blur(3px)}dialog h2{font-size:25px;margin-bottom:13px;letter-spacing:-1px}dialog p{font-size:14px;color:var(--muted);margin-bottom:20px}dialog .actions{justify-content:flex-start;margin-top:20px}.modal-close{position:absolute;right:8px;top:6px}dialog input{width:100%;border:1px solid var(--line);border-radius:6px;padding:12px;background:#f5f5ee;color:var(--ink)}.stats{display:grid;grid-template-columns:repeat(3,1fr);background:#eff1e7;border-radius:10px;padding:20px;margin:22px 0;text-align:center}.stats strong{display:block;font-size:27px}.stats span{font-size:11px;color:var(--muted)}.settings-actions{display:flex;flex-direction:column;gap:10px}.settings-actions a{text-align:center;text-decoration:none}#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);background:var(--ink);color:white;padding:13px 20px;border-radius:9px;z-index:20;max-width:calc(100% - 30px);font-size:13px;box-shadow:0 5px 25px #0002;display:none}#toast.visible{display:block}.login{max-width:900px;margin:10vh auto}.login h1{font-size:70px;line-height:1.05;margin:20px 0}.login p{font-size:18px;color:var(--muted);max-width:500px;margin-bottom:32px}.login .button{display:inline-flex;gap:25px}.login small{display:block;margin-top:16px;color:var(--muted)}.drag-ghost{position:fixed;width:65px;height:65px;pointer-events:none;z-index:50;transform:translate(-50%,-50%)}.rules-list{padding-left:20px;font-size:14px;color:var(--muted)}.rules-list li{margin-bottom:8px}.inline-note{font-size:11px;color:var(--muted)}
1:root {
2@media(min-width:1450px){.layout{grid-template-columns:minmax(0,1fr) 330px}main{padding:48px 60px}.game-grid{grid-template-columns:repeat(auto-fill,minmax(260px,1fr))}}
2 --bg: #f5f3ed;
3@media(max-width:1050px){main{padding:30px 25px}.topbar{padding:0 25px}.layout{grid-template-columns:minmax(0,1fr) 260px}aside{padding:30px 20px}.game-grid{gap:16px;grid-template-columns:repeat(auto-fill,minmax(210px,1fr))}.section-heading>span{display:none}}
3 --paper: #fffefb;
4@media(max-width:760px){.topbar{height:70px;padding:0 20px;position:sticky;top:0;z-index:7}.brand{font-size:22px}.brandmark{width:32px;height:32px;font-size:26px;line-height:29px;margin-right:9px}.tagline{display:none}.account-nav>.quiet{font-size:11px;padding:8px}.mobile-friends{display:block;background:#e7ecde;color:var(--green);font-size:12px;padding:9px 10px}.mobile-friends span{margin-left:5px}.layout{display:block}main{padding:30px 20px}h1{font-size:36px}.page-heading{align-items:flex-start;margin-bottom:30px;gap:10px}.page-heading>.primary{font-size:12px;padding:10px 12px;margin-top:27px}.page-heading p{font-size:12px;max-width:200px}.eyebrow{font-size:9px;letter-spacing:1.6px}.game-grid{grid-template-columns:minmax(0,1fr);gap:20px}.game-card{max-width:460px;width:100%;justify-self:center}.board-wrap{padding:18px}.card-header{padding:15px 18px}.card-header strong{font-size:14px}.card-footer{padding:0 18px 16px}.layout aside{position:fixed;right:0;top:0;bottom:0;width:min(320px,90vw);z-index:12;transform:translateX(100%);transition:transform .2s;overflow-y:auto}.layout aside.open{transform:translateX(0)}#friends-close{display:block}#sidebar-backdrop:not([hidden]){display:block;position:fixed;inset:0;background:#25352c66;z-index:11}footer{flex-wrap:wrap;font-size:9px}.login{padding:45px 25px;margin:4vh auto}.login h1{font-size:52px}.login p{font-size:16px}.sidebar-note{padding-top:40px}.section-heading h2{font-size:16px}.square img{max-width:90px}.end-content{aspect-ratio:auto;min-height:340px}}
4 --ink: #24352d;
5@media(prefers-reduced-motion:reduce){*{transition:none!important}}
5 --muted: #7a8178;
6 --green: #365d45;
7 --line: #dedfd5;
8 --lime: #d6e6a4;
9 --dark-square: #8caa8c;
10 --light-square: #e9edde
11}
6
12
7@media(max-width:760px){body.sidebar-open{overflow:hidden}}
13* {
14 box-sizing: border-box
15}
8
16
9.avatar img{width:90%;height:90%;object-fit:contain}#avatar-button{padding:0;color:inherit;outline-offset:4px;flex-shrink:0}#avatar-button:hover{background:#dce6cb;box-shadow:0 0 0 3px #dce6cb}dialog.avatar-picker{width:min(700px,calc(100% - 28px));max-height:calc(100dvh - 32px);overflow-y:auto}.avatar-filters{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:20px 0}.avatar-tabs{display:flex;gap:5px}.avatar-tabs button{font-size:12px;padding:8px 12px}.avatar-tabs button[aria-pressed=true]{background:var(--green);color:white}#avatar-color{font:inherit;font-size:12px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:7px;padding:8px;max-width:100%}.avatar-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(88px,1fr));gap:10px;max-height:390px;overflow-y:auto;padding:4px}.avatar-choice{display:flex;align-items:center;flex-direction:column;justify-content:center;gap:7px;min-height:108px;padding:9px 5px;background:#eff1e7;border:2px solid transparent;font-size:10px;line-height:1.3;font-weight:500}.avatar-choice img{width:54px;height:54px;object-fit:contain}.avatar-choice[aria-pressed=true]{border-color:var(--green);background:#dde8cc}.avatar-picker-footer{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-top:18px}dialog .avatar-credits{font-size:10px;margin:16px 0 0;line-height:1.6}.avatar-no-results{grid-column:1/-1;padding:25px 10px;text-align:center}#avatar-color:focus-visible{outline:3px solid #c19042;outline-offset:3px}@media(max-width:760px){dialog.avatar-picker{padding:30px 20px 22px}.avatar-choices{grid-template-columns:repeat(3,minmax(0,1fr));max-height:42dvh}.avatar-tabs button{padding:8px 10px;font-size:11px}}
17body {
18 margin: 0;
19 background: var(--bg);
20 color: var(--ink);
21 font: 15px/1.5 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif
22}
10
23
11.ended-board{position:relative}.ended-board .end-content{position:absolute;left:15px;right:15px;top:50%;transform:translateY(-50%);min-height:0;aspect-ratio:auto;padding:12px 8px;display:flex;flex-direction:row;justify-content:space-between;gap:8px;text-align:left;background:rgb(255 254 251 / 12%);opacity:.22;transition:opacity .18s,background .18s}.end-content:hover,.end-content:focus-within{background:rgb(255 254 251 / 94%);opacity:1}.end-status{min-width:0}.end-status h3{font-size:13px;line-height:1.3}.end-status small{display:block;font-size:10px}.end-content .actions{flex-wrap:nowrap;gap:4px}.end-content button{font-size:10px;padding:8px 6px}.stop-inactive{margin-left:auto;background:#b73535;color:white;font-size:22px;line-height:1;padding:3px 7px;flex-shrink:0}.card-header:has(.stop-inactive) .color-tag{margin-left:auto}.card-header:has(.stop-inactive){gap:6px}
24button,
12@media(hover:none){.ended-board .end-content{opacity:1;background:rgb(255 254 251 / 82%)}}
25a,
13@media(min-width:761px){#sidebar{position:sticky;top:0;align-self:start;height:100dvh;overflow-y:auto;padding-top:24px;padding-bottom:105px}#sidebar>*{flex-shrink:0}#friend-list{flex:1 1 auto;min-height:60px;overflow-y:auto}.sidebar-note{padding:18px 0}.sidebar-note>span{font-size:30px}}
26input {
27 -webkit-tap-highlight-color: transparent
28}
29
30button,
31.button {
32 font: inherit;
33 cursor: pointer;
34 border: 0;
35 border-radius: 8px;
36 padding: 11px 16px;
37 font-weight: 600;
38 transition: background .15s, transform .15s
39}
40
41button:hover,
42.button:hover {
43 filter: brightness(.95)
44}
45
46button:disabled {
47 cursor: default;
48 opacity: .55
49}
50
51button:focus-visible,
52a:focus-visible,
53input:focus-visible {
54 outline: 3px solid #c19042;
55 outline-offset: 3px
56}
57
58a {
59 color: inherit
60}
61
62h1,
63h2,
64h3,
65p {
66 margin: 0
67}
68
69h1 {
70 font-size: 44px;
71 letter-spacing: -2px;
72 font-weight: 650;
73 line-height: 1.2
74}
75
76h2 {
77 font-size: 18px;
78 letter-spacing: -.4px
79}
80
81h3 {
82 font-size: 18px
83}
84
85.brand-dot {
86 color: #789254
87}
88
89.topbar {
90 height: 88px;
91 border-bottom: 1px solid var(--line);
92 display: flex;
93 align-items: center;
94 padding: 0 44px;
95 gap: 38px;
96 background: var(--paper)
97}
98
99.brand {
100 display: flex;
101 align-items: center;
102 text-decoration: none;
103 font-size: 25px;
104 font-weight: 750;
105 letter-spacing: -1.2px
106}
107
108.brandmark {
109 background: var(--green);
110 color: #fff;
111 border-radius: 10px;
112 width: 38px;
113 height: 38px;
114 line-height: 34px;
115 text-align: center;
116 margin-right: 12px;
117 font-family: Georgia, serif;
118 font-size: 30px;
119 font-weight: 700;
120 position: relative
121}
122
123.brandmark span {
124 font: 14px system-ui;
125 position: absolute;
126 right: 2px;
127 top: 0;
128 color: var(--lime)
129}
130
131.tagline {
132 font-size: 13px;
133 color: var(--muted)
134}
135
136.account-nav {
137 margin-left: auto;
138 display: flex;
139 align-items: center;
140 gap: 8px
141}
142
143.quiet {
144 background: transparent;
145 color: var(--muted)
146}
147
148.layout {
149 display: grid;
150 grid-template-columns: minmax(0, 1fr) 300px;
151 min-height: calc(100vh - 88px)
152}
153
154main {
155 padding: 44px;
156 min-width: 0
157}
158
159.page-heading {
160 display: flex;
161 justify-content: space-between;
162 align-items: center;
163 gap: 20px;
164 margin-bottom: 43px
165}
166
167.eyebrow {
168 font-size: 10px;
169 font-weight: 750;
170 letter-spacing: 2px;
171 color: var(--green);
172 display: block;
173 margin-bottom: 12px
174}
175
176.page-heading p {
177 color: var(--muted);
178 margin-top: 11px;
179 font-size: 14px
180}
181
182.primary,
183.button.primary {
184 background: var(--green);
185 color: white;
186 box-shadow: 0 2px 3px #24352d12;
187 text-decoration: none;
188 white-space: nowrap
189}
190
191.section-heading {
192 display: flex;
193 justify-content: space-between;
194 align-items: center;
195 margin: 0 0 19px;
196 gap: 12px
197}
198
199.section-heading h2 {
200 display: flex;
201 align-items: center;
202 gap: 10px
203}
204
205.section-heading>span {
206 font-size: 11px;
207 color: var(--muted)
208}
209
210.status-dot {
211 width: 7px;
212 height: 7px;
213 border-radius: 50%;
214 background: #688447;
215 box-shadow: 0 0 0 4px #6884470c
216}
217
218.muted-dot {
219 background: #a7ada1
220}
221
222.count {
223 font-size: 11px;
224 border: 1px solid var(--line);
225 border-radius: 6px;
226 padding: 1px 7px;
227 color: var(--muted);
228 font-weight: 500
229}
230
231.game-grid {
232 display: grid;
233 grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
234 gap: 22px
235}
236
237.game-card {
238 background: var(--paper);
239 border: 1px solid #dbdfd3;
240 border-radius: 13px;
241 overflow: hidden;
242 box-shadow: 0 3px 5px #24352d04;
243 min-width: 0
244}
245
246.card-header {
247 display: flex;
248 align-items: center;
249 gap: 9px;
250 padding: 14px 16px;
251 border-bottom: 1px solid #e4e6dc
252}
253
254.avatar {
255 width: 31px;
256 height: 31px;
257 display: grid;
258 place-items: center;
259 border-radius: 50%;
260 background: #e8ecdf;
261 color: #56634b;
262 font-size: 11px;
263 font-weight: 750;
264 flex-shrink: 0
265}
266
267.card-header strong {
268 font-size: 13px;
269 overflow: hidden;
270 text-overflow: ellipsis;
271 white-space: nowrap
272}
273
274.color-tag {
275 margin-left: auto;
276 font-size: 10px;
277 display: flex;
278 align-items: center;
279 gap: 5px;
280 color: var(--muted)
281}
282
283.color-disc {
284 width: 9px;
285 height: 9px;
286 border-radius: 50%;
287 background: white;
288 border: 1px solid #8d978b
289}
290
291.color-disc.black {
292 background: #28382e;
293 border-color: #28382e
294}
295
296.board-wrap {
297 padding: 15px;
298 position: relative
299}
300
301.board {
302 display: grid;
303 grid-template-columns: repeat(4, 1fr);
304 border-radius: 5px;
305 overflow: hidden;
306 aspect-ratio: 4/5;
307 touch-action: pan-y
308}
309
310.square {
311 position: relative;
312 aspect-ratio: 1;
313 background: var(--light-square);
314 display: grid;
315 place-items: center;
316 border: 0;
317 border-radius: 0;
318 padding: 0;
319 min-width: 0;
320 touch-action: none
321}
322
323.square.dark {
324 background: var(--dark-square)
325}
326
327.square:disabled {
328 opacity: 1;
329 cursor: default
330}
331
332.square:hover {
333 filter: none
334}
335
336.square img {
337 width: 82%;
338 height: 82%;
339 pointer-events: none;
340 user-select: none;
341 filter: drop-shadow(0 2px 1px #00000016)
342}
343
344.square.selected {
345 background: #d6d98b
346}
347
348.square.last:after {
349 content: "";
350 position: absolute;
351 inset: 0;
352 background: #e6df5350;
353 pointer-events: none
354}
355
356.square.selected:after {
357 background: transparent
358}
359
360.square.legal:before {
361 content: "";
362 width: 23%;
363 height: 23%;
364 background: #294d4560;
365 border-radius: 50%;
366 position: absolute;
367 z-index: 2;
368 pointer-events: none
369}
370
371.square.legal.occupied:before {
372 width: 90%;
373 height: 90%;
374 border: 5px solid #294d4560;
375 background: transparent
376}
377
378.square.checked {
379 background: #ce8e77
380}
381
382.coordinate {
383 position: absolute;
384 bottom: 2px;
385 right: 4px;
386 font-size: 9px;
387 font-weight: 600;
388 color: #38543c;
389 z-index: 1;
390 line-height: 1
391}
392
393.rank {
394 top: 4px;
395 left: 4px;
396 bottom: auto;
397 right: auto
398}
399
400.card-footer {
401 padding: 0 16px 14px;
402 display: flex;
403 justify-content: space-between;
404 align-items: center;
405 gap: 5px;
406 color: var(--muted);
407 font-size: 11px
408}
409
410.card-footer .turn-label {
411 color: var(--green);
412 font-weight: 600
413}
414
415.text-button {
416 background: transparent;
417 color: var(--green);
418 padding: 3px 0;
419 font-size: 12px
420}
421
422.waiting-heading {
423 border-top: 1px solid var(--line);
424 padding-top: 30px;
425 margin-top: 34px
426}
427
428.waiting .board {
429 filter: saturate(.62)
430}
431
432.empty {
433 grid-column: 1/-1;
434 min-height: 200px;
435 border: 1px dashed #ced4c5;
436 border-radius: 12px;
437 display: flex;
438 flex-direction: column;
439 align-items: center;
440 justify-content: center;
441 text-align: center;
442 padding: 28px;
443 color: var(--muted);
444 gap: 10px
445}
446
447.empty .empty-icon {
448 font: 40px Georgia;
449 color: #859673
450}
451
452.empty h3 {
453 color: var(--ink);
454 font-size: 16px
455}
456
457.empty p {
458 font-size: 13px;
459 max-width: 340px
460}
461
462.pending-content,
463.end-content {
464 display: flex;
465 flex-direction: column;
466 align-items: center;
467 justify-content: center;
468 text-align: center;
469 gap: 15px;
470 min-height: 300px;
471 padding: 24px
472}
473
474.pending-content .big-icon,
475.end-content .big-icon {
476 font-size: 48px;
477 font-family: Georgia;
478 color: #759160
479}
480
481.pending-content p,
482.end-content p {
483 font-size: 13px;
484 color: var(--muted)
485}
486
487.actions {
488 display: flex;
489 gap: 10px;
490 flex-wrap: wrap;
491 justify-content: center
492}
493
494.secondary {
495 background: #eaece3;
496 color: var(--ink)
497}
498
499.danger {
500 color: #9c4c3a;
501 background: #f4e9e2
502}
503
504.end-content {
505 min-height: 0;
506 aspect-ratio: 4/5
507}
508
509.rematch-note {
510 background: #edf2df;
511 padding: 8px;
512 border-radius: 7px
513}
514
515.promotion {
516 position: absolute;
517 inset: 0;
518 background: #fffefbf5;
519 z-index: 4;
520 display: flex;
521 align-items: center;
522 justify-content: center;
523 flex-direction: column;
524 text-align: center;
525 padding: 18px;
526 gap: 15px
527}
528
529.promotion-options {
530 display: grid;
531 grid-template-columns: repeat(2, 1fr);
532 gap: 10px;
533 width: 100%
534}
535
536.promotion-options button {
537 background: #edf0e5;
538 display: flex;
539 align-items: center;
540 flex-direction: column;
541 font-size: 11px
542}
543
544.promotion-options img {
545 height: 54px;
546 width: 54px
547}
548
549.promotion p {
550 font-size: 12px;
551 color: var(--muted)
552}
553
554aside {
555 border-left: 1px solid var(--line);
556 padding: 39px 25px;
557 display: flex;
558 flex-direction: column;
559 background: #f0f0e8
560}
561
562.sidebar-heading {
563 display: flex;
564 align-items: center;
565 justify-content: space-between
566}
567
568.sidebar-heading h2 {
569 font-size: 22px;
570 letter-spacing: -.8px
571}
572
573.sidebar-intro {
574 font-size: 12px;
575 color: var(--muted);
576 margin: 8px 0 23px
577}
578
579.invite-friend {
580 background: transparent;
581 border: 1px solid #cbd1bf;
582 color: var(--green);
583 text-align: left;
584 font-size: 12px;
585 width: 100%
586}
587
588.invite-friend span {
589 float: right
590}
591
592.friends-label {
593 font-size: 10px;
594 font-weight: 700;
595 letter-spacing: 1.5px;
596 margin: 30px 0 15px;
597 color: #858c7f;
598 display: flex;
599 justify-content: space-between
600}
601
602.friend {
603 display: flex;
604 gap: 10px;
605 align-items: center;
606 width: 100%;
607 background: transparent;
608 padding: 11px 0;
609 text-align: left;
610 border-radius: 6px
611}
612
613.friend .avatar {
614 width: 35px;
615 height: 35px
616}
617
618.friend strong {
619 font-size: 12px;
620 display: block;
621 max-width: 165px;
622 overflow: hidden;
623 text-overflow: ellipsis
624}
625
626.friend small {
627 display: block;
628 font-size: 10px;
629 color: var(--muted);
630 font-weight: 400;
631 margin-top: 2px
632}
633
634.friend>span:last-child {
635 margin-left: auto;
636 color: #9aa38d
637}
638
639.sidebar-note {
640 margin: auto 0 0;
641 padding: 65px 0 35px;
642 text-align: center
643}
644
645.sidebar-note>span {
646 font-size: 46px;
647 color: #879777
648}
649
650.sidebar-note h3 {
651 font-size: 14px;
652 margin: 9px 0
653}
654
655.sidebar-note p {
656 font-size: 12px;
657 color: var(--muted);
658 line-height: 1.8
659}
660
661#account-summary {
662 border-top: 1px solid var(--line);
663 padding-top: 18px;
664 display: flex;
665 align-items: center;
666 gap: 10px;
667 font-size: 12px
668}
669
670#account-summary small {
671 display: block;
672 font-size: 10px;
673 color: var(--muted)
674}
675
676footer {
677 display: flex;
678 align-items: center;
679 gap: 10px;
680 color: #969b8f;
681 font-size: 10px;
682 margin-top: 40px
683}
684
685footer button {
686 margin-left: auto
687}
688
689.mobile-friends,
690#friends-close {
691 display: none
692}
693
694dialog {
695 border: 1px solid var(--line);
696 border-radius: 16px;
697 background: var(--paper);
698 color: var(--ink);
699 padding: 36px;
700 width: min(460px, calc(100% - 32px));
701 box-shadow: 0 25px 80px #15231830
702}
703
704dialog::backdrop {
705 background: #25352c66;
706 backdrop-filter: blur(3px)
707}
708
709dialog h2 {
710 font-size: 25px;
711 margin-bottom: 13px;
712 letter-spacing: -1px
713}
714
715dialog p {
716 font-size: 14px;
717 color: var(--muted);
718 margin-bottom: 20px
719}
720
721dialog .actions {
722 justify-content: flex-start;
723 margin-top: 20px
724}
725
726.modal-close {
727 position: absolute;
728 right: 8px;
729 top: 6px
730}
731
732dialog input {
733 width: 100%;
734 border: 1px solid var(--line);
735 border-radius: 6px;
736 padding: 12px;
737 background: #f5f5ee;
738 color: var(--ink)
739}
740
741.stats {
742 display: grid;
743 grid-template-columns: repeat(3, 1fr);
744 background: #eff1e7;
745 border-radius: 10px;
746 padding: 20px;
747 margin: 22px 0;
748 text-align: center
749}
750
751.stats strong {
752 display: block;
753 font-size: 27px
754}
755
756.stats span {
757 font-size: 11px;
758 color: var(--muted)
759}
760
761.settings-actions {
762 display: flex;
763 flex-direction: column;
764 gap: 10px
765}
766
767.settings-actions a {
768 text-align: center;
769 text-decoration: none
770}
771
772#toast {
773 position: fixed;
774 bottom: 22px;
775 left: 50%;
776 transform: translateX(-50%);
777 background: var(--ink);
778 color: white;
779 padding: 13px 20px;
780 border-radius: 9px;
781 z-index: 20;
782 max-width: calc(100% - 30px);
783 font-size: 13px;
784 box-shadow: 0 5px 25px #0002;
785 display: none
786}
787
788#toast.visible {
789 display: block
790}
791
792.login {
793 max-width: 900px;
794 margin: 10vh auto
795}
796
797.login h1 {
798 font-size: 70px;
799 line-height: 1.05;
800 margin: 20px 0
801}
802
803.login p {
804 font-size: 18px;
805 color: var(--muted);
806 max-width: 500px;
807 margin-bottom: 32px
808}
809
810.login .button {
811 display: inline-flex;
812 gap: 25px
813}
814
815.login small {
816 display: block;
817 margin-top: 16px;
818 color: var(--muted)
819}
820
821.drag-ghost {
822 position: fixed;
823 width: 65px;
824 height: 65px;
825 pointer-events: none;
826 z-index: 50;
827 transform: translate(-50%, -50%)
828}
829
830.rules-list {
831 padding-left: 20px;
832 font-size: 14px;
833 color: var(--muted)
834}
835
836.rules-list li {
837 margin-bottom: 8px
838}
839
840.inline-note {
841 font-size: 11px;
842 color: var(--muted)
843}
844
845@media(min-width:1450px) {
846 .layout {
847 grid-template-columns: minmax(0, 1fr) 330px
848 }
849
850 main {
851 padding: 48px 60px
852 }
853
854 .game-grid {
855 grid-template-columns: repeat(auto-fill, minmax(260px, 1fr))
856 }
857}
858
859@media(max-width:1050px) {
860 main {
861 padding: 30px 25px
862 }
863
864 .topbar {
865 padding: 0 25px
866 }
867
868 .layout {
869 grid-template-columns: minmax(0, 1fr) 260px
870 }
871
872 aside {
873 padding: 30px 20px
874 }
875
876 .game-grid {
877 gap: 16px;
878 grid-template-columns: repeat(auto-fill, minmax(210px, 1fr))
879 }
880
881 .section-heading>span {
882 display: none
883 }
884}
885
886@media(max-width:760px) {
887 .topbar {
888 height: 70px;
889 padding: 0 20px;
890 position: sticky;
891 top: 0;
892 z-index: 7
893 }
894
895 .brand {
896 font-size: 22px
897 }
898
899 .brandmark {
900 width: 32px;
901 height: 32px;
902 font-size: 26px;
903 line-height: 29px;
904 margin-right: 9px
905 }
906
907 .tagline {
908 display: none
909 }
910
911 .account-nav>.quiet {
912 font-size: 11px;
913 padding: 8px
914 }
915
916 .mobile-friends {
917 display: block;
918 background: #e7ecde;
919 color: var(--green);
920 font-size: 12px;
921 padding: 9px 10px
922 }
923
924 .mobile-friends span {
925 margin-left: 5px
926 }
927
928 .layout {
929 display: block
930 }
931
932 main {
933 padding: 30px 20px
934 }
935
936 h1 {
937 font-size: 36px
938 }
939
940 .page-heading {
941 align-items: flex-start;
942 margin-bottom: 30px;
943 gap: 10px
944 }
945
946 .page-heading>.primary {
947 font-size: 12px;
948 padding: 10px 12px;
949 margin-top: 27px
950 }
951
952 .page-heading p {
953 font-size: 12px;
954 max-width: 200px
955 }
956
957 .eyebrow {
958 font-size: 9px;
959 letter-spacing: 1.6px
960 }
961
962 .game-grid {
963 grid-template-columns: minmax(0, 1fr);
964 gap: 20px
965 }
966
967 .game-card {
968 max-width: 460px;
969 width: 100%;
970 justify-self: center
971 }
972
973 .board-wrap {
974 padding: 18px
975 }
976
977 .card-header {
978 padding: 15px 18px
979 }
980
981 .card-header strong {
982 font-size: 14px
983 }
984
985 .card-footer {
986 padding: 0 18px 16px
987 }
988
989 .layout aside {
990 position: fixed;
991 right: 0;
992 top: 0;
993 bottom: 0;
994 width: min(320px, 90vw);
995 z-index: 12;
996 transform: translateX(100%);
997 transition: transform .2s;
998 overflow-y: auto
999 }
1000
1001 .layout aside.open {
1002 transform: translateX(0)
1003 }
1004
1005 #friends-close {
1006 display: block
1007 }
1008
1009 #sidebar-backdrop:not([hidden]) {
1010 display: block;
1011 position: fixed;
1012 inset: 0;
1013 background: #25352c66;
1014 z-index: 11
1015 }
1016
1017 footer {
1018 flex-wrap: wrap;
1019 font-size: 9px
1020 }
1021
1022 .login {
1023 padding: 45px 25px;
1024 margin: 4vh auto
1025 }
1026
1027 .login h1 {
1028 font-size: 52px
1029 }
1030
1031 .login p {
1032 font-size: 16px
1033 }
1034
1035 .sidebar-note {
1036 padding-top: 40px
1037 }
1038
1039 .section-heading h2 {
1040 font-size: 16px
1041 }
1042
1043 .square img {
1044 max-width: 90px
1045 }
1046
1047 .end-content {
1048 aspect-ratio: auto;
1049 min-height: 340px
1050 }
1051}
1052
1053@media(prefers-reduced-motion:reduce) {
1054 * {
1055 transition: none !important
1056 }
1057}
1058
1059@media(max-width:760px) {
1060 body.sidebar-open {
1061 overflow: hidden
1062 }
1063}
1064
1065.avatar img {
1066 width: 90%;
1067 height: 90%;
1068 object-fit: contain
1069}
1070
1071#avatar-button {
1072 padding: 0;
1073 color: inherit;
1074 outline-offset: 4px;
1075 flex-shrink: 0
1076}
1077
1078#avatar-button:hover {
1079 background: #dce6cb;
1080 box-shadow: 0 0 0 3px #dce6cb
1081}
1082
1083dialog.avatar-picker {
1084 width: min(700px, calc(100% - 28px));
1085 max-height: calc(100dvh - 32px);
1086 overflow-y: auto
1087}
1088
1089.avatar-filters {
1090 display: flex;
1091 align-items: center;
1092 justify-content: space-between;
1093 gap: 12px;
1094 flex-wrap: wrap;
1095 margin: 20px 0
1096}
1097
1098.avatar-tabs {
1099 display: flex;
1100 gap: 5px
1101}
1102
1103.avatar-tabs button {
1104 font-size: 12px;
1105 padding: 8px 12px
1106}
1107
1108.avatar-tabs button[aria-pressed=true] {
1109 background: var(--green);
1110 color: white
1111}
1112
1113#avatar-color {
1114 font: inherit;
1115 font-size: 12px;
1116 color: var(--ink);
1117 background: var(--paper);
1118 border: 1px solid var(--line);
1119 border-radius: 7px;
1120 padding: 8px;
1121 max-width: 100%
1122}
1123
1124.avatar-choices {
1125 display: grid;
1126 grid-template-columns: repeat(auto-fill, minmax(88px, 1fr));
1127 gap: 10px;
1128 max-height: 390px;
1129 overflow-y: auto;
1130 padding: 4px
1131}
1132
1133.avatar-choice {
1134 display: flex;
1135 align-items: center;
1136 flex-direction: column;
1137 justify-content: center;
1138 gap: 7px;
1139 min-height: 108px;
1140 padding: 9px 5px;
1141 background: #eff1e7;
1142 border: 2px solid transparent;
1143 font-size: 10px;
1144 line-height: 1.3;
1145 font-weight: 500
1146}
1147
1148.avatar-choice img {
1149 width: 54px;
1150 height: 54px;
1151 object-fit: contain
1152}
1153
1154.avatar-choice[aria-pressed=true] {
1155 border-color: var(--green);
1156 background: #dde8cc
1157}
1158
1159.avatar-picker-footer {
1160 display: flex;
1161 justify-content: space-between;
1162 align-items: center;
1163 gap: 15px;
1164 margin-top: 18px
1165}
1166
1167dialog .avatar-credits {
1168 font-size: 10px;
1169 margin: 16px 0 0;
1170 line-height: 1.6
1171}
1172
1173.avatar-no-results {
1174 grid-column: 1/-1;
1175 padding: 25px 10px;
1176 text-align: center
1177}
1178
1179#avatar-color:focus-visible {
1180 outline: 3px solid #c19042;
1181 outline-offset: 3px
1182}
1183
1184@media(max-width:760px) {
1185 dialog.avatar-picker {
1186 padding: 30px 20px 22px
1187 }
1188
1189 .avatar-choices {
1190 grid-template-columns: repeat(3, minmax(0, 1fr));
1191 max-height: 42dvh
1192 }
1193
1194 .avatar-tabs button {
1195 padding: 8px 10px;
1196 font-size: 11px
1197 }
1198}
1199
1200.ended-board {
1201 position: relative
1202}
1203
1204.ended-board .end-content {
1205 position: absolute;
1206 left: 15px;
1207 right: 15px;
1208 top: 50%;
1209 transform: translateY(-50%);
1210 min-height: 0;
1211 aspect-ratio: auto;
1212 padding: 12px 8px;
1213 display: flex;
1214 flex-direction: row;
1215 justify-content: space-between;
1216 gap: 8px;
1217 text-align: left;
1218 background: rgb(255 254 251 / 82%);
1219 opacity: .72;
1220 transition: opacity .72s, background .18s
1221}
1222
1223.end-content:hover,
1224.end-content:focus-within {
1225 background: rgb(255 254 251 / 94%);
1226 opacity: 1
1227}
1228
1229.end-status {
1230 min-width: 0
1231}
1232
1233.end-status h3 {
1234 font-size: 13px;
1235 line-height: 1.3
1236}
1237
1238.end-status small {
1239 display: block;
1240 font-size: 10px
1241}
1242
1243.end-content .actions {
1244 flex-wrap: nowrap;
1245 gap: 4px
1246}
1247
1248.end-content button {
1249 font-size: 10px;
1250 padding: 8px 6px
1251}
1252
1253.stop-inactive {
1254 margin-left: auto;
1255 background: #b73535;
1256 color: white;
1257 font-size: 22px;
1258 line-height: 1;
1259 padding: 3px 7px;
1260 flex-shrink: 0
1261}
1262
1263.card-header:has(.stop-inactive) .color-tag {
1264 margin-left: auto
1265}
1266
1267.card-header:has(.stop-inactive) {
1268 gap: 6px
1269}
1270
1271@media(hover:none) {
1272 .ended-board .end-content {
1273 opacity: 1;
1274 background: rgb(255 254 251 / 82%)
1275 }
1276}
1277
1278@media(min-width:761px) {
1279 #sidebar {
1280 position: sticky;
1281 top: 0;
1282 align-self: start;
1283 height: 100dvh;
1284 overflow-y: auto;
1285 padding-top: 24px;
1286 padding-bottom: 105px
1287 }
1288
1289 #sidebar>* {
1290 flex-shrink: 0
1291 }
1292
1293 #friend-list {
1294 flex: 1 1 auto;
1295 min-height: 60px;
1296 overflow-y: auto
1297 }
1298
1299 .sidebar-note {
1300 padding: 18px 0
1301 }
1302
1303 .sidebar-note>span {
1304 font-size: 30px
1305 }
1306}
1307
1308/* One-time tactical move feedback. */
1309.game-card {
1310 position: relative
1311}
1312
1313.move-feedback {
1314 position: absolute;
1315 inset: 0;
1316 z-index: 5;
1317 pointer-events: none;
1318 border-radius: 12px;
1319 border: 3px solid var(--feedback);
1320 box-shadow: inset 0 0 38px var(--feedback-glow);
1321 background: var(--feedback-tint);
1322 opacity: 0
1323}
1324
1325.move-feedback.good {
1326 --feedback: #3188ea;
1327 --feedback-glow: #3188ea77;
1328 --feedback-tint: #3188ea16
1329}
1330
1331.move-feedback.poor {
1332 --feedback: #d94a48;
1333 --feedback-glow: #d94a4890;
1334 --feedback-tint: #d94a4818
1335}
1336
1337.move-quality {
1338 position: absolute;
1339 bottom: 38px;
1340 right: 10px;
1341 padding: 6px 10px;
1342 border-radius: 7px;
1343 background: var(--paper);
1344 border-left: 4px solid var(--feedback);
1345 color: var(--ink);
1346 font-size: 12px;
1347 font-weight: 700;
1348 box-shadow: 0 2px 12px #0002
1349}
1350
1351.move-quality small {
1352 display: block;
1353 font-size: 9px;
1354 font-weight: 400;
1355 color: var(--muted)
1356}
1357
1358/* Remaining material, with White always on the left. */
1359.opponent-info {
1360 flex: 1;
1361 min-width: 0
1362}
1363
1364.opponent-info strong {
1365 display: block
1366}
1367
1368.material-bar {
1369 height: 7px;
1370 max-width: 160px;
1371 margin-top: 5px;
1372 border: 1px solid #879187;
1373 border-radius: 5px;
1374 background: #202823;
1375 overflow: hidden;
1376 direction: ltr
1377}
1378
1379.material-white {
1380 display: block;
1381 width: 100%;
1382 height: 100%;
1383 background: #fffefb;
1384 transform: scaleX(.5);
1385 transform-origin: left center
1386}
1387
1388.material-bar:focus-visible {
1389 outline: 2px solid #c19042;
1390 outline-offset: 3px
1391}
web/assets/app.js +279 −189
@@ -1,231 +1,321 @@
1 1 'use strict';
2 2 const $ = (s, root = document) => root.querySelector(s);
3 const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
4 const names = {p:'Pawn',r:'Rook',n:'Knight',b:'Bishop',q:'Queen',k:'King'};
3 const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4 const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
5 const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
5 6 const pieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
6 const initials = name => esc(name.slice(0,2).toUpperCase());
7 const initials = name => esc(name.slice(0, 2).toUpperCase());
7 8 const avatarUrl = id => `assets/avatars/${encodeURIComponent(id)}.png`;
8 function avatarMarkup(name,id,editable=false){
9 const content=id?`<img src="${avatarUrl(id)}" alt="" draggable="false">`:initials(name);
10 return editable?`<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>`:`<span class="avatar">${content}</span>`;
9 function avatarMarkup (name, id, editable = false)
10 {
11 const content = id ? `<img src="${avatarUrl(id)}" alt="" draggable="false">` : initials(name);
12 return editable ? `<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>` : `<span class="avatar">${content}</span>`;
11 13 }
12 let avatarOptions=null,avatarGroup='all',avatarColor='all';
13 async function chooseAvatar(){
14 if(!state)return;
14 let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
15 async function chooseAvatar ()
16 {
17 if (!state) return;
15 18 showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>');
16 19 modal.classList.add('avatar-picker');
17 try{
18 if(!avatarOptions){const response=await fetch('assets/avatars/catalog.json');if(!response.ok)throw new Error('Unable to load avatars. Please try again.');avatarOptions=await response.json();}
19 if(!modal.open||!modal.classList.contains('avatar-picker'))return;
20 avatarGroup='all';avatarColor='all';
21 $('#modal-content').innerHTML=`<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all','All pieces'],['standard','Chess'],['fairy','Fairy chess']].map(([id,label])=>`<button class="secondary" data-avatar-group="${id}" aria-pressed="${id==='all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a=>a.color))].sort().map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces from Wikimedia Commons by C. Burnett and Iago Casabiell González. <a href="assets/avatars/CREDITS.md" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
20 try
21 {
22 if (!avatarOptions) { const response = await fetch('assets/avatars/catalog.json'); if (!response.ok) throw new Error('Unable to load avatars. Please try again.'); avatarOptions = await response.json(); }
23 if (!modal.open || !modal.classList.contains('avatar-picker')) return;
24 avatarGroup = 'all'; avatarColor = 'all';
25 $('#modal-content').innerHTML = `<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => `<button class="secondary" data-avatar-group="${id}" aria-pressed="${id === 'all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a => a.color))].sort().map(c => `<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces from Wikimedia Commons by C. Burnett and Iago Casabiell González. <a href="assets/avatars/CREDITS.md" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
22 26 renderAvatarChoices();
23 }catch(e){toast(e.message);if(modal.classList.contains('avatar-picker'))closeModal();}
27 } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); }
24 28 }
25 function renderAvatarChoices(){
26 const options=avatarOptions.filter(a=>(avatarGroup==='all'||a.group===avatarGroup)&&(avatarColor==='all'||a.color===avatarColor));
27 $('#avatar-choices').innerHTML=options.map(a=>`<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar===a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('')||'<p class="avatar-no-results">No pieces in this color. Try another color.</p>';
28 $('#avatar-option-count').textContent=`${options.length} pieces`;
29 document.querySelectorAll('[data-avatar-group]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.avatarGroup===avatarGroup)));
29 function renderAvatarChoices ()
30 {
31 const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor));
32 $('#avatar-choices').innerHTML = options.map(a => `<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar === a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('') || '<p class="avatar-no-results">No pieces in this color. Try another color.</p>';
33 $('#avatar-option-count').textContent = `${options.length} pieces`;
34 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
30 35 }
31 36 let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
32 37 const moveHolds = new Map();
38 const moveFeedback = new Map();
33 39 let moveHoldTimer;
34 40 let inviteToken = new URLSearchParams(location.search).get('invite');
35 41 const modal = $('#modal');
36 function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer=setTimeout(()=>$('#toast').classList.remove('visible'),5000); }
37 function showModal(html) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML=html; if (!modal.open) modal.showModal(); }
38 function closeModal() { modal.close(); }
39 $('#modal-close').onclick=closeModal;
40 modal.addEventListener('click',e=>{if(e.target===modal){const r=modal.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)closeModal();}});
41 function dismissInvite() { inviteToken=null; history.replaceState(null,'',location.pathname); }
42 modal.addEventListener('close',()=>{ if(inviteShown) dismissInvite(); });
43 const mobileLayout=matchMedia('(max-width: 760px)');
44 function showSidebar(open) {
45 const sidebar=$('#sidebar'); if(!sidebar)return;
46 sidebar.classList.toggle('open',open);
47 sidebar.inert=mobileLayout.matches&&!open;
48 $('#sidebar-backdrop').hidden=!open;
49 $('#friends-toggle').setAttribute('aria-expanded',String(open));
50 $('#main').inert=mobileLayout.matches&&open;
51 document.body.classList.toggle('sidebar-open',mobileLayout.matches&&open);
52 if(open)$('#friends-close').focus();
53 else if(mobileLayout.matches)$('#friends-toggle').focus();
42 function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
43 function showModal (html) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44 function closeModal () { modal.close(); }
45 $('#modal-close').onclick = closeModal;
46 modal.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
47 function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
48 modal.addEventListener('close', () => { if (inviteShown) dismissInvite(); });
49 const mobileLayout = matchMedia('(max-width: 760px)');
50 function showSidebar (open)
51 {
52 const sidebar = $('#sidebar'); if (!sidebar) return;
53 sidebar.classList.toggle('open', open);
54 sidebar.inert = mobileLayout.matches && !open;
55 $('#sidebar-backdrop').hidden = !open;
56 $('#friends-toggle').setAttribute('aria-expanded', String(open));
57 $('#main').inert = mobileLayout.matches && open;
58 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
59 if (open) $('#friends-close').focus();
60 else if (mobileLayout.matches) $('#friends-toggle').focus();
54 61 }
55 mobileLayout.addEventListener('change',()=>showSidebar(false));
56 if($('#sidebar'))$('#sidebar').inert=mobileLayout.matches;
57 $('#friends-toggle').onclick=()=>showSidebar(!$('#sidebar').classList.contains('open'));
58 if($('#friends-close'))$('#friends-close').onclick=()=>showSidebar(false);
59 if($('#sidebar-backdrop'))$('#sidebar-backdrop').onclick=()=>showSidebar(false);
60 document.addEventListener('keydown',e=>{if(e.key==='Escape'){showSidebar(false);selected=null;promotion=null;claimIntended=null;renderGames();}});
61 async function api(data) {
62 const response=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':state.csrf},body:JSON.stringify(data)});
63 const result=await response.json();if(!response.ok)throw new Error(result.error||'Request failed.');return result;
62 mobileLayout.addEventListener('change', () => showSidebar(false));
63 if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
64 $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
65 if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
66 if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
67 document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
68 async function api (data)
69 {
70 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
71 const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result;
64 72 }
65 async function action(data, success) {
66 if(busy)return;busy=true;
67 try {
68 const result=await api(data);
69 if(data.action==='move')moveHolds.set(data.game,{user:state.user.id,version:data.version,until:null});
70 selected=null;promotion=null;if(success)await success(result);await refresh(true);
73 async function action (data, success)
74 {
75 if (busy) return; busy = true;
76 try
77 {
78 const result = await api(data);
79 if (data.action === 'move')
80 {
81 moveHolds.set(data.game, { user: state.user.id, version: data.version, until: null });
82 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 });
83 }
84 selected = null; promotion = null; if (success) await success(result); await refresh(true);
71 85 }
72 catch(e){toast(e.message);await refresh(true);}
73 finally{busy=false;}
86 catch (e) { toast(e.message); await refresh(true); }
87 finally { busy = false; }
74 88 }
75 async function refresh(force=false) {
76 if(!$('#your-games') || (busy&&!force) || drag)return;
77 try {
78 const response=await fetch('api.php'+(inviteToken?'?invite='+encodeURIComponent(inviteToken):''));
79 const data=await response.json();
80 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'+(inviteToken?'?invite='+encodeURIComponent(inviteToken):'')+'">Sign in</a>');return;}
81 if(!response.ok)throw new Error(data.error||'Unable to load games.');
82 state=data;
83 if(selected){const g=state.games.find(g=>g.id===selected.game);if(!g?.yourTurn||g.version!==selected.version){selected=null;promotion=null;}}
84 const signature=JSON.stringify(data);
85 if(signature!==lastRender){lastRender=signature;renderGames();renderFriends();}
86 if(data.invite&&!inviteShown){inviteShown=true;const i=data.invite;
87 if(i.error)showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
88 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>`);
89 async function refresh (force = false)
90 {
91 if (!$('#your-games') || (busy && !force) || drag) return;
92 try
93 {
94 const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''));
95 const data = await response.json();
96 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' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : '') + '">Sign in</a>'); return; }
97 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
98 state = data;
99 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
100 const signature = JSON.stringify(data);
101 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); }
102 if (data.invite && !inviteShown)
103 {
104 inviteShown = true; const i = data.invite;
105 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
106 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>`);
89 107 }
90 }catch(e){toast(e.message||'Connection lost. We’ll try again shortly.');}
108 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
91 109 }
92 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>`;}
93 function renderGames() {
94 if(!state)return;
110 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>`; }
111 function renderGames ()
112 {
113 if (!state) return;
95 114 clearTimeout(moveHoldTimer);
96 let relocating=false;
97 const now=performance.now();
98 for(const [id,hold] of moveHolds){
99 const g=state.games.find(g=>g.id===id);
100 if(hold.user!==state.user.id||!g||g.status!=='active'||(g.version>hold.version&&g.yourTurn)){
101 moveHolds.delete(id);continue;
115 let relocating = false;
116 const now = performance.now();
117 for (const [id, hold] of moveHolds)
118 {
119 const g = state.games.find(g => g.id === id);
120 if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
121 {
122 moveHolds.delete(id); continue;
102 123 }
103 124 // Start the pause when the confirmed board position is first displayed.
104 if(hold.until===null&&g.version>hold.version)hold.until=now+3000;
105 if(hold.until!==null&&hold.until<=now&&!drag){moveHolds.delete(id);relocating=true;}
125 if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
126 if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
127 }
128 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 const selector = '.game-card, .waiting-heading, #main > footer';
131 const key = el => el.dataset.game || el.tagName;
132 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136 const waiting = state.games.filter(g => !yours.includes(g));
137 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length;
138 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140 {
141 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 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 }];
143 }));
144 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 $('#waiting-games').innerHTML = waiting.map(card).join('') || empty(false);
146 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 for (const el of document.querySelectorAll('.material-bar'))
148 {
149 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 fill.style.transform = `scaleX(${share})`;
151 if (!reduced && old && Math.abs(old.share - share) > .0001) fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear' });
106 152 }
107 const deadlines=[...moveHolds.values()].filter(h=>h.until!==null).map(h=>h.until);
108 if(deadlines.length)moveHoldTimer=setTimeout(renderGames,Math.max(drag?100:1,Math.min(...deadlines)-now));
109 const selector='.game-card, .waiting-heading, #main > footer';
110 const key=el=>el.dataset.game||el.tagName;
111 const animate=!matchMedia('(prefers-reduced-motion: reduce)').matches &&
112 (relocating||[...document.querySelectorAll(selector)].some(el=>el.getAnimations().length));
113 const before=new Map(animate?[...document.querySelectorAll(selector)].map(el=>[key(el),el.getBoundingClientRect()]):[]);
114 const yours=state.games.filter(g=>g.yourTurn||g.status==='ended'||g.status==='pending'&&g.incoming||moveHolds.has(g.id));
115 const waiting=state.games.filter(g=>!yours.includes(g));
116 $('#your-count').textContent=yours.length;$('#waiting-count').textContent=waiting.length;
117 $('#your-games').innerHTML=yours.map(card).join('')||empty(true);
118 $('#waiting-games').innerHTML=waiting.map(card).join('')||empty(false);
119 if(animate){
120 for(const el of document.querySelectorAll(selector)){
121 const old=before.get(key(el));
122 el.getAnimations().forEach(animation=>animation.cancel());
123 if(!old)continue;
124 const rect=el.getBoundingClientRect(),dx=old.left-rect.left,dy=old.top-rect.top;
125 if(Math.abs(dx)<1&&Math.abs(dy)<1)continue;
153 renderMoveFeedback(now, reduced);
154 if (animate)
155 {
156 for (const el of document.querySelectorAll(selector))
157 {
158 const old = before.get(key(el));
159 el.getAnimations().forEach(animation => animation.cancel());
160 if (!old) continue;
161 const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
162 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
126 163 el.animate([
127 {transform:`translate(${dx}px, ${dy}px)`,zIndex:2},
128 {transform:'translate(0, 0)',zIndex:2}
129 ],{duration:650,easing:'cubic-bezier(.22, 1, .36, 1)'});
164 { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
165 { transform: 'translate(0, 0)', zIndex: 2 }
166 ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
130 167 }
131 168 }
132 169 }
133 function card(g){
134 let content='';
135 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">The next move is theirs.</span>'}</div>`;
136 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>`;
137 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>`;
138 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)}<strong>${esc(g.opponent)}</strong>${g.status!=='pending'?`<span class="color-tag"><span class="color-disc ${g.color==='b'?'black':''}"></span>${g.color==='w'?'White':'Black'}</span>`:''}${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>`;
170 function card (g)
171 {
172 let content = '';
173 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">The next move is theirs.</span>'}</div>`;
174 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>`;
175 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>`;
176 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>${esc(g.opponent)}</strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${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>`;
177 }
178 function materialBar (g)
179 {
180 const totals = { w: 0, b: 0 };
181 for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
182 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
183 const label = `White: ${totals.w} material points. Black: ${totals.b} material points. You play ${g.color === 'w' ? 'White' : 'Black'}.`;
184 return `<div class="material-bar" data-share="${share}" role="meter" aria-label="Material balance, White on the left and Black on the right" 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"></span></div>`;
185 }
186 function renderMoveFeedback (now, reduced)
187 {
188 for (const [id, feedback] of moveFeedback)
189 {
190 const g = state.games.find(g => g.id === id);
191 if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
192 if (g.state.ply !== feedback.ply) continue;
193 if (feedback.start === null)
194 {
195 feedback.start = now;
196 setTimeout(() =>
197 {
198 if (moveFeedback.get(id) !== feedback) return;
199 moveFeedback.delete(id);
200 document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
201 }, 1800);
202 }
203 const elapsed = now - feedback.start;
204 if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
205 const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
206 const overlay = document.createElement('div');
207 overlay.className = `move-feedback ${feedback.quality}`;
208 const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
209 el.append(overlay);
210 if (reduced) { overlay.style.opacity = '1'; continue; }
211 const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
212 const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
213 animation.currentTime = elapsed;
214 }
139 215 }
140 function board(g){
141 const indices=Array.from({length:20},(_,i)=>g.color==='w'?i:19-i);
142 const active=selected?.game===g.id?selected.from:null;
143 const legal=g.legal.filter(m=>m.from===active).map(m=>m.to);
144 let html='<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
145 indices.forEach((i,view)=>{
146 const p=g.state.board[i], square=String.fromCharCode(97+i%4)+(5-Math.floor(i/4));
147 const last=g.state.last&&(i===g.state.last.from||i===g.state.last.to);
148 const checked=g.check&&p.toLowerCase()==='k'&&(p===p.toUpperCase()?'w':'b')===g.state.turn;
149 const label=`${square}${p!=='.'?' '+(p===p.toUpperCase()?'white ':'black ')+names[p.toLowerCase()]:''}${legal.includes(i)?', legal destination':''}`;
150 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)}" 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>`;
216 function board (g)
217 {
218 const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
219 const active = selected?.game === g.id ? selected.from : null;
220 const legal = g.legal.filter(m => m.from === active).map(m => m.to);
221 let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
222 indices.forEach((i, view) =>
223 {
224 const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
225 const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
226 const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
227 const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
228 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)}" 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>`;
151 229 });
152 html+='</div>';
153 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)}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
154 return html+'</div>';
230 html += '</div>';
231 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)}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
232 return html + '</div>';
155 233 }
156 function renderFriends(){
157 $('#friend-count').textContent=state.friends.length;$('#sidebar-count').textContent=state.friends.length;
158 $('#friend-list').innerHTML=state.friends.map(f=>`<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name,f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('')||'<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>';
159 $('#account-summary').innerHTML=`${avatarMarkup(state.user.name,state.user.avatar,true)}<span>${esc(state.user.name)}<small>${state.local?'Local test account':'Ready for your next move'}</small></span>`;
234 function renderFriends ()
235 {
236 $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;
237 $('#friend-list').innerHTML = state.friends.map(f => `<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name, f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('') || '<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>';
238 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.local ? 'Local test account' : 'Ready for your next move'}</small></span>`;
160 239 }
161 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;}
162 function chooseSquare(g,i){
163 if(!g.yourTurn||busy||promotion)return;
164 if(selected?.game===g.id&&g.legal.some(m=>m.from===selected.from&&m.to===i)){attemptMove(g,selected.from,i);return;}
165 const p=g.state.board[i];
166 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};}
167 else selected=null;
240 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; }
241 function chooseSquare (g, i)
242 {
243 if (!g.yourTurn || busy || promotion) return;
244 if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
245 const p = g.state.board[i];
246 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 }; }
247 else selected = null;
168 248 renderGames();
169 249 }
170 let claimIntended=null;
171 function attemptMove(g,from,to,promote){
172 const moves=g.legal.filter(m=>m.from===from&&m.to===to);if(!moves.length)return;
173 if(moves[0].promotion&&!promote){promotion={game:g.id,from,to};renderGames();return;}
174 const kind=claimIntended===g.id?'claim_draw':'move';claimIntended=null;
175 action({action:kind,game:g.id,version:g.version,from,to,promotion:promote??null});
250 let claimIntended = null;
251 function attemptMove (g, from, to, promote)
252 {
253 const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
254 if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
255 const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
256 action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
176 257 }
177 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 they 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>`);});}
178 if($('#match-link'))$('#match-link').onclick=()=>createLink('match');
179 if($('#friend-link'))$('#friend-link').onclick=()=>createLink('friend');
180 $('#settings-button').onclick=()=>{if(!state)return;showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><div class="settings-actions">${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>`);};
181 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></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>`);
182 document.addEventListener('click',e=>{
183 const el=e.target.closest('button');if(!el)return;
184 const gameEl=el.closest('[data-game]');const g=gameEl&&state?.games.find(g=>g.id===Number(gameEl.dataset.game));
185 if(el.id==='avatar-button')chooseAvatar();
186 if(el.dataset.createLink)createLink(el.dataset.createLink);
187 if(el.hasAttribute('data-square')&&g){if(suppressClick){suppressClick=false;return;}chooseSquare(g,Number(el.dataset.square));}
188 if(el.dataset.gameAction&&g){if(el.dataset.gameAction==='stop-confirm'){showModal(`<h2 id="modal-title">Spel stoppen?</h2><p>De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Spel stoppen</button><button class="secondary" data-modal-action="close">Annuleren</button></div>`);}else if(el.dataset.gameAction==='options')options(g);else action({action:el.dataset.gameAction,game:g.id,version:g.version});}
189 if(el.dataset.promotion&&g&&promotion)attemptMove(g,promotion.from,promotion.to,el.dataset.promotion);
190 if(el.hasAttribute('data-cancel-promotion')){promotion=null;claimIntended=null;renderGames();}
191 if(el.dataset.friend){const f=state.friends.find(f=>f.id===el.dataset.friend);showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions"><button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button></div>`);$('#modal-content').dataset.friend=f.id;}
258 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 they 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>`); }); }
259 if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
260 if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
261 $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><div class="settings-actions">${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>`); };
262 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>`);
263 document.addEventListener('click', e =>
264 {
265 const el = e.target.closest('button'); if (!el) return;
266 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
267 if (el.id === 'avatar-button') chooseAvatar();
268 if (el.dataset.createLink) createLink(el.dataset.createLink);
269 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
270 if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Spel stoppen?</h2><p>De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Spel stoppen</button><button class="secondary" data-modal-action="close">Annuleren</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
271 if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
272 if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
273 if (el.dataset.friend) { const f = state.friends.find(f => f.id === el.dataset.friend); showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions"><button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button></div>`); $('#modal-content').dataset.friend = f.id; }
192 274 });
193 $('#modal-content').addEventListener('click',async e=>{
194 const b=e.target.closest('button');if(!b)return;
195 if(b.dataset.stopGame){await action({action:'stop_inactive',game:Number(b.dataset.stopGame),version:Number(b.dataset.version)},()=>closeModal());return;}
196 if(b.dataset.avatarGroup){avatarGroup=b.dataset.avatarGroup;renderAvatarChoices();return;}
197 if(b.hasAttribute('data-avatar-choice')){await action({action:'set_avatar',avatar:b.dataset.avatarChoice||null},()=>{closeModal();toast('Avatar updated.');});return;}
198 if(b.dataset.modalAction==='close')closeModal();
199 if(b.dataset.modalAction==='accept-invite')await action({action:'accept_link',token:inviteToken},()=>{closeModal();toast('Invitation accepted.');});
200 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.');}}
201 if(b.dataset.modalAction==='switch')await action({action:'switch_user',user:state.user.name==='test_user_1'?'test_user_2':'test_user_1'},()=>{lastRender='';closeModal();});
202 if(b.dataset.modalAction==='logout')await action({action:'logout'},()=>location.reload());
203 if(b.dataset.friendAction){const id=$('#modal-content').dataset.friend;
204 if(b.dataset.friendAction==='remove'){showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>');}
205 else await action({action:b.dataset.friendAction==='challenge'?'challenge':'remove_friend',friend:id},()=>{closeModal();toast(b.dataset.friendAction==='challenge'?'Challenge sent.':'Friend removed.');});
275 $('#modal-content').addEventListener('click', async e =>
276 {
277 const b = e.target.closest('button'); if (!b) return;
278 if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; }
279 if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; }
280 if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; }
281 if (b.dataset.modalAction === 'close') closeModal();
282 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
283 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.'); } }
284 if (b.dataset.modalAction === 'switch') await action({ action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
285 if (b.dataset.modalAction === 'logout') await action({ action: 'logout' }, () => location.reload());
286 if (b.dataset.friendAction)
287 {
288 const id = $('#modal-content').dataset.friend;
289 if (b.dataset.friendAction === 'remove') { showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); }
290 else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); });
206 291 }
207 if(b.dataset.option){const g=state.games.find(g=>g.id===Number($('#modal-content').dataset.game));if(!g)return;
208 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;}
209 if(b.dataset.option==='claim-intended'){claimIntended=g.id;closeModal();toast('Select your intended move to claim a draw.');return;}
210 await action({action:b.dataset.option,game:g.id,version:g.version},()=>closeModal());
292 if (b.dataset.option)
293 {
294 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
295 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; }
296 if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
297 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
211 298 }
212 299 });
213 $('#modal-content').addEventListener('change',e=>{if(e.target.id==='avatar-color'){avatarColor=e.target.value;renderAvatarChoices();}});
214 let suppressClick=false;
215 document.addEventListener('pointerdown',e=>{
216 const sq=e.target.closest('[data-square]');if(!sq||e.button!==0||busy||promotion)return;
217 const g=state?.games.find(g=>g.id===Number(sq.closest('[data-game]').dataset.game));if(!g?.yourTurn)return;
218 const from=Number(sq.dataset.square),p=g.state.board[from];if(p==='.'||(p===p.toUpperCase()?'w':'b')!==g.color)return;
219 drag={game:g.id,from,p,x:e.clientX,y:e.clientY,id:e.pointerId,moving:false};
300 $('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } });
301 let suppressClick = false;
302 document.addEventListener('pointerdown', e =>
303 {
304 const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
305 const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
306 const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
307 drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
220 308 });
221 document.addEventListener('pointermove',e=>{
222 if(!drag||e.pointerId!==drag.id)return;
223 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);document.body.append(img);}
224 if(drag.moving){e.preventDefault();const img=$('.drag-ghost');img.style.left=e.clientX+'px';img.style.top=e.clientY+'px';}
225 },{passive:false});
226 document.addEventListener('pointerup',e=>{
227 if(!drag||e.pointerId!==drag.id)return;const d=drag;drag=null;$('.drag-ghost')?.remove();
228 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));}
309 document.addEventListener('pointermove', e =>
310 {
311 if (!drag || e.pointerId !== drag.id) return;
312 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); document.body.append(img); }
313 if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
314 }, { passive: false });
315 document.addEventListener('pointerup', e =>
316 {
317 if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
318 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)); }
229 319 });
230 document.addEventListener('pointercancel',()=>{drag=null;$('.drag-ghost')?.remove();});
231 refresh();setInterval(()=>{if(!document.hidden)refresh();},2500);document.addEventListener('visibilitychange',()=>{if(!document.hidden)refresh();});
320 document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
321 refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
@@ -1,231 +1,321 @@
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]));
4const names = {p:'Pawn',r:'Rook',n:'Knight',b:'Bishop',q:'Queen',k:'King'};
4const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
5const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
5const pieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
6const pieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
6const initials = name => esc(name.slice(0,2).toUpperCase());
7const initials = name => esc(name.slice(0, 2).toUpperCase());
7const avatarUrl = id => `assets/avatars/${encodeURIComponent(id)}.png`;
8const avatarUrl = id => `assets/avatars/${encodeURIComponent(id)}.png`;
8function avatarMarkup(name,id,editable=false){
9function avatarMarkup (name, id, editable = false)
9 const content=id?`<img src="${avatarUrl(id)}" alt="" draggable="false">`:initials(name);
10{
10 return editable?`<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>`:`<span class="avatar">${content}</span>`;
11 const content = id ? `<img src="${avatarUrl(id)}" alt="" draggable="false">` : initials(name);
12 return editable ? `<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>` : `<span class="avatar">${content}</span>`;
11}
13}
12let avatarOptions=null,avatarGroup='all',avatarColor='all';
14let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
13async function chooseAvatar(){
15async function chooseAvatar ()
14 if(!state)return;
16{
17 if (!state) return;
15 showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>');
18 showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>');
16 modal.classList.add('avatar-picker');
19 modal.classList.add('avatar-picker');
17 try{
20 try
18 if(!avatarOptions){const response=await fetch('assets/avatars/catalog.json');if(!response.ok)throw new Error('Unable to load avatars. Please try again.');avatarOptions=await response.json();}
21 {
19 if(!modal.open||!modal.classList.contains('avatar-picker'))return;
22 if (!avatarOptions) { const response = await fetch('assets/avatars/catalog.json'); if (!response.ok) throw new Error('Unable to load avatars. Please try again.'); avatarOptions = await response.json(); }
20 avatarGroup='all';avatarColor='all';
23 if (!modal.open || !modal.classList.contains('avatar-picker')) return;
21 $('#modal-content').innerHTML=`<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all','All pieces'],['standard','Chess'],['fairy','Fairy chess']].map(([id,label])=>`<button class="secondary" data-avatar-group="${id}" aria-pressed="${id==='all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a=>a.color))].sort().map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces from Wikimedia Commons by C. Burnett and Iago Casabiell González. <a href="assets/avatars/CREDITS.md" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
24 avatarGroup = 'all'; avatarColor = 'all';
25 $('#modal-content').innerHTML = `<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => `<button class="secondary" data-avatar-group="${id}" aria-pressed="${id === 'all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a => a.color))].sort().map(c => `<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces from Wikimedia Commons by C. Burnett and Iago Casabiell González. <a href="assets/avatars/CREDITS.md" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
22 renderAvatarChoices();
26 renderAvatarChoices();
23 }catch(e){toast(e.message);if(modal.classList.contains('avatar-picker'))closeModal();}
27 } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); }
24}
28}
25function renderAvatarChoices(){
29function renderAvatarChoices ()
26 const options=avatarOptions.filter(a=>(avatarGroup==='all'||a.group===avatarGroup)&&(avatarColor==='all'||a.color===avatarColor));
30{
27 $('#avatar-choices').innerHTML=options.map(a=>`<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar===a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('')||'<p class="avatar-no-results">No pieces in this color. Try another color.</p>';
31 const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor));
28 $('#avatar-option-count').textContent=`${options.length} pieces`;
32 $('#avatar-choices').innerHTML = options.map(a => `<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar === a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('') || '<p class="avatar-no-results">No pieces in this color. Try another color.</p>';
29 document.querySelectorAll('[data-avatar-group]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.avatarGroup===avatarGroup)));
33 $('#avatar-option-count').textContent = `${options.length} pieces`;
34 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
30}
35}
31let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
36let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
32const moveHolds = new Map();
37const moveHolds = new Map();
38const moveFeedback = new Map();
33let moveHoldTimer;
39let moveHoldTimer;
34let inviteToken = new URLSearchParams(location.search).get('invite');
40let inviteToken = new URLSearchParams(location.search).get('invite');
35const modal = $('#modal');
41const modal = $('#modal');
36function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer=setTimeout(()=>$('#toast').classList.remove('visible'),5000); }
42function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
37function showModal(html) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML=html; if (!modal.open) modal.showModal(); }
43function showModal (html) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
38function closeModal() { modal.close(); }
44function closeModal () { modal.close(); }
39$('#modal-close').onclick=closeModal;
45$('#modal-close').onclick = closeModal;
40modal.addEventListener('click',e=>{if(e.target===modal){const r=modal.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)closeModal();}});
46modal.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
41function dismissInvite() { inviteToken=null; history.replaceState(null,'',location.pathname); }
47function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
42modal.addEventListener('close',()=>{ if(inviteShown) dismissInvite(); });
48modal.addEventListener('close', () => { if (inviteShown) dismissInvite(); });
43const mobileLayout=matchMedia('(max-width: 760px)');
49const mobileLayout = matchMedia('(max-width: 760px)');
44function showSidebar(open) {
50function showSidebar (open)
45 const sidebar=$('#sidebar'); if(!sidebar)return;
51{
46 sidebar.classList.toggle('open',open);
52 const sidebar = $('#sidebar'); if (!sidebar) return;
47 sidebar.inert=mobileLayout.matches&&!open;
53 sidebar.classList.toggle('open', open);
48 $('#sidebar-backdrop').hidden=!open;
54 sidebar.inert = mobileLayout.matches && !open;
49 $('#friends-toggle').setAttribute('aria-expanded',String(open));
55 $('#sidebar-backdrop').hidden = !open;
50 $('#main').inert=mobileLayout.matches&&open;
56 $('#friends-toggle').setAttribute('aria-expanded', String(open));
51 document.body.classList.toggle('sidebar-open',mobileLayout.matches&&open);
57 $('#main').inert = mobileLayout.matches && open;
52 if(open)$('#friends-close').focus();
58 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
53 else if(mobileLayout.matches)$('#friends-toggle').focus();
59 if (open) $('#friends-close').focus();
60 else if (mobileLayout.matches) $('#friends-toggle').focus();
54}
61}
55mobileLayout.addEventListener('change',()=>showSidebar(false));
62mobileLayout.addEventListener('change', () => showSidebar(false));
56if($('#sidebar'))$('#sidebar').inert=mobileLayout.matches;
63if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
57$('#friends-toggle').onclick=()=>showSidebar(!$('#sidebar').classList.contains('open'));
64$('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
58if($('#friends-close'))$('#friends-close').onclick=()=>showSidebar(false);
65if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
59if($('#sidebar-backdrop'))$('#sidebar-backdrop').onclick=()=>showSidebar(false);
66if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
60document.addEventListener('keydown',e=>{if(e.key==='Escape'){showSidebar(false);selected=null;promotion=null;claimIntended=null;renderGames();}});
67document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
61async function api(data) {
68async function api (data)
62 const response=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':state.csrf},body:JSON.stringify(data)});
69{
63 const result=await response.json();if(!response.ok)throw new Error(result.error||'Request failed.');return result;
70 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
71 const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result;
64}
72}
65async function action(data, success) {
73async function action (data, success)
66 if(busy)return;busy=true;
74{
67 try {
75 if (busy) return; busy = true;
68 const result=await api(data);
76 try
69 if(data.action==='move')moveHolds.set(data.game,{user:state.user.id,version:data.version,until:null});
77 {
70 selected=null;promotion=null;if(success)await success(result);await refresh(true);
78 const result = await api(data);
79 if (data.action === 'move')
80 {
81 moveHolds.set(data.game, { user: state.user.id, version: data.version, until: null });
82 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 });
83 }
84 selected = null; promotion = null; if (success) await success(result); await refresh(true);
71 }
85 }
72 catch(e){toast(e.message);await refresh(true);}
86 catch (e) { toast(e.message); await refresh(true); }
73 finally{busy=false;}
87 finally { busy = false; }
74}
88}
75async function refresh(force=false) {
89async function refresh (force = false)
76 if(!$('#your-games') || (busy&&!force) || drag)return;
90{
77 try {
91 if (!$('#your-games') || (busy && !force) || drag) return;
78 const response=await fetch('api.php'+(inviteToken?'?invite='+encodeURIComponent(inviteToken):''));
92 try
79 const data=await response.json();
93 {
80 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'+(inviteToken?'?invite='+encodeURIComponent(inviteToken):'')+'">Sign in</a>');return;}
94 const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''));
81 if(!response.ok)throw new Error(data.error||'Unable to load games.');
95 const data = await response.json();
82 state=data;
96 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' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : '') + '">Sign in</a>'); return; }
83 if(selected){const g=state.games.find(g=>g.id===selected.game);if(!g?.yourTurn||g.version!==selected.version){selected=null;promotion=null;}}
97 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
84 const signature=JSON.stringify(data);
98 state = data;
85 if(signature!==lastRender){lastRender=signature;renderGames();renderFriends();}
99 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
86 if(data.invite&&!inviteShown){inviteShown=true;const i=data.invite;
100 const signature = JSON.stringify(data);
87 if(i.error)showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
101 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); }
88 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>`);
102 if (data.invite && !inviteShown)
103 {
104 inviteShown = true; const i = data.invite;
105 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
106 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>`);
89 }
107 }
90 }catch(e){toast(e.message||'Connection lost. We’ll try again shortly.');}
108 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
91}
109}
92function 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>`;}
110function 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>`; }
93function renderGames() {
111function renderGames ()
94 if(!state)return;
112{
113 if (!state) return;
95 clearTimeout(moveHoldTimer);
114 clearTimeout(moveHoldTimer);
96 let relocating=false;
115 let relocating = false;
97 const now=performance.now();
116 const now = performance.now();
98 for(const [id,hold] of moveHolds){
117 for (const [id, hold] of moveHolds)
99 const g=state.games.find(g=>g.id===id);
118 {
100 if(hold.user!==state.user.id||!g||g.status!=='active'||(g.version>hold.version&&g.yourTurn)){
119 const g = state.games.find(g => g.id === id);
101 moveHolds.delete(id);continue;
120 if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
121 {
122 moveHolds.delete(id); continue;
102 }
123 }
103 // Start the pause when the confirmed board position is first displayed.
124 // Start the pause when the confirmed board position is first displayed.
104 if(hold.until===null&&g.version>hold.version)hold.until=now+3000;
125 if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
105 if(hold.until!==null&&hold.until<=now&&!drag){moveHolds.delete(id);relocating=true;}
126 if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
127 }
128 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 const selector = '.game-card, .waiting-heading, #main > footer';
131 const key = el => el.dataset.game || el.tagName;
132 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136 const waiting = state.games.filter(g => !yours.includes(g));
137 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length;
138 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140 {
141 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 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 }];
143 }));
144 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 $('#waiting-games').innerHTML = waiting.map(card).join('') || empty(false);
146 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 for (const el of document.querySelectorAll('.material-bar'))
148 {
149 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 fill.style.transform = `scaleX(${share})`;
151 if (!reduced && old && Math.abs(old.share - share) > .0001) fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear' });
106 }
152 }
107 const deadlines=[...moveHolds.values()].filter(h=>h.until!==null).map(h=>h.until);
153 renderMoveFeedback(now, reduced);
108 if(deadlines.length)moveHoldTimer=setTimeout(renderGames,Math.max(drag?100:1,Math.min(...deadlines)-now));
154 if (animate)
109 const selector='.game-card, .waiting-heading, #main > footer';
155 {
110 const key=el=>el.dataset.game||el.tagName;
156 for (const el of document.querySelectorAll(selector))
111 const animate=!matchMedia('(prefers-reduced-motion: reduce)').matches &&
157 {
112 (relocating||[...document.querySelectorAll(selector)].some(el=>el.getAnimations().length));
158 const old = before.get(key(el));
113 const before=new Map(animate?[...document.querySelectorAll(selector)].map(el=>[key(el),el.getBoundingClientRect()]):[]);
159 el.getAnimations().forEach(animation => animation.cancel());
114 const yours=state.games.filter(g=>g.yourTurn||g.status==='ended'||g.status==='pending'&&g.incoming||moveHolds.has(g.id));
160 if (!old) continue;
115 const waiting=state.games.filter(g=>!yours.includes(g));
161 const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
116 $('#your-count').textContent=yours.length;$('#waiting-count').textContent=waiting.length;
162 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
117 $('#your-games').innerHTML=yours.map(card).join('')||empty(true);
118 $('#waiting-games').innerHTML=waiting.map(card).join('')||empty(false);
119 if(animate){
120 for(const el of document.querySelectorAll(selector)){
121 const old=before.get(key(el));
122 el.getAnimations().forEach(animation=>animation.cancel());
123 if(!old)continue;
124 const rect=el.getBoundingClientRect(),dx=old.left-rect.left,dy=old.top-rect.top;
125 if(Math.abs(dx)<1&&Math.abs(dy)<1)continue;
126 el.animate([
163 el.animate([
127 {transform:`translate(${dx}px, ${dy}px)`,zIndex:2},
164 { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
128 {transform:'translate(0, 0)',zIndex:2}
165 { transform: 'translate(0, 0)', zIndex: 2 }
129 ],{duration:650,easing:'cubic-bezier(.22, 1, .36, 1)'});
166 ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
130 }
167 }
131 }
168 }
132}
169}
133function card(g){
170function card (g)
134 let content='';
171{
135 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">The next move is theirs.</span>'}</div>`;
172 let content = '';
136 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>`;
173 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">The next move is theirs.</span>'}</div>`;
137 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>`;
174 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>`;
138 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)}<strong>${esc(g.opponent)}</strong>${g.status!=='pending'?`<span class="color-tag"><span class="color-disc ${g.color==='b'?'black':''}"></span>${g.color==='w'?'White':'Black'}</span>`:''}${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>`;
175 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>`;
176 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>${esc(g.opponent)}</strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${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>`;
177}
178function materialBar (g)
179{
180 const totals = { w: 0, b: 0 };
181 for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
182 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
183 const label = `White: ${totals.w} material points. Black: ${totals.b} material points. You play ${g.color === 'w' ? 'White' : 'Black'}.`;
184 return `<div class="material-bar" data-share="${share}" role="meter" aria-label="Material balance, White on the left and Black on the right" 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"></span></div>`;
185}
186function renderMoveFeedback (now, reduced)
187{
188 for (const [id, feedback] of moveFeedback)
189 {
190 const g = state.games.find(g => g.id === id);
191 if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
192 if (g.state.ply !== feedback.ply) continue;
193 if (feedback.start === null)
194 {
195 feedback.start = now;
196 setTimeout(() =>
197 {
198 if (moveFeedback.get(id) !== feedback) return;
199 moveFeedback.delete(id);
200 document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
201 }, 1800);
202 }
203 const elapsed = now - feedback.start;
204 if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
205 const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
206 const overlay = document.createElement('div');
207 overlay.className = `move-feedback ${feedback.quality}`;
208 const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
209 el.append(overlay);
210 if (reduced) { overlay.style.opacity = '1'; continue; }
211 const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
212 const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
213 animation.currentTime = elapsed;
214 }
139}
215}
140function board(g){
216function board (g)
141 const indices=Array.from({length:20},(_,i)=>g.color==='w'?i:19-i);
217{
142 const active=selected?.game===g.id?selected.from:null;
218 const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
143 const legal=g.legal.filter(m=>m.from===active).map(m=>m.to);
219 const active = selected?.game === g.id ? selected.from : null;
144 let html='<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
220 const legal = g.legal.filter(m => m.from === active).map(m => m.to);
145 indices.forEach((i,view)=>{
221 let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
146 const p=g.state.board[i], square=String.fromCharCode(97+i%4)+(5-Math.floor(i/4));
222 indices.forEach((i, view) =>
147 const last=g.state.last&&(i===g.state.last.from||i===g.state.last.to);
223 {
148 const checked=g.check&&p.toLowerCase()==='k'&&(p===p.toUpperCase()?'w':'b')===g.state.turn;
224 const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
149 const label=`${square}${p!=='.'?' '+(p===p.toUpperCase()?'white ':'black ')+names[p.toLowerCase()]:''}${legal.includes(i)?', legal destination':''}`;
225 const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
150 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)}" 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>`;
226 const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
227 const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
228 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)}" 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>`;
151 });
229 });
152 html+='</div>';
230 html += '</div>';
153 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)}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
231 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)}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
154 return html+'</div>';
232 return html + '</div>';
155}
233}
156function renderFriends(){
234function renderFriends ()
157 $('#friend-count').textContent=state.friends.length;$('#sidebar-count').textContent=state.friends.length;
235{
158 $('#friend-list').innerHTML=state.friends.map(f=>`<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name,f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('')||'<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>';
236 $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;
159 $('#account-summary').innerHTML=`${avatarMarkup(state.user.name,state.user.avatar,true)}<span>${esc(state.user.name)}<small>${state.local?'Local test account':'Ready for your next move'}</small></span>`;
237 $('#friend-list').innerHTML = state.friends.map(f => `<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name, f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('') || '<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>';
238 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.local ? 'Local test account' : 'Ready for your next move'}</small></span>`;
160}
239}
161function 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;}
240function 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; }
162function chooseSquare(g,i){
241function chooseSquare (g, i)
163 if(!g.yourTurn||busy||promotion)return;
242{
164 if(selected?.game===g.id&&g.legal.some(m=>m.from===selected.from&&m.to===i)){attemptMove(g,selected.from,i);return;}
243 if (!g.yourTurn || busy || promotion) return;
165 const p=g.state.board[i];
244 if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
166 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};}
245 const p = g.state.board[i];
167 else selected=null;
246 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 }; }
247 else selected = null;
168 renderGames();
248 renderGames();
169}
249}
170let claimIntended=null;
250let claimIntended = null;
171function attemptMove(g,from,to,promote){
251function attemptMove (g, from, to, promote)
172 const moves=g.legal.filter(m=>m.from===from&&m.to===to);if(!moves.length)return;
252{
173 if(moves[0].promotion&&!promote){promotion={game:g.id,from,to};renderGames();return;}
253 const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
174 const kind=claimIntended===g.id?'claim_draw':'move';claimIntended=null;
254 if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
175 action({action:kind,game:g.id,version:g.version,from,to,promotion:promote??null});
255 const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
256 action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
176}
257}
177async 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 they 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>`);});}
258async 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 they 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>`); }); }
178if($('#match-link'))$('#match-link').onclick=()=>createLink('match');
259if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
179if($('#friend-link'))$('#friend-link').onclick=()=>createLink('friend');
260if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
180$('#settings-button').onclick=()=>{if(!state)return;showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><div class="settings-actions">${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>`);};
261$('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><div class="settings-actions">${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>`); };
181if($('#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></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>`);
262if ($('#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>`);
182document.addEventListener('click',e=>{
263document.addEventListener('click', e =>
183 const el=e.target.closest('button');if(!el)return;
264{
184 const gameEl=el.closest('[data-game]');const g=gameEl&&state?.games.find(g=>g.id===Number(gameEl.dataset.game));
265 const el = e.target.closest('button'); if (!el) return;
185 if(el.id==='avatar-button')chooseAvatar();
266 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
186 if(el.dataset.createLink)createLink(el.dataset.createLink);
267 if (el.id === 'avatar-button') chooseAvatar();
187 if(el.hasAttribute('data-square')&&g){if(suppressClick){suppressClick=false;return;}chooseSquare(g,Number(el.dataset.square));}
268 if (el.dataset.createLink) createLink(el.dataset.createLink);
188 if(el.dataset.gameAction&&g){if(el.dataset.gameAction==='stop-confirm'){showModal(`<h2 id="modal-title">Spel stoppen?</h2><p>De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Spel stoppen</button><button class="secondary" data-modal-action="close">Annuleren</button></div>`);}else if(el.dataset.gameAction==='options')options(g);else action({action:el.dataset.gameAction,game:g.id,version:g.version});}
269 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
189 if(el.dataset.promotion&&g&&promotion)attemptMove(g,promotion.from,promotion.to,el.dataset.promotion);
270 if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Spel stoppen?</h2><p>De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Spel stoppen</button><button class="secondary" data-modal-action="close">Annuleren</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
190 if(el.hasAttribute('data-cancel-promotion')){promotion=null;claimIntended=null;renderGames();}
271 if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
191 if(el.dataset.friend){const f=state.friends.find(f=>f.id===el.dataset.friend);showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions"><button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button></div>`);$('#modal-content').dataset.friend=f.id;}
272 if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
273 if (el.dataset.friend) { const f = state.friends.find(f => f.id === el.dataset.friend); showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions"><button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button></div>`); $('#modal-content').dataset.friend = f.id; }
192});
274});
193$('#modal-content').addEventListener('click',async e=>{
275$('#modal-content').addEventListener('click', async e =>
194 const b=e.target.closest('button');if(!b)return;
276{
195 if(b.dataset.stopGame){await action({action:'stop_inactive',game:Number(b.dataset.stopGame),version:Number(b.dataset.version)},()=>closeModal());return;}
277 const b = e.target.closest('button'); if (!b) return;
196 if(b.dataset.avatarGroup){avatarGroup=b.dataset.avatarGroup;renderAvatarChoices();return;}
278 if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; }
197 if(b.hasAttribute('data-avatar-choice')){await action({action:'set_avatar',avatar:b.dataset.avatarChoice||null},()=>{closeModal();toast('Avatar updated.');});return;}
279 if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; }
198 if(b.dataset.modalAction==='close')closeModal();
280 if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; }
199 if(b.dataset.modalAction==='accept-invite')await action({action:'accept_link',token:inviteToken},()=>{closeModal();toast('Invitation accepted.');});
281 if (b.dataset.modalAction === 'close') closeModal();
200 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.');}}
282 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
201 if(b.dataset.modalAction==='switch')await action({action:'switch_user',user:state.user.name==='test_user_1'?'test_user_2':'test_user_1'},()=>{lastRender='';closeModal();});
283 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.'); } }
202 if(b.dataset.modalAction==='logout')await action({action:'logout'},()=>location.reload());
284 if (b.dataset.modalAction === 'switch') await action({ action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
203 if(b.dataset.friendAction){const id=$('#modal-content').dataset.friend;
285 if (b.dataset.modalAction === 'logout') await action({ action: 'logout' }, () => location.reload());
204 if(b.dataset.friendAction==='remove'){showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>');}
286 if (b.dataset.friendAction)
205 else await action({action:b.dataset.friendAction==='challenge'?'challenge':'remove_friend',friend:id},()=>{closeModal();toast(b.dataset.friendAction==='challenge'?'Challenge sent.':'Friend removed.');});
287 {
288 const id = $('#modal-content').dataset.friend;
289 if (b.dataset.friendAction === 'remove') { showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); }
290 else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); });
206 }
291 }
207 if(b.dataset.option){const g=state.games.find(g=>g.id===Number($('#modal-content').dataset.game));if(!g)return;
292 if (b.dataset.option)
208 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;}
293 {
209 if(b.dataset.option==='claim-intended'){claimIntended=g.id;closeModal();toast('Select your intended move to claim a draw.');return;}
294 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
210 await action({action:b.dataset.option,game:g.id,version:g.version},()=>closeModal());
295 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; }
296 if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
297 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
211 }
298 }
212});
299});
213$('#modal-content').addEventListener('change',e=>{if(e.target.id==='avatar-color'){avatarColor=e.target.value;renderAvatarChoices();}});
300$('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } });
214let suppressClick=false;
301let suppressClick = false;
215document.addEventListener('pointerdown',e=>{
302document.addEventListener('pointerdown', e =>
216 const sq=e.target.closest('[data-square]');if(!sq||e.button!==0||busy||promotion)return;
303{
217 const g=state?.games.find(g=>g.id===Number(sq.closest('[data-game]').dataset.game));if(!g?.yourTurn)return;
304 const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
218 const from=Number(sq.dataset.square),p=g.state.board[from];if(p==='.'||(p===p.toUpperCase()?'w':'b')!==g.color)return;
305 const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
219 drag={game:g.id,from,p,x:e.clientX,y:e.clientY,id:e.pointerId,moving:false};
306 const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
307 drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
220});
308});
221document.addEventListener('pointermove',e=>{
309document.addEventListener('pointermove', e =>
222 if(!drag||e.pointerId!==drag.id)return;
310{
223 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);document.body.append(img);}
311 if (!drag || e.pointerId !== drag.id) return;
224 if(drag.moving){e.preventDefault();const img=$('.drag-ghost');img.style.left=e.clientX+'px';img.style.top=e.clientY+'px';}
312 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); document.body.append(img); }
225},{passive:false});
313 if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
226document.addEventListener('pointerup',e=>{
314}, { passive: false });
227 if(!drag||e.pointerId!==drag.id)return;const d=drag;drag=null;$('.drag-ghost')?.remove();
315document.addEventListener('pointerup', e =>
228 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));}
316{
317 if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
318 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)); }
229});
319});
230document.addEventListener('pointercancel',()=>{drag=null;$('.drag-ghost')?.remove();});
320document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
231refresh();setInterval(()=>{if(!document.hidden)refresh();},2500);document.addEventListener('visibilitychange',()=>{if(!document.hidden)refresh();});
321refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
web/lib/Chess.php +6 −0
@@ -76,6 +76,12 @@ final class Chess
76 76 {
77 77 $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
78 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;
79 85 $p=$s['board'][$from];
80 86 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
81 87 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
@@ -76,6 +76,12 @@ final class Chess
76 {
76 {
77 $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
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.');
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;
79 $p=$s['board'][$from];
85 $p=$s['board'][$from];
80 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
86 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
81 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
87 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
web/lib/MoveFeedback.php added +98 −0
@@ -0,0 +1,98 @@
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 {}
@@ -0,0 +1,98 @@
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/bootstrap.php +1 −0
@@ -1,6 +1,7 @@
1 1 <?php
2 2 declare(strict_types=1);
3 3 require_once __DIR__.'/Chess.php';
4 require_once __DIR__.'/MoveFeedback.php';
4 5 ini_set('display_errors','0');
5 6 ini_set('log_errors','1');
6 7 ini_set('error_log',dirname(__DIR__).'/data/php-errors.log');
@@ -1,6 +1,7 @@
1<?php
1<?php
2declare(strict_types=1);
2declare(strict_types=1);
3require_once __DIR__.'/Chess.php';
3require_once __DIR__.'/Chess.php';
4require_once __DIR__.'/MoveFeedback.php';
4ini_set('display_errors','0');
5ini_set('display_errors','0');
5ini_set('log_errors','1');
6ini_set('log_errors','1');
6ini_set('error_log',dirname(__DIR__).'/data/php-errors.log');
7ini_set('error_log',dirname(__DIR__).'/data/php-errors.log');
web/tests/browser.mjs +53 −2
@@ -7,7 +7,7 @@ import path from 'node:path';
7 7 import assert from 'node:assert/strict';
8 8 const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
9 9 const root=await mkdtemp(path.join(web,'tests/artifacts/browser-'));
10 for(const f of ['api.php','index.php','auth.php','callback.php','router.php','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true});
10 for(const f of ['api.php','index.php','auth.php','callback.php','router.php','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true,filter:source=>path.basename(source)!=='tablebase'});
11 11 await mkdir(path.join(root,'data'));
12 12 const port=18081;
13 13 const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'});
@@ -51,9 +51,15 @@ try{
51 51 const held=white.locator(`#your-games [data-game="${id}"]`);
52 52 await held.locator('[data-square="11"]:disabled').waitFor();
53 53 const heldAt=Date.now(),heldRect=await held.boundingBox();
54 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
55 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
56 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
54 57 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
55 58 await white.waitForTimeout(2200);
56 59 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
60 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
61 await white.evaluate(()=>renderGames());
62 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
57 63 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
58 64 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
59 65 await relocated.waitFor({state:'attached'});
@@ -68,6 +74,51 @@ try{
68 74 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();
69 75 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
70 76 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
77 // Real tactical evaluations, using board fixtures only in this disposable game database.
78 async function tacticalFixture(pieces){
79 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
80 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
81 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)]);
82 await white.evaluate(()=>refresh(true));
83 }
84 for(const [quality,pieces,reduced] of [
85 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
86 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
87 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
88 ]){
89 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
90 await tacticalFixture(pieces);
91 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
92 const started=Date.now();
93 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
94 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
95 await pulse.waitFor({state:'attached'});
96 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
97 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
98 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
99 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
100 if(reduced){
101 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
102 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
103 }
104 else{
105 await white.evaluate(()=>renderGames());
106 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
107 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
108 await white.waitForTimeout(250);
109 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
110 }
111 await pulse.waitFor({state:'detached'});
112 const expected=quality==='good'?1:9/14;
113 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
114 await black.evaluate(()=>refresh(true));
115 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');
116 await white.evaluate(()=>renderGames());
117 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
118 }
119 await white.emulateMedia({reducedMotion:'no-preference'});
120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
71 122 // Fixture a legal promotion position in the isolated database.
72 123 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
73 124 fixture.history=[fixture.board.join('')+'w'];
@@ -101,7 +152,7 @@ try{
101 152 await a.setViewportSize({width:1440,height:640});
102 153 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
103 154 const sidebar=await a.locator('#sidebar').boundingBox();
104 assert(sidebar.y>=0&&sidebar.y+sidebar.height<=640,'Desktop sidebar fits viewport while scrolling');
155 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
105 156 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
106 157 const staleId=(await state(a)).games[0].id;
107 158 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)]);
@@ -7,7 +7,7 @@ import path from 'node:path';
7import assert from 'node:assert/strict';
7import assert from 'node:assert/strict';
8const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
8const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
9const root=await mkdtemp(path.join(web,'tests/artifacts/browser-'));
9const root=await mkdtemp(path.join(web,'tests/artifacts/browser-'));
10for(const f of ['api.php','index.php','auth.php','callback.php','router.php','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true});
10for(const f of ['api.php','index.php','auth.php','callback.php','router.php','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true,filter:source=>path.basename(source)!=='tablebase'});
11await mkdir(path.join(root,'data'));
11await mkdir(path.join(root,'data'));
12const port=18081;
12const port=18081;
13const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'});
13const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'});
@@ -51,9 +51,15 @@ try{
51 const held=white.locator(`#your-games [data-game="${id}"]`);
51 const held=white.locator(`#your-games [data-game="${id}"]`);
52 await held.locator('[data-square="11"]:disabled').waitFor();
52 await held.locator('[data-square="11"]:disabled').waitFor();
53 const heldAt=Date.now(),heldRect=await held.boundingBox();
53 const heldAt=Date.now(),heldRect=await held.boundingBox();
54 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
55 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
56 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
54 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
57 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
55 await white.waitForTimeout(2200);
58 await white.waitForTimeout(2200);
56 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
59 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
60 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
61 await white.evaluate(()=>renderGames());
62 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
57 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
63 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
58 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
64 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
59 await relocated.waitFor({state:'attached'});
65 await relocated.waitFor({state:'attached'});
@@ -68,6 +74,51 @@ try{
68 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();
74 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();
69 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
75 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
70 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
76 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
77 // Real tactical evaluations, using board fixtures only in this disposable game database.
78 async function tacticalFixture(pieces){
79 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
80 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
81 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)]);
82 await white.evaluate(()=>refresh(true));
83 }
84 for(const [quality,pieces,reduced] of [
85 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
86 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
87 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
88 ]){
89 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
90 await tacticalFixture(pieces);
91 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
92 const started=Date.now();
93 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
94 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
95 await pulse.waitFor({state:'attached'});
96 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
97 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
98 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
99 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
100 if(reduced){
101 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
102 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
103 }
104 else{
105 await white.evaluate(()=>renderGames());
106 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
107 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
108 await white.waitForTimeout(250);
109 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
110 }
111 await pulse.waitFor({state:'detached'});
112 const expected=quality==='good'?1:9/14;
113 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
114 await black.evaluate(()=>refresh(true));
115 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');
116 await white.evaluate(()=>renderGames());
117 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
118 }
119 await white.emulateMedia({reducedMotion:'no-preference'});
120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
71 // Fixture a legal promotion position in the isolated database.
122 // Fixture a legal promotion position in the isolated database.
72 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
123 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
73 fixture.history=[fixture.board.join('')+'w'];
124 fixture.history=[fixture.board.join('')+'w'];
@@ -101,7 +152,7 @@ try{
101 await a.setViewportSize({width:1440,height:640});
152 await a.setViewportSize({width:1440,height:640});
102 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
153 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
103 const sidebar=await a.locator('#sidebar').boundingBox();
154 const sidebar=await a.locator('#sidebar').boundingBox();
104 assert(sidebar.y>=0&&sidebar.y+sidebar.height<=640,'Desktop sidebar fits viewport while scrolling');
155 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
105 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
156 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
106 const staleId=(await state(a)).games[0].id;
157 const staleId=(await state(a)).games[0].id;
107 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)]);
158 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)]);
web/tests/feedback.php added +47 −0
@@ -0,0 +1,47 @@
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";
@@ -0,0 +1,47 @@
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 +5 −2
@@ -29,7 +29,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
29 29 root = Path(tmp)
30 30 for name in ['api.php', 'index.php', 'auth.php', 'callback.php', 'router.php']:
31 31 shutil.copy(WEB / name, root / name)
32 shutil.copytree(WEB / 'lib', root / 'lib')
32 shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase'))
33 33 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
34 34 (root / 'data').mkdir()
35 35 with socket.socket() as sock:
@@ -122,7 +122,10 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
122 122 current = white.game(id)
123 123 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
124 124 move = current['legal'][0]
125 white.post('move', game=id, version=current['version'], **move)
125 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
126 response = white.post('move', game=id, version=current['version'], **move)
127 check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate')
128 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
126 129 white.post('move', game=id, version=current['version'], **move, expected=409)
127 130 check(black.game(id)['yourTurn'], 'Turn passes')
128 131 black.game_action('resign', id)
@@ -29,7 +29,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
29 root = Path(tmp)
29 root = Path(tmp)
30 for name in ['api.php', 'index.php', 'auth.php', 'callback.php', 'router.php']:
30 for name in ['api.php', 'index.php', 'auth.php', 'callback.php', 'router.php']:
31 shutil.copy(WEB / name, root / name)
31 shutil.copy(WEB / name, root / name)
32 shutil.copytree(WEB / 'lib', root / 'lib')
32 shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase'))
33 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
33 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
34 (root / 'data').mkdir()
34 (root / 'data').mkdir()
35 with socket.socket() as sock:
35 with socket.socket() as sock:
@@ -122,7 +122,10 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
122 current = white.game(id)
122 current = white.game(id)
123 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
123 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
124 move = current['legal'][0]
124 move = current['legal'][0]
125 white.post('move', game=id, version=current['version'], **move)
125 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
126 response = white.post('move', game=id, version=current['version'], **move)
127 check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate')
128 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
126 white.post('move', game=id, version=current['version'], **move, expected=409)
129 white.post('move', game=id, version=current['version'], **move, expected=409)
127 check(black.game(id)['yourTurn'], 'Turn passes')
130 check(black.game(id)['yourTurn'], 'Turn passes')
128 black.game_action('resign', id)
131 black.game_action('resign', id)
web/tests/startup.py +1 −1
@@ -11,7 +11,7 @@ ARTIFACTS = WEB / 'tests/artifacts'
11 11 ARTIFACTS.mkdir(exist_ok=True)
12 12 with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
13 13 root = Path(tmp)
14 shutil.copytree(WEB / 'lib', root / 'lib')
14 shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase'))
15 15 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
16 16 (root / 'data').mkdir()
17 17 def startup():
@@ -11,7 +11,7 @@ ARTIFACTS = WEB / 'tests/artifacts'
11ARTIFACTS.mkdir(exist_ok=True)
11ARTIFACTS.mkdir(exist_ok=True)
12with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
12with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
13 root = Path(tmp)
13 root = Path(tmp)
14 shutil.copytree(WEB / 'lib', root / 'lib')
14 shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase'))
15 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
15 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
16 (root / 'data').mkdir()
16 (root / 'data').mkdir()
17 def startup():
17 def startup():