diff --git a/documentation/games.md b/documentation/games.md index dd7d0b5b..beeb32a9 100644 --- a/documentation/games.md +++ b/documentation/games.md @@ -23,7 +23,7 @@ The board turns so that your pieces are at the bottom. Tap one of your pieces, t - **Offer draw** / **Accept draw**. Making a move instead declines an offer. - **Resign** asks first. - **Claim win on time** appears when your opponent has gone more than 10 minutes past the time per move. Your phone times it from when it sent your last move; the 10 minutes allow for slow delivery. Other phones accept the claim once the time per move has passed since they heard that move. -- **Ask for update** gets a stuck game moving. While you wait after your own move, it sends that move again, and your opponent's phone answers with its move if you missed it. Otherwise it asks the players to send the latest move again. A player answers within a few seconds, at most once a minute per game. +- **Ask for update** gets a stuck game moving. While you wait after your own move, it sends that move again, and your opponent's phone answers with its move if you missed it. Otherwise it asks the players to send the latest move again. A player answers within a few seconds, at most once a minute per game. A finished game answers too, with the last move and the resignation, draw accept or win claim that ended it, so a game whose last packet got lost still ends on every phone. If the radio doesn't confirm a move, the move stays on your board, since it may have gone out, and the game says so. Use **Ask for update** to send it again. @@ -58,6 +58,6 @@ Other packets: invite 55 bytes (87 for a challenge, with the name), accept 53, d The inviter's first value after the commitment is kept for the game info, which says whose accept won. Anyone who heard the invite can check it came from the inviter, and works out the colours from the invite rather than taking the packet's word. If you accepted and the game info names someone else, you watch the game instead, and switch to playing if a later game info names you. -Players also check that the move gives the position in the packet. Spectators who missed moves take the position as it is. A draw accept only counts after a draw offer, and a timeout claim only when the game has a time per move and it has run out. +Players also check that the move gives the position in the packet. Spectators who missed moves take the position as it is. A draw accept only counts after a draw offer, and a timeout claim only when the game has a time per move and it has run out. Both are for the position they were sent in: one that crosses a move on air counts on neither phone. Your secret values stay on your phone, stored per radio with the rest of the game. diff --git a/lib/games/chess/chess_game.dart b/lib/games/chess/chess_game.dart index d3fc262a..dc8b0c15 100644 --- a/lib/games/chess/chess_game.dart +++ b/lib/games/chess/chess_game.dart @@ -158,6 +158,10 @@ class ChessGame { /// Latest move packet heard or sent, kept so any holder can re-send it. Uint8List? lastMovePacket; + /// The resign, draw accept or timeout claim that ended the game, sent or + /// heard, kept so players can send it again to anyone who missed it. + Uint8List? finalActionPacket; + ChessSide? drawOfferedBy; ChessSide? winner; ChessEndReason? endReason; @@ -195,6 +199,7 @@ class ChessGame { this.hasPosition = true, this.lastMoveUci, this.lastMovePacket, + this.finalActionPacket, this.drawOfferedBy, this.winner, this.endReason, @@ -366,6 +371,8 @@ class ChessGame { 'hasPosition': hasPosition, if (lastMoveUci != null) 'lastUci': lastMoveUci, if (lastMovePacket != null) 'lastPacket': base64Encode(lastMovePacket!), + if (finalActionPacket != null) + 'finalPacket': base64Encode(finalActionPacket!), if (drawOfferedBy != null) 'draw': drawOfferedBy!.name, if (winner != null) 'winner': winner!.name, if (endReason != null) 'end': endReason!.name, @@ -383,6 +390,7 @@ class ChessGame { final created = json['created']; if (channel is! String || id is! int || created is! int) return null; final packet = json['lastPacket']; + final finalPacket = json['finalPacket']; return ChessGame( channelId: channel, gameId: id, @@ -414,6 +422,9 @@ class ChessGame { hasPosition: json['hasPosition'] != false, lastMoveUci: json['lastUci'] as String?, lastMovePacket: packet is String ? base64Decode(packet) : null, + finalActionPacket: finalPacket is String + ? base64Decode(finalPacket) + : null, drawOfferedBy: _enumByNameOrNull(ChessSide.values, json['draw']), winner: _enumByNameOrNull(ChessSide.values, json['winner']), endReason: _enumByNameOrNull(ChessEndReason.values, json['end']), diff --git a/lib/games/chess/chess_service.dart b/lib/games/chess/chess_service.dart index e09ae044..4c07cf82 100644 --- a/lib/games/chess/chess_service.dart +++ b/lib/games/chess/chess_service.dart @@ -281,22 +281,19 @@ class ChessService extends ChangeNotifier { g.drawOfferedBy = side; }); - Future acceptDraw(ChessGame game) { - final side = game.mySide; - if (side == null || game.drawOfferedBy != side.other) { - return Future.value(false); - } - return _sendAction(game, ChessPacketKind.drawAccept, (g, _) { - g.finish(ChessEndReason.drawAgreed); - }); - } + Future acceptDraw(ChessGame game) => _sendAction( + game, + ChessPacketKind.drawAccept, + (g, _) => g.finish(ChessEndReason.drawAgreed), + valid: (g, side) => side != null && g.drawOfferedBy == side.other, + ); - Future claimTimeout(ChessGame game) { - if (!canClaimTimeout(game)) return Future.value(false); - return _sendAction(game, ChessPacketKind.timeoutClaim, (g, side) { - g.finish(ChessEndReason.timeout, winner: side); - }); - } + Future claimTimeout(ChessGame game) => _sendAction( + game, + ChessPacketKind.timeoutClaim, + (g, side) => g.finish(ChessEndReason.timeout, winner: side), + valid: (g, _) => canClaimTimeout(g), + ); /// Gets a stuck game moving. While we wait for the opponent after our own /// move, sends that move again (the opponent answers with theirs if we @@ -333,10 +330,12 @@ class ChessService extends ChangeNotifier { ChessPacketKind kind, void Function(ChessGame game, ChessSide? side) apply, { ChessGameStatus allowedStatus = ChessGameStatus.active, + bool Function(ChessGame game, ChessSide? side)? valid, }) async { if (game.status != allowedStatus || isSending(game)) return false; if (!link.canSend) return false; final side = game.mySide; + if (valid != null && !valid(game, side)) return false; final record = kind == ChessPacketKind.cancel ? (game.iAmInviter ? game.inviter : null) : (side == null ? null : game.playerOf(side)); @@ -345,20 +344,30 @@ class ChessService extends ChangeNotifier { if (chain == null) return false; // Used up even if the send fails: the packet may have gone out. record.use(chain.index); - final ok = await _send( - game, - ChessActionPacket( - kind: kind, - gameId: game.gameId, - ply: game.ply, - chainValue: chain.value, - ), - ); - if (!ok || game.status != allowedStatus) { + final ply = game.ply; + final packet = ChessActionPacket( + kind: kind, + gameId: game.gameId, + ply: ply, + chainValue: chain.value, + ).encode(); + final ok = await _sendRaw(game, packet); + // A move heard while sending makes the action stale: receivers check it + // against the new position and ignore it, so it doesn't apply here + // either. Only a resignation counts at any ply. + final stale = + game.status != allowedStatus || + (kind != ChessPacketKind.resign && game.ply != ply) || + (valid != null && !valid(game, side)); + if (!ok || stale) { _changed(); return false; } apply(game, side); + if (kind != ChessPacketKind.cancel && + game.status == ChessGameStatus.finished) { + game.finalActionPacket = packet; + } _touch(game); return true; } @@ -436,9 +445,7 @@ class ChessService extends ChangeNotifier { if (packet == null) return; final channelId = incoming.channelId; final existing = game(channelId, packet.gameId); - if (existing != null && - (packet is ChessInfoPacket || - (packet is ChessMovePacket && packet.ply >= existing.ply))) { + if (existing != null && _answersPending(existing, packet, incoming)) { // Someone answered; our own pending answer is no longer needed. _pendingAnswers.remove(existing.key)?.cancel(); } @@ -447,13 +454,27 @@ class ChessService extends ChangeNotifier { ChessAcceptPacket p => _onAccept(existing, p), ChessDeclinePacket p => _onDecline(existing, p), ChessMovePacket p => _onMove(channelId, existing, p, incoming.payload), - ChessActionPacket p => _onAction(existing, p), + ChessActionPacket p => _onAction(existing, p, incoming.payload), ChessInfoPacket p => _onInfo(channelId, existing, p), ChessRequestPacket p => _onRequest(existing, p), }; if (changed) _changed(); } + /// Whether [packet] makes our pending answer for [game] unnecessary. A + /// finished game's answer ends with the action that finished it, so only + /// that action replaces it. + static bool _answersPending( + ChessGame game, + ChessPacket packet, + ChessIncoming incoming, + ) { + final ending = game.finalActionPacket; + if (ending != null) return bytesEqual(ending, incoming.payload); + return packet is ChessInfoPacket || + (packet is ChessMovePacket && packet.ply >= game.ply); + } + bool _onInvite(String channelId, ChessGame? existing, ChessInvitePacket p) { if (existing != null) return false; final game = ChessGame( @@ -724,6 +745,16 @@ class ChessService extends ChangeNotifier { } switch (game.status) { case ChessGameStatus.finished: + if (game.isPlayer && game.mySide != mover && ply <= game.ply) { + // The opponent sent a move again: they missed how the game ended. + _scheduleAnswer( + game, + info: false, + latestMove: ply < game.ply, + finalAction: game.finalActionPacket != null, + ); + } + return false; case ChessGameStatus.starting: // Wait for the inviter's confirmation. return false; case ChessGameStatus.invite: @@ -824,7 +855,7 @@ class ChessService extends ChangeNotifier { fullMoveNumber: p.ply ~/ 2 + 1, ); - bool _onAction(ChessGame? game, ChessActionPacket p) { + bool _onAction(ChessGame? game, ChessActionPacket p, Uint8List raw) { if (game == null) return false; if (p.kind == ChessPacketKind.cancel) { if (game.iAmInviter) return false; @@ -875,6 +906,7 @@ class ChessService extends ChangeNotifier { default: break; } + if (game.status == ChessGameStatus.finished) game.finalActionPacket = raw; return true; } @@ -893,6 +925,7 @@ class ChessService extends ChangeNotifier { game, info: p.wantsInfo, latestMove: p.wantsLatestMove && p.ply < game.ply, + finalAction: p.wantsLatestMove && game.finalActionPacket != null, ); return false; } @@ -903,9 +936,10 @@ class ChessService extends ChangeNotifier { ChessGame game, { required bool info, required bool latestMove, + bool finalAction = false, bool immediate = false, }) { - if (!info && !latestMove) return; + if (!info && !latestMove && !finalAction) return; if (_pendingAnswers.containsKey(game.key)) return; final last = game.lastAnsweredRequestAtMs; if (!immediate && @@ -927,13 +961,16 @@ class ChessService extends ChangeNotifier { // Confirmations are not answers to a request; they don't count. if (!immediate) game.lastAnsweredRequestAtMs = _now; if (info) await _sendInfo(game); - if (!latestMove) return; - final move = game.lastMovePacket; - if (_latestMoveIsMine(game)) { - await _resendLatestMove(game); - } else if (move != null) { - await _sendRaw(game, move); + if (latestMove) { + final move = game.lastMovePacket; + if (game.status == ChessGameStatus.active && _latestMoveIsMine(game)) { + await _resendLatestMove(game); + } else if (move != null) { + await _sendRaw(game, move); + } } + final ending = game.finalActionPacket; + if (finalAction && ending != null) await _sendRaw(game, ending); }); } diff --git a/test/games/chess_service_test.dart b/test/games/chess_service_test.dart index 81c009ae..7a5ff0d2 100644 --- a/test/games/chess_service_test.dart +++ b/test/games/chess_service_test.dart @@ -806,6 +806,139 @@ void main() { expect(dave.game!.fen, alice.game!.fen); }); + test( + 'a lost checkmate reaches the opponent who sends their move again', + () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + const moves = ['e2e4', 'e7e5', 'f1c4', 'b8c6', 'd1h5', 'g8f6']; + for (var i = 0; i < moves.length; i++) { + final mover = i.isEven ? white : black; + await mover.service.makeMove(mover.game!, moves[i]); + } + mesh.filter = (from, to, _) => + !(from == white.link && to == black.link); + await white.service.makeMove(white.game!, 'h5f7'); + mesh.filter = null; + expect(white.game!.endReason, ChessEndReason.checkmate); + expect(black.game!.status, ChessGameStatus.active); + + // Black's Ask for update re-sends g8f6; White answers with the mate. + await black.service.requestUpdate(black.game!); + await settle(); + expect(black.game!.status, ChessGameStatus.finished); + expect(black.game!.endReason, ChessEndReason.checkmate); + expect(black.game!.winner, ChessSide.white); + + // Rate-limited like other answers. + final sent = white.link.sent.length; + feed(white, sentOf(black).last); + await settle(); + expect(white.link.sent.length, sent); + }, + ); + + test('a lost resignation is sent again with recovery answers', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + final (white, black) = await startGame(alice, bob); + await white.service.makeMove(white.game!, 'e2e4'); + await black.service.makeMove(black.game!, 'e7e5'); + mesh.filter = (from, to, payload) => + !(from == white.link && + ChessPacket.decode(payload) is ChessActionPacket); + expect(await white.service.resign(white.game!), isTrue); + expect(white.game!.finalActionPacket, isNotNull); + expect(black.game!.status, ChessGameStatus.active); + expect(carol.game!.status, ChessGameStatus.active); + + // Kept across a restart. + await white.service.store.flush(); + final reloaded = ChessStore().load(white.link.storageScope).single; + expect(reloaded.finalActionPacket, white.game!.finalActionPacket); + + // Black re-sends its move; White answers with the resignation. Carol + // still misses it. + mesh.filter = (from, to, payload) => + !(to == carol.link && + ChessPacket.decode(payload) is ChessActionPacket); + await black.service.requestUpdate(black.game!); + await settle(); + expect(black.game!.endReason, ChessEndReason.resignation); + expect(black.game!.winner, black.game!.mySide); + expect(carol.game!.status, ChessGameStatus.active); + + // Carol asks; a player answers with the resignation. + mesh.filter = null; + now = now.add(ChessService.requestAnswerInterval); + await carol.service.requestUpdate(carol.game!); + await settle(); + expect(carol.game!.endReason, ChessEndReason.resignation); + expect(carol.game!.winner, ChessSide.black); + + // Hearing it again changes nothing. + final resign = sentOf(white).first; + final index = carol.game!.white!.lastIndex; + feed(carol, resign); + expect(carol.game!.white!.lastIndex, index); + expect(carol.game!.endReason, ChessEndReason.resignation); + }); + + test('a draw accept or timeout claim that crosses a move does not ' + 'apply', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + await white.service.makeMove(white.game!, 'e2e4'); + now = now.add(const Duration(hours: 1, minutes: 11)); + expect(white.service.canClaimTimeout(white.game!), isTrue); + + // White's claim and Black's move cross on air. + Uint8List? claim; + mesh.filter = (from, to, payload) { + if (from == white.link && + ChessPacket.decode(payload) is ChessActionPacket) { + claim = payload; + return false; + } + return true; + }; + white.link.slow = true; + Timer.run(() => black.service.makeMove(black.game!, 'e7e5')); + expect(await white.service.claimTimeout(white.game!), isFalse); + await settle(); + black.service.handleIncoming(ChessIncoming(_channel, claim!)); + for (final p in [white, black]) { + expect(p.game!.status, ChessGameStatus.active); + expect(p.game!.ply, 2); + } + // The claim's value is used up on both sides. + final claimIndex = white.game!.myNextChainIndex - 1; + expect(white.game!.playerOf(white.game!.mySide!)!.lastIndex, claimIndex); + expect(black.game!.playerOf(ChessSide.white)!.lastIndex, claimIndex); + + // Same for a draw accept crossing a move. + claim = null; + await white.service.makeMove(white.game!, 'g1f3'); + await black.service.offerDraw(black.game!); + expect(white.game!.drawOfferedBy, ChessSide.black); + // Black then moves after all, while White accepts. + Timer.run(() => black.service.makeMove(black.game!, 'b8c6')); + expect(await white.service.acceptDraw(white.game!), isFalse); + await settle(); + black.service.handleIncoming(ChessIncoming(_channel, claim!)); + for (final p in [white, black]) { + expect(p.game!.status, ChessGameStatus.active); + expect(p.game!.ply, 4); + } + mesh.filter = null; + white.link.slow = false; + expect(await white.service.makeMove(white.game!, 'f1c4'), isTrue); + expect(black.game!.ply, 5); + }); + test('a malformed position never throws out of the listener', () { final carol = player('Carol'); final packet = Uint8List.fromList(