Add Elo matchmaking and opponent friend requests
@@ -66,8 +66,18 @@ The top grid includes your moves, incoming challenges and finished games. Oppone
66
66
67
67
A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect.
68
68
69
Click an opponent's name above a game to open the same rivalry statistics shown from the friends list. Non-friends can send a friend request; incoming requests appear below the friends list with Accept/Reject controls. Requests persist across sessions, and only the recipient can accept or reject them. Acceptance adds both players to each other's friends lists. Duplicate requests do not create extra entries; accepting a friend invitation link also clears any pending request between those players. Pending requests are included in data exports.
70
69
71
Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. **Account → Export my data (JSON)** exports the user's profile, relationships, invitations, games and historical results.
70
72
73
## Ratings and matchmaking
74
75
Existing and new accounts start at 1200 Elo. Results completed after this update use Elo with K=32 (win 1, draw 0.5, loss 0), rounded to whole points with equal and opposite changes. Past results are preserved without retroactive rating changes. All completed games count, including friend challenges, match links and rematches. Stopped unfinished games do not count. Ratings and a per-result ledger are written in the same transaction as the result; rematches reuse a tile but get their own result and rating change. Ratings appear in the account summary, friends list and opponent headers, and rating history is included in data exports.
76
77
**New game → Challenge a random player** adds one persistent search per account, with cancellation and retry after expiry. Searches last 24 hours, including while offline. Joining immediately checks the entire pool; authenticated state requests otherwise trigger a transactionally throttled check at most once per minute. There is no background worker. Each player's allowed difference starts at 100, grows by 50 per elapsed minute and stops at 500. Both players must allow the difference. The oldest search selects its closest eligible opponent (ties prefer older searches), then processing continues through the remaining pool. Pairing creates one active game with random colors and consumes both entries atomically. Expired entries cannot match and display a retry option. A match does not create a friendship.
78
79
The integration tests exercise rating updates, rematches, duplicate results, concurrent joins, cancellation, expiry, widening, the maximum difference and whole-pool matching. Browser tests cover joining from below the invite link, persistence after reload, cancellation, automatic game appearance and visible ratings.
80
71
81
## Avatars
72
82
73
83
Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.
@@ -66,8 +66,18 @@ The top grid includes your moves, incoming challenges and finished games. Oppone66
66
67
A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect.67
A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect.68
68
69
Click an opponent's name above a game to open the same rivalry statistics shown from the friends list. Non-friends can send a friend request; incoming requests appear below the friends list with Accept/Reject controls. Requests persist across sessions, and only the recipient can accept or reject them. Acceptance adds both players to each other's friends lists. Duplicate requests do not create extra entries; accepting a friend invitation link also clears any pending request between those players. Pending requests are included in data exports.70
69
Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. **Account → Export my data (JSON)** exports the user's profile, relationships, invitations, games and historical results.71
Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. **Account → Export my data (JSON)** exports the user's profile, relationships, invitations, games and historical results.70
72
73
## Ratings and matchmaking74
75
Existing and new accounts start at 1200 Elo. Results completed after this update use Elo with K=32 (win 1, draw 0.5, loss 0), rounded to whole points with equal and opposite changes. Past results are preserved without retroactive rating changes. All completed games count, including friend challenges, match links and rematches. Stopped unfinished games do not count. Ratings and a per-result ledger are written in the same transaction as the result; rematches reuse a tile but get their own result and rating change. Ratings appear in the account summary, friends list and opponent headers, and rating history is included in data exports.76
77
**New game → Challenge a random player** adds one persistent search per account, with cancellation and retry after expiry. Searches last 24 hours, including while offline. Joining immediately checks the entire pool; authenticated state requests otherwise trigger a transactionally throttled check at most once per minute. There is no background worker. Each player's allowed difference starts at 100, grows by 50 per elapsed minute and stops at 500. Both players must allow the difference. The oldest search selects its closest eligible opponent (ties prefer older searches), then processing continues through the remaining pool. Pairing creates one active game with random colors and consumes both entries atomically. Expired entries cannot match and display a retry option. A match does not create a friendship.78
79
The integration tests exercise rating updates, rematches, duplicate results, concurrent joins, cancellation, expiry, widening, the maximum difference and whole-pool matching. Browser tests cover joining from below the invite link, persistence after reload, cancellation, automatic game appearance and visible ratings.80
71
## Avatars81
## Avatars72
82
73
Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.83
Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.@@ -16,16 +16,26 @@ try {
16
16
header('Content-Disposition: attachment; filename="microchess-data.json"');
17
17
jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
18
18
'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
19
'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
19
20
'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),
21
'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
22
'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
20
23
'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
21
24
'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
22
25
}
23
26
if ($action!=='state') fail('Unknown action.',404);
27
if ((int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()<=time()-60) {
28
db()->exec('BEGIN IMMEDIATE');
29
matchPlayers();
30
db()->exec('COMMIT');
31
}
24
32
$friends=query('SELECT u.*,av.avatar FROM friends f JOIN users u ON u.id=CASE WHEN f.a=? THEN f.b ELSE f.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE f.a=? OR f.b=? ORDER BY u.name',[$u,$u,$u])->fetchAll();
25
33
foreach ($friends as &$f) {
26
$rows=query('SELECT winner FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$f['id'],$f['id'],$u])->fetchAll();
27
$f['wins']=count(array_filter($rows,fn($r)=>$r['winner']===$u));$f['ties']=count(array_filter($rows,fn($r)=>$r['winner']===null));$f['losses']=count($rows)-$f['wins']-$f['ties'];
34
$f['rating']=(int)profile($f['id'])['rating'];
35
$f+=rivalry($u,$f['id']);
28
36
} unset($f);
37
$requests=query('SELECT u.id,u.name,av.avatar,r.sender FROM friend_requests r JOIN users u ON u.id=CASE WHEN r.a=? THEN r.b ELSE r.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE r.a=? OR r.b=? ORDER BY r.created,u.id',[$u,$u,$u])->fetchAll();
38
foreach ($requests as &$request) {$request['incoming']=$request['sender']!==$u;unset($request['sender']);} unset($request);
29
39
$games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();
30
40
$invite=null;
31
41
if (isset($_GET['invite'])) {
@@ -34,7 +44,8 @@ try {
34
44
elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];
35
45
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];
36
46
}
37
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite]);
47
$joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();
48
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);
38
49
}
39
50
if ($method!=='POST') fail('Method not allowed.',405);
40
51
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);
@@ -52,7 +63,27 @@ try {
52
63
}
53
64
db()->exec('BEGIN IMMEDIATE');
54
65
$out=['ok'=>true];
55
if ($action==='set_avatar') {
66
if (in_array($action,['send_friend_request','accept_friend_request','reject_friend_request'],true)) {
67
$other=$in['friend']??null;
68
if (!is_string($other) || $other===$u) throw new DomainException('Choose another player.');
69
$p=pair($u,$other);
70
if ($action==='send_friend_request') {
71
if (!query('SELECT 1 FROM games WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('Player not found.');
72
if (query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('You are already friends.');
73
$sender=query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn();
74
if ($sender!==false && $sender!==$u) throw new DomainException('This player has already sent you a friend request.');
75
query('INSERT OR IGNORE INTO friend_requests(a,b,sender,created) VALUES(?,?,?,?)',[$p[0],$p[1],$u,time()]);
76
} else {
77
if (query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn()!==$other) throw new DomainException('This friend request is no longer available.');
78
if ($action==='accept_friend_request') befriend($u,$other);
79
else query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
80
}
81
} elseif ($action==='join_matchmaking') {
82
query('INSERT INTO matchmaking(user_id,joined) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET joined=excluded.joined WHERE matchmaking.joined<=?',[$u,time(),time()-86400]);
83
matchPlayers(true);
84
} elseif ($action==='cancel_matchmaking') {
85
query('DELETE FROM matchmaking WHERE user_id=?',[$u]);
86
} elseif ($action==='set_avatar') {
56
87
$avatar=$in['avatar']??null;
57
88
if ($avatar===null) {
58
89
$avatars=avatarCatalog();
@@ -71,7 +102,7 @@ try {
71
102
$l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();
72
103
if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');
73
104
if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');
74
if ($l['kind']==='friend') query('INSERT OR IGNORE INTO friends VALUES(?,?)',pair($u,$l['owner']));
105
if ($l['kind']==='friend') befriend($u,$l['owner']);
75
106
else $out['game']=startGame($l['owner'],$u);
76
107
query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);
77
108
} elseif ($action==='remove_friend' || $action==='challenge') {
@@ -16,16 +16,26 @@ try {16
header('Content-Disposition: attachment; filename="microchess-data.json"');16
header('Content-Disposition: attachment; filename="microchess-data.json"');17
jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),17
jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),18
'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),18
'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),19
'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),19
'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),20
'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),21
'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),22
'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),20
'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),23
'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),21
'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);24
'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);22
}25
}23
if ($action!=='state') fail('Unknown action.',404);26
if ($action!=='state') fail('Unknown action.',404);27
if ((int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()<=time()-60) {28
db()->exec('BEGIN IMMEDIATE');29
matchPlayers();30
db()->exec('COMMIT');31
}24
$friends=query('SELECT u.*,av.avatar FROM friends f JOIN users u ON u.id=CASE WHEN f.a=? THEN f.b ELSE f.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE f.a=? OR f.b=? ORDER BY u.name',[$u,$u,$u])->fetchAll();32
$friends=query('SELECT u.*,av.avatar FROM friends f JOIN users u ON u.id=CASE WHEN f.a=? THEN f.b ELSE f.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE f.a=? OR f.b=? ORDER BY u.name',[$u,$u,$u])->fetchAll();25
foreach ($friends as &$f) {33
foreach ($friends as &$f) {26
$rows=query('SELECT winner FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$f['id'],$f['id'],$u])->fetchAll();34
$f['rating']=(int)profile($f['id'])['rating'];27
$f['wins']=count(array_filter($rows,fn($r)=>$r['winner']===$u));$f['ties']=count(array_filter($rows,fn($r)=>$r['winner']===null));$f['losses']=count($rows)-$f['wins']-$f['ties'];35
$f+=rivalry($u,$f['id']);28
} unset($f);36
} unset($f);37
$requests=query('SELECT u.id,u.name,av.avatar,r.sender FROM friend_requests r JOIN users u ON u.id=CASE WHEN r.a=? THEN r.b ELSE r.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE r.a=? OR r.b=? ORDER BY r.created,u.id',[$u,$u,$u])->fetchAll();38
foreach ($requests as &$request) {$request['incoming']=$request['sender']!==$u;unset($request['sender']);} unset($request);29
$games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();39
$games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();30
$invite=null;40
$invite=null;31
if (isset($_GET['invite'])) {41
if (isset($_GET['invite'])) {@@ -34,7 +44,8 @@ try {34
elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];44
elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];35
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];45
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];36
}46
}37
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite]);47
$joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();48
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);38
}49
}39
if ($method!=='POST') fail('Method not allowed.',405);50
if ($method!=='POST') fail('Method not allowed.',405);40
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);51
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);@@ -52,7 +63,27 @@ try {52
}63
}53
db()->exec('BEGIN IMMEDIATE');64
db()->exec('BEGIN IMMEDIATE');54
$out=['ok'=>true];65
$out=['ok'=>true];55
if ($action==='set_avatar') {66
if (in_array($action,['send_friend_request','accept_friend_request','reject_friend_request'],true)) {67
$other=$in['friend']??null;68
if (!is_string($other) || $other===$u) throw new DomainException('Choose another player.');69
$p=pair($u,$other);70
if ($action==='send_friend_request') {71
if (!query('SELECT 1 FROM games WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('Player not found.');72
if (query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('You are already friends.');73
$sender=query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn();74
if ($sender!==false && $sender!==$u) throw new DomainException('This player has already sent you a friend request.');75
query('INSERT OR IGNORE INTO friend_requests(a,b,sender,created) VALUES(?,?,?,?)',[$p[0],$p[1],$u,time()]);76
} else {77
if (query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn()!==$other) throw new DomainException('This friend request is no longer available.');78
if ($action==='accept_friend_request') befriend($u,$other);79
else query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);80
}81
} elseif ($action==='join_matchmaking') {82
query('INSERT INTO matchmaking(user_id,joined) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET joined=excluded.joined WHERE matchmaking.joined<=?',[$u,time(),time()-86400]);83
matchPlayers(true);84
} elseif ($action==='cancel_matchmaking') {85
query('DELETE FROM matchmaking WHERE user_id=?',[$u]);86
} elseif ($action==='set_avatar') {56
$avatar=$in['avatar']??null;87
$avatar=$in['avatar']??null;57
if ($avatar===null) {88
if ($avatar===null) {58
$avatars=avatarCatalog();89
$avatars=avatarCatalog();@@ -71,7 +102,7 @@ try {71
$l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();102
$l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();72
if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');103
if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');73
if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');104
if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');74
if ($l['kind']==='friend') query('INSERT OR IGNORE INTO friends VALUES(?,?)',pair($u,$l['owner']));105
if ($l['kind']==='friend') befriend($u,$l['owner']);75
else $out['game']=startGame($l['owner'],$u);106
else $out['game']=startGame($l['owner'],$u);76
query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);107
query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);77
} elseif ($action==='remove_friend' || $action==='challenge') {108
} elseif ($action==='remove_friend' || $action==='challenge') {@@ -271,6 +271,12 @@ main {
271
271
white-space: nowrap
272
272
}
273
273
274
.rating {
275
font-size: 11px;
276
font-weight: 500;
277
color: #56634b;
278
}
279
274
280
.color-tag {
275
281
margin-left: auto;
276
282
font-size: 10px;
@@ -1388,4 +1394,24 @@ dialog .avatar-credits {
1388
1394
.material-bar:focus-visible {
1389
1395
outline: 2px solid #c19042;
1390
1396
outline-offset: 3px
1391
}
1397
}
1398
1399
.opponent-name {
1400
padding: 0;
1401
border: 0;
1402
background: transparent;
1403
color: inherit;
1404
font: inherit;
1405
cursor: pointer;
1406
}
1407
.opponent-name:hover { text-decoration: underline; }
1408
.friend-request {
1409
display: flex;
1410
align-items: center;
1411
gap: 10px;
1412
margin: 12px 0;
1413
}
1414
.friend-request > div { min-width: 0; }
1415
.friend-request strong { overflow-wrap: anywhere; font-size: 13px; }
1416
.friend-request .actions { margin-top: 8px; flex-wrap: wrap; }
1417
.friend-request button { padding: 7px 10px; font-size: 12px; }
@@ -271,6 +271,12 @@ main {271
white-space: nowrap271
white-space: nowrap272
}272
}273
273
274
.rating {275
font-size: 11px;276
font-weight: 500;277
color: #56634b;278
}279
274
.color-tag {280
.color-tag {275
margin-left: auto;281
margin-left: auto;276
font-size: 10px;282
font-size: 10px;@@ -1388,4 +1394,24 @@ dialog .avatar-credits {1388
.material-bar:focus-visible {1394
.material-bar:focus-visible {1389
outline: 2px solid #c19042;1395
outline: 2px solid #c19042;1390
outline-offset: 3px1396
outline-offset: 3px1391
}1397
}1398
1399
.opponent-name {1400
padding: 0;1401
border: 0;1402
background: transparent;1403
color: inherit;1404
font: inherit;1405
cursor: pointer;1406
}1407
.opponent-name:hover { text-decoration: underline; }1408
.friend-request {1409
display: flex;1410
align-items: center;1411
gap: 10px;1412
margin: 12px 0;1413
}1414
.friend-request > div { min-width: 0; }1415
.friend-request strong { overflow-wrap: anywhere; font-size: 13px; }1416
.friend-request .actions { margin-top: 8px; flex-wrap: wrap; }1417
.friend-request button { padding: 7px 10px; font-size: 12px; }@@ -40,7 +40,7 @@ let moveHoldTimer;
40
40
let inviteToken = new URLSearchParams(location.search).get('invite');
41
41
const modal = $('#modal');
42
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(); }
43
function showModal (html) { delete $('#modal-content').dataset.rivalry; modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44
44
function closeModal () { modal.close(); }
45
45
$('#modal-close').onclick = closeModal;
46
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(); } });
@@ -98,7 +98,7 @@ async function refresh (force = false)
98
98
state = data;
99
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
100
const signature = JSON.stringify(data);
101
if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); }
101
if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); }
102
102
if (data.invite && !inviteShown)
103
103
{
104
104
inviteShown = true; const i = data.invite;
@@ -134,7 +134,7 @@ function renderGames ()
134
134
const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135
135
const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136
136
const waiting = state.games.filter(g => !yours.includes(g));
137
$('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length;
137
$('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
138
138
// Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139
139
const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140
140
{
@@ -142,7 +142,7 @@ function renderGames ()
142
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
143
}));
144
144
$('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145
$('#waiting-games').innerHTML = waiting.map(card).join('') || empty(false);
145
$('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
146
146
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147
147
for (const el of document.querySelectorAll('.material-bar'))
148
148
{
@@ -173,7 +173,7 @@ function card (g)
173
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"></span>'}</div>`;
174
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
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>`;
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><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<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
177
}
178
178
function materialBar (g)
179
179
{
@@ -234,8 +234,34 @@ function board (g)
234
234
function renderFriends ()
235
235
{
236
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>`;
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.rating} Elo · ${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
const incoming = state.friendRequests.filter(r => r.incoming);
239
$('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';
240
$('#friend-count').textContent = state.friends.length + incoming.length;
241
$('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span>`;
242
}
243
function showRivalry (id)
244
{
245
const friend = state.friends.find(f => f.id === id);
246
const game = state.games.find(g => g.opponentId === id);
247
const f = friend || (game && { id, name: game.opponent, ...game.rivalry });
248
if (!f) return;
249
const request = state.friendRequests.find(r => r.id === id);
250
const actions = friend
251
? '<button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button>'
252
: request?.incoming
253
? `<button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(id)}">Accept friend request</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(id)}">Reject</button>`
254
: request
255
? '<button class="secondary" disabled>Friend request sent</button>'
256
: `<button class="primary" data-request-action="send_friend_request" data-request-user="${esc(id)}">Send friend request</button>`;
257
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">${actions}</div>`);
258
$('#modal-content').dataset.friend = id;
259
$('#modal-content').dataset.rivalry = id;
260
}
261
function refreshRivalry ()
262
{
263
const id = $('#modal-content').dataset.rivalry;
264
if (modal.open && id) showRivalry(id);
239
265
}
240
266
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
267
function chooseSquare (g, i)
@@ -255,22 +281,37 @@ function attemptMove (g, from, to, promote)
255
281
const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
256
282
action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
257
283
}
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 the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>`); }); }
284
function matchmakingCard ()
285
{
286
const searching = state.matchmaking.status === 'searching';
287
return `<article class="game-card"><div class="pending-content"><span class="big-icon">♘</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
288
}
289
function renderMatchmaking ()
290
{
291
const target = $('#matchmaking-actions');
292
if (!target || !state) return;
293
target.innerHTML = state.matchmaking?.status === 'searching'
294
? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
295
: '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
296
}
297
async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
259
298
if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
260
299
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>`); };
300
$('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><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
301
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
302
document.addEventListener('click', e =>
264
303
{
265
304
const el = e.target.closest('button'); if (!el) return;
266
305
const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
306
if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
307
if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
267
308
if (el.id === 'avatar-button') chooseAvatar();
268
309
if (el.dataset.createLink) createLink(el.dataset.createLink);
269
310
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 }); }
311
if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
271
312
if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
272
313
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; }
314
if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
274
315
});
275
316
$('#modal-content').addEventListener('click', async e =>
276
317
{
@@ -40,7 +40,7 @@ let moveHoldTimer;40
let inviteToken = new URLSearchParams(location.search).get('invite');40
let inviteToken = new URLSearchParams(location.search).get('invite');41
const modal = $('#modal');41
const modal = $('#modal');42
function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }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(); }43
function showModal (html) { delete $('#modal-content').dataset.rivalry; modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }44
function closeModal () { modal.close(); }44
function closeModal () { modal.close(); }45
$('#modal-close').onclick = closeModal;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(); } });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(); } });@@ -98,7 +98,7 @@ async function refresh (force = false)98
state = data;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; } }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);100
const signature = JSON.stringify(data);101
if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); }101
if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); }102
if (data.invite && !inviteShown)102
if (data.invite && !inviteShown)103
{103
{104
inviteShown = true; const i = data.invite;104
inviteShown = true; const i = data.invite;@@ -134,7 +134,7 @@ function renderGames ()134
const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);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));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));136
const waiting = state.games.filter(g => !yours.includes(g));137
$('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length;137
$('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);138
// Continue from the visible fill even when polling/selection recreates the cards mid-animation.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 =>139
const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>140
{140
{@@ -142,7 +142,7 @@ function renderGames ()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 }];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
}));143
}));144
$('#your-games').innerHTML = yours.map(card).join('') || empty(true);144
$('#your-games').innerHTML = yours.map(card).join('') || empty(true);145
$('#waiting-games').innerHTML = waiting.map(card).join('') || empty(false);145
$('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);146
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;146
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;147
for (const el of document.querySelectorAll('.material-bar'))147
for (const el of document.querySelectorAll('.material-bar'))148
{148
{@@ -173,7 +173,7 @@ function card (g)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"></span>'}</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"></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>`;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>`;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>`;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><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<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
}177
}178
function materialBar (g)178
function materialBar (g)179
{179
{@@ -234,8 +234,34 @@ function board (g)234
function renderFriends ()234
function renderFriends ()235
{235
{236
$('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;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>';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.rating} Elo · ${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>`;238
const incoming = state.friendRequests.filter(r => r.incoming);239
$('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';240
$('#friend-count').textContent = state.friends.length + incoming.length;241
$('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span>`;242
}243
function showRivalry (id)244
{245
const friend = state.friends.find(f => f.id === id);246
const game = state.games.find(g => g.opponentId === id);247
const f = friend || (game && { id, name: game.opponent, ...game.rivalry });248
if (!f) return;249
const request = state.friendRequests.find(r => r.id === id);250
const actions = friend251
? '<button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button>'252
: request?.incoming253
? `<button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(id)}">Accept friend request</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(id)}">Reject</button>`254
: request255
? '<button class="secondary" disabled>Friend request sent</button>'256
: `<button class="primary" data-request-action="send_friend_request" data-request-user="${esc(id)}">Send friend request</button>`;257
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">${actions}</div>`);258
$('#modal-content').dataset.friend = id;259
$('#modal-content').dataset.rivalry = id;260
}261
function refreshRivalry ()262
{263
const id = $('#modal-content').dataset.rivalry;264
if (modal.open && id) showRivalry(id);239
}265
}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; }266
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)267
function chooseSquare (g, i)@@ -255,22 +281,37 @@ function attemptMove (g, from, to, promote)255
const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;281
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 });282
action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });257
}283
}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 the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>`); }); }284
function matchmakingCard ()285
{286
const searching = state.matchmaking.status === 'searching';287
return `<article class="game-card"><div class="pending-content"><span class="big-icon">♘</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;288
}289
function renderMatchmaking ()290
{291
const target = $('#matchmaking-actions');292
if (!target || !state) return;293
target.innerHTML = state.matchmaking?.status === 'searching'294
? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'295
: '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';296
}297
async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }259
if ($('#match-link')) $('#match-link').onclick = () => createLink('match');298
if ($('#match-link')) $('#match-link').onclick = () => createLink('match');260
if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');299
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>`); };300
$('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><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>`);301
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 =>302
document.addEventListener('click', e =>264
{303
{265
const el = e.target.closest('button'); if (!el) return;304
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));305
const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));306
if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });307
if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });267
if (el.id === 'avatar-button') chooseAvatar();308
if (el.id === 'avatar-button') chooseAvatar();268
if (el.dataset.createLink) createLink(el.dataset.createLink);309
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)); }310
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 }); }311
if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }271
if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);312
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(); }313
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; }314
if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);274
});315
});275
$('#modal-content').addEventListener('click', async e =>316
$('#modal-content').addEventListener('click', async e =>276
{317
{@@ -21,7 +21,7 @@ $invite=is_string($_GET['invite']??null)&&preg_match('/^[a-f0-9]{48}$/D',$_GET['
21
21
<div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>
22
22
<div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>
23
23
<footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>
24
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
24
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
25
25
<?php endif ?>
26
26
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>
27
27
<div id="toast" role="status" aria-live="polite"></div>
@@ -21,7 +21,7 @@ $invite=is_string($_GET['invite']??null)&&preg_match('/^[a-f0-9]{48}$/D',$_GET['21
<div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>21
<div id="your-games" class="game-grid"><div class="empty">Loading your games…</div></div>22
<div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>22
<div class="section-heading waiting-heading"><h2><span class="status-dot muted-dot"></span>Not your turn <span id="waiting-count" class="count">0</span></h2></div><div id="waiting-games" class="game-grid"></div>23
<footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>23
<footer><button id="rules-button" class="text-button">How to play ↗</button></footer></main>24
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>24
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>25
<?php endif ?>25
<?php endif ?>26
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>26
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>27
<div id="toast" role="status" aria-live="polite"></div>27
<div id="toast" role="status" aria-live="polite"></div>@@ -19,6 +19,7 @@ function db(): PDO {
19
19
CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
20
20
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
21
21
CREATE TABLE IF NOT EXISTS friends (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), PRIMARY KEY(a,b), CHECK(a<b));
22
CREATE TABLE IF NOT EXISTS friend_requests (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), sender TEXT NOT NULL REFERENCES users(id), created INTEGER NOT NULL, PRIMARY KEY(a,b), CHECK(a<b), CHECK(sender=a OR sender=b));
22
23
CREATE TABLE IF NOT EXISTS links (token TEXT PRIMARY KEY, owner TEXT NOT NULL REFERENCES users(id), kind TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);
23
24
CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);
24
25
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
@@ -52,6 +53,11 @@ function db(): PDO {
52
53
$q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');
53
54
$q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
54
55
}
56
$db->exec('CREATE TABLE IF NOT EXISTS ratings (user_id TEXT PRIMARY KEY REFERENCES users(id), rating INTEGER NOT NULL DEFAULT 1200, played INTEGER NOT NULL DEFAULT 0);
57
CREATE TABLE IF NOT EXISTS rating_changes (result_id INTEGER PRIMARY KEY REFERENCES results(id), a_before INTEGER NOT NULL, b_before INTEGER NOT NULL, delta INTEGER NOT NULL);
58
CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
59
CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
60
INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
55
61
return $db;
56
62
}
57
63
function activityTriggers(PDO $db): void {
@@ -60,7 +66,7 @@ function activityTriggers(PDO $db): void {
60
66
}
61
67
function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
62
68
function profile(string $id): array {
63
return query('SELECT u.*,a.avatar FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id WHERE u.id=?',[$id])->fetch();
69
return query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id WHERE u.id=?',[$id])->fetch();
64
70
}
65
71
function avatarCatalog(): array {
66
72
static $avatars;
@@ -143,9 +149,49 @@ function user(): string {
143
149
function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;}
144
150
function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;}
145
151
function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; }
152
function rivalry(string $u,string $other): array {
153
$r=query('SELECT COUNT(*) AS total,COALESCE(SUM(winner=?),0) AS wins,COALESCE(SUM(winner IS NULL),0) AS ties FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$u,$other,$other,$u])->fetch();
154
return ['wins'=>(int)$r['wins'],'losses'=>(int)$r['total']-(int)$r['wins']-(int)$r['ties'],'ties'=>(int)$r['ties']];
155
}
156
function befriend(string $a,string $b): void {
157
$p=pair($a,$b);
158
query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
159
query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
160
}
146
161
function finishGame(array $g,?string $winner,string $reason,array $s): void {
147
query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=?",[$winner,$reason,json_encode($s),$g['id']]);
162
$finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($s),$g['id'],$g['version']]);
163
if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
148
164
query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);
165
$result=(int)db()->lastInsertId();
166
$a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
167
$score=$winner===null?0.5:($winner===$g['a']?1:0);
168
$delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
169
query('INSERT INTO rating_changes VALUES(?,?,?,?)',[$result,$a,$b,$delta]);
170
foreach ([[$g['a'],$a+$delta],[$g['b'],$b-$delta]] as [$id,$rating]) {
171
query('INSERT INTO ratings(user_id,rating,played) VALUES(?,?,1) ON CONFLICT(user_id) DO UPDATE SET rating=excluded.rating,played=ratings.played+1',[$id,$rating]);
172
}
173
}
174
// Called inside BEGIN IMMEDIATE: selecting pairs and consuming entries is atomic.
175
function matchPlayers(bool $force=false): void {
176
$now=time();
177
if (!$force && (int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()>$now-60) return;
178
query('UPDATE matchmaking_clock SET checked=? WHERE id=1',[$now]);
179
$pool=query('SELECT m.*,COALESCE(r.rating,1200) AS rating FROM matchmaking m LEFT JOIN ratings r ON r.user_id=m.user_id WHERE m.joined>? ORDER BY m.joined,m.user_id',[$now-86400])->fetchAll();
180
$used=[];
181
foreach ($pool as $a) {
182
if (isset($used[$a['user_id']])) continue;
183
$best=null;$distance=PHP_INT_MAX;
184
foreach ($pool as $b) {
185
if ($a['user_id']===$b['user_id'] || isset($used[$b['user_id']])) continue;
186
$gap=abs($a['rating']-$b['rating']);
187
$limit=min(500,100+50*intdiv(max(0,$now-$a['joined']),60),100+50*intdiv(max(0,$now-$b['joined']),60));
188
if ($gap<=$limit && $gap<$distance) {$best=$b;$distance=$gap;}
189
}
190
if ($best===null) continue;
191
startGame($a['user_id'],$best['user_id']);
192
query('DELETE FROM matchmaking WHERE user_id IN (?,?)',[$a['user_id'],$best['user_id']]);
193
$used[$a['user_id']]=$used[$best['user_id']]=true;
194
}
149
195
}
150
196
function startGame(string $a,string $b): int {
151
197
query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,random_int(0,1)?$a:$b,json_encode(Chess::initial()),time()]);
@@ -156,7 +202,7 @@ function gameView(array $g,string $u): array {
156
202
$opponent=profile($other);
157
203
$s=$g['state']?json_decode($g['state'],true):null;
158
204
$color=$g['white']===$u?'w':'b';
159
return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
205
return ['id'=>(int)$g['id'],'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
160
206
'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
161
207
'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
162
208
'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
@@ -19,6 +19,7 @@ function db(): PDO {19
CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);19
CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);20
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);20
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);21
CREATE TABLE IF NOT EXISTS friends (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), PRIMARY KEY(a,b), CHECK(a<b));21
CREATE TABLE IF NOT EXISTS friends (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), PRIMARY KEY(a,b), CHECK(a<b));22
CREATE TABLE IF NOT EXISTS friend_requests (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), sender TEXT NOT NULL REFERENCES users(id), created INTEGER NOT NULL, PRIMARY KEY(a,b), CHECK(a<b), CHECK(sender=a OR sender=b));22
CREATE TABLE IF NOT EXISTS links (token TEXT PRIMARY KEY, owner TEXT NOT NULL REFERENCES users(id), kind TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);23
CREATE TABLE IF NOT EXISTS links (token TEXT PRIMARY KEY, owner TEXT NOT NULL REFERENCES users(id), kind TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);23
CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);24
CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);24
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);25
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);@@ -52,6 +53,11 @@ function db(): PDO {52
$q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');53
$q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');53
$q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);54
$q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);54
}55
}56
$db->exec('CREATE TABLE IF NOT EXISTS ratings (user_id TEXT PRIMARY KEY REFERENCES users(id), rating INTEGER NOT NULL DEFAULT 1200, played INTEGER NOT NULL DEFAULT 0);57
CREATE TABLE IF NOT EXISTS rating_changes (result_id INTEGER PRIMARY KEY REFERENCES results(id), a_before INTEGER NOT NULL, b_before INTEGER NOT NULL, delta INTEGER NOT NULL);58
CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);59
CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);60
INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');55
return $db;61
return $db;56
}62
}57
function activityTriggers(PDO $db): void {63
function activityTriggers(PDO $db): void {@@ -60,7 +66,7 @@ function activityTriggers(PDO $db): void {60
}66
}61
function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }67
function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }62
function profile(string $id): array {68
function profile(string $id): array {63
return query('SELECT u.*,a.avatar FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id WHERE u.id=?',[$id])->fetch();69
return query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id WHERE u.id=?',[$id])->fetch();64
}70
}65
function avatarCatalog(): array {71
function avatarCatalog(): array {66
static $avatars;72
static $avatars;@@ -143,9 +149,49 @@ function user(): string {143
function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;}149
function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;}144
function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;}150
function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;}145
function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; }151
function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; }152
function rivalry(string $u,string $other): array {153
$r=query('SELECT COUNT(*) AS total,COALESCE(SUM(winner=?),0) AS wins,COALESCE(SUM(winner IS NULL),0) AS ties FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$u,$other,$other,$u])->fetch();154
return ['wins'=>(int)$r['wins'],'losses'=>(int)$r['total']-(int)$r['wins']-(int)$r['ties'],'ties'=>(int)$r['ties']];155
}156
function befriend(string $a,string $b): void {157
$p=pair($a,$b);158
query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);159
query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);160
}146
function finishGame(array $g,?string $winner,string $reason,array $s): void {161
function finishGame(array $g,?string $winner,string $reason,array $s): void {147
query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=?",[$winner,$reason,json_encode($s),$g['id']]);162
$finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($s),$g['id'],$g['version']]);163
if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');148
query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);164
query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);165
$result=(int)db()->lastInsertId();166
$a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];167
$score=$winner===null?0.5:($winner===$g['a']?1:0);168
$delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));169
query('INSERT INTO rating_changes VALUES(?,?,?,?)',[$result,$a,$b,$delta]);170
foreach ([[$g['a'],$a+$delta],[$g['b'],$b-$delta]] as [$id,$rating]) {171
query('INSERT INTO ratings(user_id,rating,played) VALUES(?,?,1) ON CONFLICT(user_id) DO UPDATE SET rating=excluded.rating,played=ratings.played+1',[$id,$rating]);172
}173
}174
// Called inside BEGIN IMMEDIATE: selecting pairs and consuming entries is atomic.175
function matchPlayers(bool $force=false): void {176
$now=time();177
if (!$force && (int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()>$now-60) return;178
query('UPDATE matchmaking_clock SET checked=? WHERE id=1',[$now]);179
$pool=query('SELECT m.*,COALESCE(r.rating,1200) AS rating FROM matchmaking m LEFT JOIN ratings r ON r.user_id=m.user_id WHERE m.joined>? ORDER BY m.joined,m.user_id',[$now-86400])->fetchAll();180
$used=[];181
foreach ($pool as $a) {182
if (isset($used[$a['user_id']])) continue;183
$best=null;$distance=PHP_INT_MAX;184
foreach ($pool as $b) {185
if ($a['user_id']===$b['user_id'] || isset($used[$b['user_id']])) continue;186
$gap=abs($a['rating']-$b['rating']);187
$limit=min(500,100+50*intdiv(max(0,$now-$a['joined']),60),100+50*intdiv(max(0,$now-$b['joined']),60));188
if ($gap<=$limit && $gap<$distance) {$best=$b;$distance=$gap;}189
}190
if ($best===null) continue;191
startGame($a['user_id'],$best['user_id']);192
query('DELETE FROM matchmaking WHERE user_id IN (?,?)',[$a['user_id'],$best['user_id']]);193
$used[$a['user_id']]=$used[$best['user_id']]=true;194
}149
}195
}150
function startGame(string $a,string $b): int {196
function startGame(string $a,string $b): int {151
query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,random_int(0,1)?$a:$b,json_encode(Chess::initial()),time()]);197
query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,random_int(0,1)?$a:$b,json_encode(Chess::initial()),time()]);@@ -156,7 +202,7 @@ function gameView(array $g,string $u): array {156
$opponent=profile($other);202
$opponent=profile($other);157
$s=$g['state']?json_decode($g['state'],true):null;203
$s=$g['state']?json_decode($g['state'],true):null;158
$color=$g['white']===$u?'w':'b';204
$color=$g['white']===$u?'w':'b';159
return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,205
return ['id'=>(int)$g['id'],'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,160
'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),206
'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),161
'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),207
'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),162
'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],208
'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],@@ -35,9 +35,9 @@ try{
35
35
const friendLink=await a.locator('#share-url').inputValue();
36
36
await a.locator('#modal-close').click();
37
37
await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();
38
await a.locator('[data-friend="local:test_user_2"]').waitFor();
39
await b.locator('[data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();
40
await a.locator('[data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();
38
await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
39
await b.locator('#friend-list [data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();
40
await a.locator('#friend-list [data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();
41
41
await b.getByRole('button',{name:'Accept',exact:true}).click();
42
42
await a.locator('.board').waitFor();await b.locator('.board').waitFor();
43
43
await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();
@@ -134,9 +134,9 @@ try{
134
134
assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
135
135
assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
136
136
await page.mouse.move(0,0);
137
await page.waitForTimeout(250);
138
assert(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))<.3,'Result starts transparent');
139
await page.locator('.end-content').hover();await page.waitForTimeout(250);
137
await page.waitForTimeout(850);
138
assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent');
139
await page.locator('.end-content').hover();await page.waitForTimeout(850);
140
140
assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
141
141
}
142
142
await white.getByRole('button',{name:'Rematch',exact:true}).click();
@@ -157,11 +157,11 @@ try{
157
157
const staleId=(await state(a)).games[0].id;
158
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)]);
159
159
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
160
await a.getByText('De laatste zet was 8 dagen geleden. Wil je het spel stoppen?').waitFor();
161
await a.getByRole('button',{name:'Annuleren',exact:true}).click();
160
await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
161
await a.getByRole('button',{name:'Cancel',exact:true}).click();
162
162
assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
163
163
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
164
await a.getByRole('button',{name:'Spel stoppen',exact:true}).click();
164
await a.getByRole('button',{name:'Stop game',exact:true}).click();
165
165
await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
166
166
await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
167
167
await a.setViewportSize({width:390,height:844});
@@ -199,6 +199,62 @@ try{
199
199
await mobileWaiting.waitFor({state:'attached'});
200
200
assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');
201
201
await mobileContext.close();
202
// New game offers matchmaking below the link, with persistent cancellation.
203
await a.setViewportSize({width:1440,height:1080});
204
await a.locator('#match-link').click();
205
await a.getByRole('button',{name:'Challenge a random player',exact:true}).waitFor();
206
const linkBox=await a.locator('#share-url').boundingBox();
207
const matchBox=await a.getByRole('button',{name:'Challenge a random player',exact:true}).boundingBox();
208
assert(matchBox.y>linkBox.y,'Random challenge is below invite link');
209
await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
210
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
211
await a.reload();
212
await a.getByRole('button',{name:'Cancel search',exact:true}).waitFor();
213
await a.locator('#match-link').click();
214
await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).waitFor();
215
await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).click();
216
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
217
await a.locator('#match-link').click();
218
await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
219
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
220
const priorIds=new Set((await state(a)).games.map(g=>g.id));
221
await b.locator('#match-link').click();
222
await b.getByRole('button',{name:'Challenge a random player',exact:true}).click();
223
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
224
const randomGame=(await state(a)).games.find(g=>!priorIds.has(g.id));
225
assert(randomGame,'Matchmaking creates a new game');
226
for(const p of[a,b]) await p.locator(`[data-game="${randomGame.id}"] .board`).waitFor();
227
assert.match(await a.locator('#account-summary').innerText(),/\d+ Elo/,'Own rating is visible');
228
assert.equal(await a.locator(`[data-game="${randomGame.id}"] .rating`).innerText(),String(randomGame.opponentRating),'Opponent rating is visible');
229
// The same rivalry modal is available from a game and the friends list.
230
await post(a,'remove_friend',{friend:'local:test_user_2'});
231
await a.reload();
232
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
233
const rivalryStats=await a.locator('.stats').innerText();
234
await a.getByRole('button',{name:'Send friend request',exact:true}).click();
235
await a.locator('#modal').waitFor({state:'hidden'});
236
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
237
assert(await a.getByRole('button',{name:'Friend request sent',exact:true}).isDisabled(),'Sender sees pending status');
238
await a.locator('#modal-close').click();
239
await b.locator('#friend-requests').getByRole('button',{name:'Reject',exact:true}).click();
240
await b.locator('.friend-request').waitFor({state:'detached'});
241
await a.reload();
242
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
243
await a.getByRole('button',{name:'Send friend request',exact:true}).click();
244
await b.reload();
245
await b.setViewportSize({width:390,height:844});
246
await b.locator('#friends-toggle').click();
247
await b.locator('#friend-requests').getByRole('button',{name:'Accept',exact:true}).click();
248
await b.locator('#friend-list [data-friend="local:test_user_1"]').waitFor();
249
await b.locator('.friend-request').waitFor({state:'detached'});
250
await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
251
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
252
assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Game modal retains rivalry history');
253
await a.getByRole('button',{name:'Challenge to a game'}).waitFor();
254
await a.locator('#modal-close').click();
255
await a.locator('#friend-list [data-friend="local:test_user_2"]').click();
256
assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
257
await a.locator('#modal-close').click();
202
258
assert.deepEqual(errors,[],'No browser errors');
203
259
console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');
204
260
}finally{
@@ -35,9 +35,9 @@ try{35
const friendLink=await a.locator('#share-url').inputValue();35
const friendLink=await a.locator('#share-url').inputValue();36
await a.locator('#modal-close').click();36
await a.locator('#modal-close').click();37
await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();37
await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();38
await a.locator('[data-friend="local:test_user_2"]').waitFor();38
await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();39
await b.locator('[data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();39
await b.locator('#friend-list [data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();40
await a.locator('[data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();40
await a.locator('#friend-list [data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();41
await b.getByRole('button',{name:'Accept',exact:true}).click();41
await b.getByRole('button',{name:'Accept',exact:true}).click();42
await a.locator('.board').waitFor();await b.locator('.board').waitFor();42
await a.locator('.board').waitFor();await b.locator('.board').waitFor();43
await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();43
await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();@@ -134,9 +134,9 @@ try{134
assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');134
assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');135
assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');135
assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');136
await page.mouse.move(0,0);136
await page.mouse.move(0,0);137
await page.waitForTimeout(250);137
await page.waitForTimeout(850);138
assert(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))<.3,'Result starts transparent');138
assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent');139
await page.locator('.end-content').hover();await page.waitForTimeout(250);139
await page.locator('.end-content').hover();await page.waitForTimeout(850);140
assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');140
assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');141
}141
}142
await white.getByRole('button',{name:'Rematch',exact:true}).click();142
await white.getByRole('button',{name:'Rematch',exact:true}).click();@@ -157,11 +157,11 @@ try{157
const staleId=(await state(a)).games[0].id;157
const staleId=(await state(a)).games[0].id;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)]);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)]);159
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();159
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();160
await a.getByText('De laatste zet was 8 dagen geleden. Wil je het spel stoppen?').waitFor();160
await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();161
await a.getByRole('button',{name:'Annuleren',exact:true}).click();161
await a.getByRole('button',{name:'Cancel',exact:true}).click();162
assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');162
assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');163
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();163
await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();164
await a.getByRole('button',{name:'Spel stoppen',exact:true}).click();164
await a.getByRole('button',{name:'Stop game',exact:true}).click();165
await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});165
await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});166
await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});166
await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});167
await a.setViewportSize({width:390,height:844});167
await a.setViewportSize({width:390,height:844});@@ -199,6 +199,62 @@ try{199
await mobileWaiting.waitFor({state:'attached'});199
await mobileWaiting.waitFor({state:'attached'});200
assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');200
assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');201
await mobileContext.close();201
await mobileContext.close();202
// New game offers matchmaking below the link, with persistent cancellation.203
await a.setViewportSize({width:1440,height:1080});204
await a.locator('#match-link').click();205
await a.getByRole('button',{name:'Challenge a random player',exact:true}).waitFor();206
const linkBox=await a.locator('#share-url').boundingBox();207
const matchBox=await a.getByRole('button',{name:'Challenge a random player',exact:true}).boundingBox();208
assert(matchBox.y>linkBox.y,'Random challenge is below invite link');209
await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();210
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();211
await a.reload();212
await a.getByRole('button',{name:'Cancel search',exact:true}).waitFor();213
await a.locator('#match-link').click();214
await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).waitFor();215
await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).click();216
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});217
await a.locator('#match-link').click();218
await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();219
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();220
const priorIds=new Set((await state(a)).games.map(g=>g.id));221
await b.locator('#match-link').click();222
await b.getByRole('button',{name:'Challenge a random player',exact:true}).click();223
await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});224
const randomGame=(await state(a)).games.find(g=>!priorIds.has(g.id));225
assert(randomGame,'Matchmaking creates a new game');226
for(const p of[a,b]) await p.locator(`[data-game="${randomGame.id}"] .board`).waitFor();227
assert.match(await a.locator('#account-summary').innerText(),/\d+ Elo/,'Own rating is visible');228
assert.equal(await a.locator(`[data-game="${randomGame.id}"] .rating`).innerText(),String(randomGame.opponentRating),'Opponent rating is visible');229
// The same rivalry modal is available from a game and the friends list.230
await post(a,'remove_friend',{friend:'local:test_user_2'});231
await a.reload();232
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();233
const rivalryStats=await a.locator('.stats').innerText();234
await a.getByRole('button',{name:'Send friend request',exact:true}).click();235
await a.locator('#modal').waitFor({state:'hidden'});236
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();237
assert(await a.getByRole('button',{name:'Friend request sent',exact:true}).isDisabled(),'Sender sees pending status');238
await a.locator('#modal-close').click();239
await b.locator('#friend-requests').getByRole('button',{name:'Reject',exact:true}).click();240
await b.locator('.friend-request').waitFor({state:'detached'});241
await a.reload();242
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();243
await a.getByRole('button',{name:'Send friend request',exact:true}).click();244
await b.reload();245
await b.setViewportSize({width:390,height:844});246
await b.locator('#friends-toggle').click();247
await b.locator('#friend-requests').getByRole('button',{name:'Accept',exact:true}).click();248
await b.locator('#friend-list [data-friend="local:test_user_1"]').waitFor();249
await b.locator('.friend-request').waitFor({state:'detached'});250
await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();251
await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();252
assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Game modal retains rivalry history');253
await a.getByRole('button',{name:'Challenge to a game'}).waitFor();254
await a.locator('#modal-close').click();255
await a.locator('#friend-list [data-friend="local:test_user_2"]').click();256
assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');257
await a.locator('#modal-close').click();202
assert.deepEqual(errors,[],'No browser errors');258
assert.deepEqual(errors,[],'No browser errors');203
console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');259
console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');204
}finally{260
}finally{@@ -85,6 +85,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
85
85
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
86
86
b.state(); b.post('switch_user', user='test_user_2'); b.state()
87
87
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
88
check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')
88
89
initial_avatar=b.state()['user']['avatar']
89
90
check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')
90
91
a.post('set_avatar',avatar='blue-knight')
@@ -130,6 +131,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
130
131
check(black.game(id)['yourTurn'], 'Turn passes')
131
132
black.game_action('resign', id)
132
133
check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
134
check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
135
black.game_action('resign', id, expected=409)
136
check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')
133
137
check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')
134
138
old_color = a.game(id)['color']
135
139
a.game_action('rematch', id)
@@ -142,6 +146,8 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
142
146
other = b if turn is a else a
143
147
other.game_action('accept_draw', id)
144
148
check(a.state()['friends'][0]['ties']==1, 'Draw stats')
149
check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')
150
check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')
145
151
a.game_action('rematch', id); b.game_action('exit', id)
146
152
check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')
147
153
check(not b.state()['games'], 'Exit hides own tile only')
@@ -207,6 +213,88 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
207
213
a.game_action('stop_inactive',inactive_id)
208
214
check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
209
215
check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')
216
# Opponent statistics work without friendship; requests need recipient consent.
217
opponent=a.state()['games'][0]
218
check(opponent['opponentId']=='local:test_user_2' and sum(opponent['rivalry'].values())==3,'Non-friend opponent has historical rivalry statistics')
219
a.post('send_friend_request',friend='local:test_user_1',expected=409)
220
a.post('send_friend_request',friend='missing',expected=409)
221
a.post('send_friend_request',friend=['invalid'],expected=409)
222
old=a.csrf; a.csrf='wrong';a.post('send_friend_request',friend='local:test_user_2',expected=403);a.csrf=old
223
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
224
list(pool.map(lambda _:a.post('send_friend_request',friend='local:test_user_2'),range(2)))
225
check(len(a.state()['friendRequests'])==len(b.state()['friendRequests'])==1,'Concurrent sends produce one request')
226
check(not a.state()['friendRequests'][0]['incoming'] and b.state()['friendRequests'][0]['incoming'],'Request direction is correct')
227
check(not a.state()['friends'] and not b.state()['friends'],'Sending request does not create friendship')
228
check(len(a.get('/api.php?action=export')['friend_requests'])==1,'Export includes pending requests')
229
a.post('accept_friend_request',friend='local:test_user_2',expected=409)
230
a.post('reject_friend_request',friend='local:test_user_2',expected=409)
231
b.post('send_friend_request',friend='local:test_user_1',expected=409)
232
b.post('reject_friend_request',friend='local:test_user_1')
233
check(not a.state()['friendRequests'] and not b.state()['friends'],'Rejection clears request without friendship')
234
a.post('send_friend_request',friend='local:test_user_2')
235
b.post('accept_friend_request',friend='local:test_user_1')
236
check(len(a.state()['friends'])==len(b.state()['friends'])==1,'Acceptance creates bilateral friendship')
237
check(not a.state()['friendRequests'] and not b.state()['friendRequests'],'Acceptance consumes request for both users')
238
check({k:a.state()['friends'][0][k] for k in ['wins','losses','ties']}==opponent['rivalry'],'Friend and opponent statistics match')
239
b.post('accept_friend_request',friend='local:test_user_1',expected=409)
240
a.post('send_friend_request',friend='local:test_user_2',expected=409)
241
a.post('remove_friend',friend='local:test_user_2')
242
a.post('send_friend_request',friend='local:test_user_2')
243
token=b.post('create_link',kind='friend')['url'].split('=')[1]
244
a.post('accept_link',token=token)
245
check(not a.state()['friendRequests'],'Friend link acceptance clears pending request')
246
a.post('remove_friend',friend='local:test_user_2')
247
# Queue requests survive sessions and never match the same user to themselves.
248
before_count=con.execute('SELECT count(*) FROM games').fetchone()[0]
249
a.post('join_matchmaking'); a.post('join_matchmaking')
250
check(con.execute('SELECT count(*) FROM matchmaking').fetchone()[0]==1,'One queue entry per user')
251
check(a.state()['matchmaking']['status']=='searching','Search persists on polling')
252
check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count,'No self match')
253
a.post('cancel_matchmaking'); a.post('cancel_matchmaking')
254
check(a.state()['matchmaking'] is None,'Cancel is persistent and idempotent')
255
# Simultaneous joins produce one bilateral game, even without friendship.
256
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
257
list(pool.map(lambda c:c.post('join_matchmaking'),[a,b]))
258
check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count+1,'Concurrent joins create exactly one game')
259
check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Both entries consumed')
260
matched=a.state()['games'][0]
261
check(matched['id']==b.state()['games'][0]['id'] and matched['status']=='active','Match starts for both players')
262
check(matched['color']!=b.game(matched['id'])['color'],'Matched players have opposite colors')
263
# Set ratings and elapsed time directly rather than sleeping for minutes.
264
con.execute('UPDATE ratings SET rating=1200 WHERE user_id=?',('local:test_user_1',))
265
con.execute('UPDATE ratings SET rating=1400 WHERE user_id=?',('local:test_user_2',)); con.commit()
266
a.post('join_matchmaking'); b.post('join_matchmaking')
267
check(a.state()['matchmaking'] and b.state()['matchmaking'],'200 point gap initially waits')
268
con.execute('UPDATE matchmaking SET joined=? WHERE user_id=?',(int(time.time())-120,'local:test_user_1'))
269
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
270
check(a.state()['matchmaking'] is not None,'Both players must allow rating gap')
271
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-120,))
272
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
273
check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Activity matches after two minutes of widening')
274
a.post('join_matchmaking')
275
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-86400,));con.commit()
276
b.post('join_matchmaking')
277
check(a.state()['matchmaking']['status']=='expired','Expired registration is excluded')
278
a.post('join_matchmaking')
279
check(a.state()['matchmaking']['status']=='searching','Expired search can restart')
280
con.execute('UPDATE ratings SET rating=1800 WHERE user_id=?',('local:test_user_2',))
281
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-3600,))
282
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
283
check(a.state()['matchmaking'] is not None,'Rating tolerance capped at 500')
284
a.post('cancel_matchmaking');b.post('cancel_matchmaking')
285
# An unrelated user's page activity processes the entire pool, oldest first,
286
# choosing the closest eligible opponent and leaving unmatched entries intact.
287
now=int(time.time())
288
for uid,rating,joined in [('queue:oldest',1200,now-300),('queue:far',1290,now-200),('queue:near',1220,now-100)]:
289
con.execute('INSERT INTO users VALUES(?,?)',(uid,uid))
290
con.execute('INSERT INTO ratings VALUES(?,?,0)',(uid,rating))
291
con.execute('INSERT INTO matchmaking VALUES(?,?)',(uid,joined))
292
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
293
a.state()
294
pair=con.execute('SELECT a,b FROM games ORDER BY id DESC LIMIT 1').fetchone()
295
check(set(pair)=={'queue:oldest','queue:near'},'Whole pool prefers closest opponent for oldest entry')
296
check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
297
check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
210
298
con.close()
211
299
print(f'API: {checks} assertions passed.')
212
300
finally:
@@ -85,6 +85,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:85
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')85
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')86
b.state(); b.post('switch_user', user='test_user_2'); b.state()86
b.state(); b.post('switch_user', user='test_user_2'); b.state()87
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')87
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')88
check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')88
initial_avatar=b.state()['user']['avatar']89
initial_avatar=b.state()['user']['avatar']89
check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')90
check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')90
a.post('set_avatar',avatar='blue-knight')91
a.post('set_avatar',avatar='blue-knight')@@ -130,6 +131,9 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:130
check(black.game(id)['yourTurn'], 'Turn passes')131
check(black.game(id)['yourTurn'], 'Turn passes')131
black.game_action('resign', id)132
black.game_action('resign', id)132
check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')133
check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')134
check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')135
black.game_action('resign', id, expected=409)136
check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')133
check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')137
check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')134
old_color = a.game(id)['color']138
old_color = a.game(id)['color']135
a.game_action('rematch', id)139
a.game_action('rematch', id)@@ -142,6 +146,8 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:142
other = b if turn is a else a146
other = b if turn is a else a143
other.game_action('accept_draw', id)147
other.game_action('accept_draw', id)144
check(a.state()['friends'][0]['ties']==1, 'Draw stats')148
check(a.state()['friends'][0]['ties']==1, 'Draw stats')149
check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')150
check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')145
a.game_action('rematch', id); b.game_action('exit', id)151
a.game_action('rematch', id); b.game_action('exit', id)146
check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')152
check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')147
check(not b.state()['games'], 'Exit hides own tile only')153
check(not b.state()['games'], 'Exit hides own tile only')@@ -207,6 +213,88 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:207
a.game_action('stop_inactive',inactive_id)213
a.game_action('stop_inactive',inactive_id)208
check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')214
check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')209
check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')215
check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')216
# Opponent statistics work without friendship; requests need recipient consent.217
opponent=a.state()['games'][0]218
check(opponent['opponentId']=='local:test_user_2' and sum(opponent['rivalry'].values())==3,'Non-friend opponent has historical rivalry statistics')219
a.post('send_friend_request',friend='local:test_user_1',expected=409)220
a.post('send_friend_request',friend='missing',expected=409)221
a.post('send_friend_request',friend=['invalid'],expected=409)222
old=a.csrf; a.csrf='wrong';a.post('send_friend_request',friend='local:test_user_2',expected=403);a.csrf=old223
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:224
list(pool.map(lambda _:a.post('send_friend_request',friend='local:test_user_2'),range(2)))225
check(len(a.state()['friendRequests'])==len(b.state()['friendRequests'])==1,'Concurrent sends produce one request')226
check(not a.state()['friendRequests'][0]['incoming'] and b.state()['friendRequests'][0]['incoming'],'Request direction is correct')227
check(not a.state()['friends'] and not b.state()['friends'],'Sending request does not create friendship')228
check(len(a.get('/api.php?action=export')['friend_requests'])==1,'Export includes pending requests')229
a.post('accept_friend_request',friend='local:test_user_2',expected=409)230
a.post('reject_friend_request',friend='local:test_user_2',expected=409)231
b.post('send_friend_request',friend='local:test_user_1',expected=409)232
b.post('reject_friend_request',friend='local:test_user_1')233
check(not a.state()['friendRequests'] and not b.state()['friends'],'Rejection clears request without friendship')234
a.post('send_friend_request',friend='local:test_user_2')235
b.post('accept_friend_request',friend='local:test_user_1')236
check(len(a.state()['friends'])==len(b.state()['friends'])==1,'Acceptance creates bilateral friendship')237
check(not a.state()['friendRequests'] and not b.state()['friendRequests'],'Acceptance consumes request for both users')238
check({k:a.state()['friends'][0][k] for k in ['wins','losses','ties']}==opponent['rivalry'],'Friend and opponent statistics match')239
b.post('accept_friend_request',friend='local:test_user_1',expected=409)240
a.post('send_friend_request',friend='local:test_user_2',expected=409)241
a.post('remove_friend',friend='local:test_user_2')242
a.post('send_friend_request',friend='local:test_user_2')243
token=b.post('create_link',kind='friend')['url'].split('=')[1]244
a.post('accept_link',token=token)245
check(not a.state()['friendRequests'],'Friend link acceptance clears pending request')246
a.post('remove_friend',friend='local:test_user_2')247
# Queue requests survive sessions and never match the same user to themselves.248
before_count=con.execute('SELECT count(*) FROM games').fetchone()[0]249
a.post('join_matchmaking'); a.post('join_matchmaking')250
check(con.execute('SELECT count(*) FROM matchmaking').fetchone()[0]==1,'One queue entry per user')251
check(a.state()['matchmaking']['status']=='searching','Search persists on polling')252
check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count,'No self match')253
a.post('cancel_matchmaking'); a.post('cancel_matchmaking')254
check(a.state()['matchmaking'] is None,'Cancel is persistent and idempotent')255
# Simultaneous joins produce one bilateral game, even without friendship.256
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:257
list(pool.map(lambda c:c.post('join_matchmaking'),[a,b]))258
check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count+1,'Concurrent joins create exactly one game')259
check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Both entries consumed')260
matched=a.state()['games'][0]261
check(matched['id']==b.state()['games'][0]['id'] and matched['status']=='active','Match starts for both players')262
check(matched['color']!=b.game(matched['id'])['color'],'Matched players have opposite colors')263
# Set ratings and elapsed time directly rather than sleeping for minutes.264
con.execute('UPDATE ratings SET rating=1200 WHERE user_id=?',('local:test_user_1',))265
con.execute('UPDATE ratings SET rating=1400 WHERE user_id=?',('local:test_user_2',)); con.commit()266
a.post('join_matchmaking'); b.post('join_matchmaking')267
check(a.state()['matchmaking'] and b.state()['matchmaking'],'200 point gap initially waits')268
con.execute('UPDATE matchmaking SET joined=? WHERE user_id=?',(int(time.time())-120,'local:test_user_1'))269
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()270
check(a.state()['matchmaking'] is not None,'Both players must allow rating gap')271
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-120,))272
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()273
check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Activity matches after two minutes of widening')274
a.post('join_matchmaking')275
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-86400,));con.commit()276
b.post('join_matchmaking')277
check(a.state()['matchmaking']['status']=='expired','Expired registration is excluded')278
a.post('join_matchmaking')279
check(a.state()['matchmaking']['status']=='searching','Expired search can restart')280
con.execute('UPDATE ratings SET rating=1800 WHERE user_id=?',('local:test_user_2',))281
con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-3600,))282
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()283
check(a.state()['matchmaking'] is not None,'Rating tolerance capped at 500')284
a.post('cancel_matchmaking');b.post('cancel_matchmaking')285
# An unrelated user's page activity processes the entire pool, oldest first,286
# choosing the closest eligible opponent and leaving unmatched entries intact.287
now=int(time.time())288
for uid,rating,joined in [('queue:oldest',1200,now-300),('queue:far',1290,now-200),('queue:near',1220,now-100)]:289
con.execute('INSERT INTO users VALUES(?,?)',(uid,uid))290
con.execute('INSERT INTO ratings VALUES(?,?,0)',(uid,rating))291
con.execute('INSERT INTO matchmaking VALUES(?,?)',(uid,joined))292
con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()293
a.state()294
pair=con.execute('SELECT a,b FROM games ORDER BY id DESC LIMIT 1').fetchone()295
check(set(pair)=={'queue:oldest','queue:near'},'Whole pool prefers closest opponent for oldest entry')296
check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')297
check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')210
con.close()298
con.close()211
print(f'API: {checks} assertions passed.')299
print(f'API: {checks} assertions passed.')212
finally:300
finally: