From c2877f687533128f0d36a9e20068b595a7907643 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 22 Nov 2026 17:44:28 -0700 Subject: [PATCH] Harden chess against forged packets and lost moves - Chain values count once and in order; moves need a fresh value - Game info carries the inviter's chain value; colours come from the invite - Accepters keep their seed; unconfirmed sends keep the move and resend it - Check draw accept and timeout claim preconditions; drop unused minutes - Notify in the background, keep own games under the cap, 16-bit ply - Sanitise adopted castling rights, guard incoming handling - Localised square labels and translations for the new strings - Restore two Korean strings changed by mistake --- documentation/games.md | 27 +- lib/games/chess/chess_game.dart | 89 ++-- lib/games/chess/chess_packets.dart | 53 +- lib/games/chess/chess_position_codec.dart | 39 +- lib/games/chess/chess_service.dart | 586 +++++++++++++++------ lib/games/chess/ui/chess_board.dart | 18 +- lib/games/chess/ui/chess_game_screen.dart | 7 +- lib/games/chess/ui/chess_games_sheet.dart | 26 +- lib/games/game_packet.dart | 11 +- lib/l10n/app_bg.arb | 9 +- lib/l10n/app_cs.arb | 9 +- lib/l10n/app_de.arb | 9 +- lib/l10n/app_en.arb | 37 ++ lib/l10n/app_es.arb | 9 +- lib/l10n/app_fr.arb | 9 +- lib/l10n/app_hu.arb | 9 +- lib/l10n/app_it.arb | 9 +- lib/l10n/app_ja.arb | 9 +- lib/l10n/app_ko.arb | 13 +- lib/l10n/app_localizations.dart | 42 ++ lib/l10n/app_localizations_bg.dart | 29 + lib/l10n/app_localizations_cs.dart | 29 + lib/l10n/app_localizations_de.dart | 29 + lib/l10n/app_localizations_en.dart | 29 + lib/l10n/app_localizations_es.dart | 29 + lib/l10n/app_localizations_fr.dart | 29 + lib/l10n/app_localizations_hu.dart | 29 + lib/l10n/app_localizations_it.dart | 29 + lib/l10n/app_localizations_ja.dart | 29 + lib/l10n/app_localizations_ko.dart | 32 +- lib/l10n/app_localizations_nl.dart | 29 + lib/l10n/app_localizations_pl.dart | 29 + lib/l10n/app_localizations_pt.dart | 58 ++ lib/l10n/app_localizations_ru.dart | 29 + lib/l10n/app_localizations_sk.dart | 29 + lib/l10n/app_localizations_sl.dart | 29 + lib/l10n/app_localizations_sv.dart | 29 + lib/l10n/app_localizations_uk.dart | 29 + lib/l10n/app_localizations_zh.dart | 27 + lib/l10n/app_nl.arb | 9 +- lib/l10n/app_pl.arb | 9 +- lib/l10n/app_pt.arb | 9 +- lib/l10n/app_pt_PT.arb | 9 +- lib/l10n/app_ru.arb | 9 +- lib/l10n/app_sk.arb | 9 +- lib/l10n/app_sl.arb | 9 +- lib/l10n/app_sv.arb | 9 +- lib/l10n/app_uk.arb | 9 +- lib/l10n/app_zh.arb | 9 +- test/games/chess_protocol_test.dart | 83 ++- test/games/chess_service_test.dart | 488 ++++++++++++++++- test/games/chess_ui_test.dart | 14 +- test/screens/small_screen_layout_test.dart | 7 +- 53 files changed, 1977 insertions(+), 306 deletions(-) diff --git a/documentation/games.md b/documentation/games.md index 7e31c74a..c68e5632 100644 --- a/documentation/games.md +++ b/documentation/games.md @@ -11,7 +11,7 @@ Play chess with someone on a channel, or watch other people's games. Moves go ov Open a channel, tap **⋮**, then **Chess games**. The menu shows how many games and invites are open on that channel. -- **Challenge someone**: pick a person recently heard on this channel. Only they can accept. Their phone shows a notification. +- **Challenge someone**: pick a person recently heard on this channel. Only a radio with that name can accept. Their phone shows a notification. - **Post an open invite**: anyone on the channel can accept. If two people accept at the same time, the inviter's phone picks the first one it heard and tells everyone; the other person keeps watching. Choose the **time per move** (no limit, 15 minutes, 1 hour (default), 6 hours, 1 day or 3 days) and **your colour** (random, white or black). Unanswered invites expire after a day. Tap your own invite to cancel it. @@ -22,37 +22,42 @@ 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. -- **Ask for update** asks the players to send the latest move again. Use it when a game looks stuck. A player answers within a few seconds, at most once a minute per game. +- **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. + +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. Checkmate, stalemate, not enough pieces to mate, the 50-move rule and repetition end the game on their own. -You get a notification when you're challenged, when it's your move, and when a game ends, unless the channel is muted. Notifications open the channel. +You get a notification when you're challenged, when it's your move, and when a game ends, unless the channel is muted or the game is open on screen. Notifications open the channel. ## Watch -Every game on the channel shows up under **Live games**. If you joined late, the board appears with the next move, because each move carries the whole position. Moves from before you joined show as "(missed)". Until you've heard how the game started, the players are marked as not confirmed; **Ask for update** fetches that. +Every game on the channel shows up under **Live games**. If you joined late, the board appears with the next move, because each move carries the whole position. Moves from before you joined show as "(missed)". Until you've heard how the game started, the players are marked as not confirmed; **Ask for update** fetches that. If your phone never heard the invite, the players stay marked as not confirmed, because nothing ties them to it. Finished games stay in the list for a week. Tap **✕** to remove one sooner. ## How moves are sent -Each packet starts with a 4-byte header: app and packet kind, a random 2-byte game ID, and the half-move number. Kinds are invite, accept, decline, move, resign, draw offer, draw accept, cancel, timeout claim, game info and request. +Each packet starts with a 5-byte header: app and packet kind, a random 2-byte game ID, and the 2-byte half-move number. Kinds are invite, accept, decline, move, resign, draw offer, draw accept, cancel, timeout claim, game info and request. -A move is 49 bytes or less, which fills four 16-byte encrypted blocks on air: +A move is 48 bytes or less, which fills four 16-byte encrypted blocks on air: | Field | Bytes | |---|---| -| Header | 4 | -| Minutes since the game started | 2 | +| Header | 5 | | Move, as its index in the sorted list of legal moves | 1 | | Chain value (see below) | 16 | | Position after the move | ≤26 | The position is an 8-byte map of occupied squares, 2 bytes for side to move, castling, en passant and the 50-move counter, then half a byte per piece. -**Checking who moved.** Each player's phone makes a secret value and hashes it 512 times. Only the last hash is sent, in the invite or accept. Each later action reveals the hash one step back, which anyone can check with a single hash but nobody else can produce. A packet with a value that doesn't fit the player's chain is ignored. If two different packets arrive with the same value, the first one heard counts. Player names are not checked; the chain is. +Other packets: invite 55 bytes (87 for a challenge, with the name), accept 53, decline 37, resign, draw offer, draw accept, cancel and timeout claim 21 each, game info 122, request 6, with names of up to 31 bytes. -Players also check that the move gives the position in the packet. Spectators who missed moves take the position as it is. +**Checking who moved.** Each player's phone makes a secret value and hashes it 512 times. Only the last hash is sent, in the invite or accept. Each later action reveals the hash one step back, which anyone can check by hashing it forward but nobody else can produce. A packet with a value that doesn't fit the player's chain is ignored. Each value counts once, and only after the ones before it: the first packet heard with a value uses it up, even when it doesn't change the game (a draw offer for a position you haven't seen yet, say), and values before it no longer count. If your opponent then needs a move again, their phone sends it with a new value. Player names are not checked; the chain is. + +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. 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 ecf80bf4..d3fc262a 100644 --- a/lib/games/chess/chess_game.dart +++ b/lib/games/chess/chess_game.dart @@ -45,38 +45,42 @@ enum ChessEndReason { taken, } -/// One player's identity in a game: their name (unauthenticated) and the -/// hash chain values verified so far. +/// One player's identity in a game: their name (unauthenticated), their +/// chain commitment, and the highest chain index used up so far. +/// +/// Values count once and only in order: a value is fresh when its index is +/// above [lastIndex]. Anyone can hash a revealed value back to the lower +/// ones, so once index `i` is used up nothing at or below it is accepted. class ChessPlayer { final String name; final Uint8List commitment; - Uint8List lastValue; int lastIndex; ChessPlayer({ required this.name, required this.commitment, - Uint8List? lastValue, this.lastIndex = 0, - }) : lastValue = lastValue ?? commitment; + }); - /// Accepts [value] when it extends this player's chain, returning true. - bool verifyAndAdvance(Uint8List value) { - final steps = hashChainDistance(value, lastValue); - if (steps == null || steps == 0) return false; - lastValue = value; - lastIndex += steps; - return true; + /// The inviter's record: index 1 is reserved for the game info. + ChessPlayer.inviter({required this.name, required this.commitment}) + : lastIndex = 1; + + /// Chain index of [value] when it is on this chain and not used up yet, + /// otherwise null. Does not change anything. + int? freshIndex(Uint8List value) { + final index = hashChainDistance(value, commitment); + return index != null && index > lastIndex ? index : null; } - /// True when [value] is on this player's chain at or after the last - /// verified value (a valid new value or an exact duplicate). - bool owns(Uint8List value) => hashChainDistance(value, lastValue) != null; + /// Marks every value up to [index] as used. + void use(int index) { + if (index > lastIndex) lastIndex = index; + } Map toJson() => { 'name': name, 'commitment': _hex(commitment), - 'last': _hex(lastValue), 'index': lastIndex, }; @@ -88,7 +92,6 @@ class ChessPlayer { return ChessPlayer( name: name, commitment: commitment, - lastValue: _unhex(json['last']) ?? commitment, lastIndex: json['index'] is int ? json['index'] as int : 0, ); } @@ -112,8 +115,12 @@ class ChessGame { ChessPlayer? white; ChessPlayer? black; - /// Our own chain seed (hex) when we are a player or the inviter. + /// Our own chain seed (hex) when we posted or accepted the invite. Kept + /// after losing an accept race, in case a later game info lists us. String? mySeedHex; + + /// Next index of our chain to reveal. Never goes back, even after a failed + /// send: the packet may have gone out. int myNextChainIndex; /// Which side we play, or null when watching. @@ -122,6 +129,17 @@ class ChessGame { /// True when we posted the invite. bool iAmInviter; + /// False while [white] and [black] come from a game info we could not + /// check, because we never heard the invite. + bool playersConfirmed; + + /// Our last move was applied but the radio did not confirm sending it. + bool moveUnconfirmed; + + /// Value 1 of the inviter's chain, from the game info, so any player can + /// send the game info again. + Uint8List? inviterInfoValue; + /// Position the move history below starts from: the start position, or a /// position adopted after missed moves. String baseFen; @@ -166,6 +184,9 @@ class ChessGame { this.myNextChainIndex = 1, this.mySide, this.iAmInviter = false, + this.playersConfirmed = true, + this.moveUnconfirmed = false, + this.inviterInfoValue, String? baseFen, List? uciSinceBase, List? sanMoves, @@ -199,6 +220,9 @@ class ChessGame { /// Players are known (we can verify their actions). bool get hasPlayers => white != null && black != null; + /// We posted or accepted this game. + bool get isMine => iAmInviter || mySeedHex != null; + ChessSide get sideToMove => ChessSide.moverOfPly(ply + 1); bool get isMyTurn => @@ -209,10 +233,12 @@ class ChessGame { String? nameOf(ChessSide side) => playerOf(side)?.name; - /// Which side's chain [value] belongs to, if any. - ChessSide? sideOwning(Uint8List value) { - if (white?.owns(value) ?? false) return ChessSide.white; - if (black?.owns(value) ?? false) return ChessSide.black; + /// The side whose chain holds [value] as a fresh value, with its index. + (ChessSide, int)? freshSide(Uint8List value) { + for (final side in ChessSide.values) { + final index = playerOf(side)?.freshIndex(value); + if (index != null) return (side, index); + } return null; } @@ -221,11 +247,12 @@ class ChessGame { return seed == null ? null : HashChain(seed); } - /// The next value of our chain, advancing the counter. - Uint8List? takeMyChainValue() { + /// The next value of our chain with its index, advancing the counter. + ({int index, Uint8List value})? takeMyChainValue() { final chain = myChain; if (chain == null || myNextChainIndex > HashChain.length) return null; - return chain.valueAt(myNextChainIndex++); + final index = myNextChainIndex++; + return (index: index, value: chain.valueAt(index)); } /// Rules engine at the current position, with as much history as we have @@ -314,12 +341,6 @@ class ChessGame { /// The packed position for the current [fen]. Uint8List packedPosition() => ChessPositionCodec.encodeFen(fen); - /// Minutes since the game started, for move packets. - int minutesSinceStart(int nowMs) { - final start = startedAtMs ?? createdAtMs; - return ((nowMs - start) ~/ 60000).clamp(0, 0xFFFF); - } - Map toJson() => { 'channel': channelId, 'id': gameId, @@ -334,6 +355,9 @@ class ChessGame { 'nextChain': myNextChainIndex, if (mySide != null) 'side': mySide!.name, 'inviterSelf': iAmInviter, + if (!playersConfirmed) 'unconfirmed': true, + if (moveUnconfirmed) 'moveUnconfirmed': true, + if (inviterInfoValue != null) 'infoValue': _hex(inviterInfoValue!), 'baseFen': baseFen, 'uci': uciSinceBase, 'san': sanMoves, @@ -379,6 +403,9 @@ class ChessGame { myNextChainIndex: _int(json['nextChain']) ?? 1, mySide: _enumByNameOrNull(ChessSide.values, json['side']), iAmInviter: json['inviterSelf'] == true, + playersConfirmed: json['unconfirmed'] != true, + moveUnconfirmed: json['moveUnconfirmed'] == true, + inviterInfoValue: _unhex(json['infoValue']), baseFen: json['baseFen'] as String?, uciSinceBase: (json['uci'] as List?)?.whereType().toList(), sanMoves: (json['san'] as List?)?.map((e) => e as String?).toList(), diff --git a/lib/games/chess/chess_packets.dart b/lib/games/chess/chess_packets.dart index 2b4462d4..df7c52ca 100644 --- a/lib/games/chess/chess_packets.dart +++ b/lib/games/chess/chess_packets.dart @@ -60,7 +60,7 @@ enum ChessDeadline { values.firstWhere((v) => v.code == code, orElse: () => defaultValue); } -/// A decoded chess packet. [ply] is the half-move number modulo 256. +/// A decoded chess packet. [ply] is a half-move number (see each kind). sealed class ChessPacket { final int gameId; final int ply; @@ -196,8 +196,8 @@ class ChessAcceptPacket extends ChessPacket { } } -/// A declined direct challenge. Not authenticated; only the inviter acts on -/// it, and only for a challenge addressed to [declinerName]. +/// A declined direct challenge. Not authenticated, so only the inviter acts +/// on it, and only for a challenge addressed to [declinerName]. class ChessDeclinePacket extends ChessPacket { final String declinerName; @@ -220,7 +220,6 @@ class ChessDeclinePacket extends ChessPacket { /// One half-move. [ply] is the number of the half-move being made (the first /// move of the game has ply 1). [position] is the packed position after it. class ChessMovePacket extends ChessPacket { - final int minutes; final int moveIndex; final Uint8List chainValue; final Uint8List position; @@ -228,7 +227,6 @@ class ChessMovePacket extends ChessPacket { const ChessMovePacket({ required super.gameId, required super.ply, - required this.minutes, required this.moveIndex, required this.chainValue, required this.position, @@ -239,24 +237,30 @@ class ChessMovePacket extends ChessPacket { @override void writeBody(BytesBuilder out) { - writeU16(out, minutes); out ..addByte(moveIndex) ..add(chainValue) ..add(position); } + /// The same move carrying [value] instead of [chainValue]. + ChessMovePacket withChainValue(Uint8List value) => ChessMovePacket( + gameId: gameId, + ply: ply, + moveIndex: moveIndex, + chainValue: value, + position: position, + ); + static ChessMovePacket? _read(int id, int ply, GamePacketReader r) { - final minutes = r.u16(); final index = r.u8(); final chain = r.bytes(HashChain.valueBytes); final position = r.rest(); - if (minutes == null || index == null || chain == null) return null; + if (index == null || chain == null) return null; if (position == null || position.isEmpty) return null; return ChessMovePacket( gameId: id, ply: ply, - minutes: minutes, moveIndex: index, chainValue: chain, position: position, @@ -265,26 +269,22 @@ class ChessMovePacket extends ChessPacket { } /// Resign, draw offer, draw accept, cancel invite or timeout claim: an -/// authenticated action with no other data. +/// authenticated action with no other data. [ply] is the sender's current +/// half-move number. class ChessActionPacket extends ChessPacket { @override final ChessPacketKind kind; - final int minutes; final Uint8List chainValue; const ChessActionPacket({ required this.kind, required super.gameId, required super.ply, - required this.minutes, required this.chainValue, }); @override - void writeBody(BytesBuilder out) { - writeU16(out, minutes); - out.add(chainValue); - } + void writeBody(BytesBuilder out) => out.add(chainValue); static ChessActionPacket? _read( ChessPacketKind kind, @@ -292,25 +292,27 @@ class ChessActionPacket extends ChessPacket { int ply, GamePacketReader r, ) { - final minutes = r.u16(); final chain = r.bytes(HashChain.valueBytes); - if (minutes == null || chain == null) return null; + if (chain == null) return null; return ChessActionPacket( kind: kind, gameId: id, ply: ply, - minutes: minutes, chainValue: chain, ); } } -/// Everything a late spectator needs to follow and verify a game. +/// The inviter's confirmation of who plays: everything a spectator needs to +/// follow and verify a game. [inviterValue] is value 1 of the inviter's +/// chain, which is used for nothing else, so anyone who heard the invite can +/// check that the inviter sent it. [ply] is the sender's current half-move. class ChessInfoPacket extends ChessPacket { final int startedAtUnix; final ChessDeadline deadline; final Uint8List whiteCommitment; final Uint8List blackCommitment; + final Uint8List inviterValue; final String whiteName; final String blackName; @@ -321,6 +323,7 @@ class ChessInfoPacket extends ChessPacket { required this.deadline, required this.whiteCommitment, required this.blackCommitment, + required this.inviterValue, required this.whiteName, required this.blackName, }); @@ -333,9 +336,9 @@ class ChessInfoPacket extends ChessPacket { writeU32(out, startedAtUnix); out ..addByte(deadline.code) - ..addByte(0) // flags, reserved ..add(whiteCommitment) - ..add(blackCommitment); + ..add(blackCommitment) + ..add(inviterValue); writeShortString(out, whiteName); writeShortString(out, blackName); } @@ -343,13 +346,14 @@ class ChessInfoPacket extends ChessPacket { static ChessInfoPacket? _read(int id, int ply, GamePacketReader r) { final started = r.u32(); final deadline = r.u8(); - r.u8(); // flags final white = r.bytes(HashChain.valueBytes); final black = r.bytes(HashChain.valueBytes); + final inviterValue = r.bytes(HashChain.valueBytes); final whiteName = r.shortString(); final blackName = r.shortString(); if (started == null || deadline == null || white == null) return null; - if (black == null || whiteName == null || blackName == null) return null; + if (black == null || inviterValue == null) return null; + if (whiteName == null || blackName == null) return null; return ChessInfoPacket( gameId: id, ply: ply, @@ -357,6 +361,7 @@ class ChessInfoPacket extends ChessPacket { deadline: ChessDeadline.fromCode(deadline), whiteCommitment: white, blackCommitment: black, + inviterValue: inviterValue, whiteName: whiteName, blackName: blackName, ); diff --git a/lib/games/chess/chess_position_codec.dart b/lib/games/chess/chess_position_codec.dart index 9d44245c..38be1e59 100644 --- a/lib/games/chess/chess_position_codec.dart +++ b/lib/games/chess/chess_position_codec.dart @@ -83,7 +83,8 @@ abstract final class ChessPositionCodec { /// Unpacks [bytes] into a FEN with [fullMoveNumber]. Returns null when the /// bytes are malformed (wrong length for the occupancy, bad piece codes). - /// Does not check that the position is legal. + /// Castling and en-passant rights that the pieces rule out are dropped; + /// otherwise the position is not checked for legality. static String? decodeToFen(Uint8List bytes, {required int fullMoveNumber}) { if (bytes.length < _fixedBytes) return null; final squares = []; @@ -123,17 +124,37 @@ abstract final class ChessPositionCodec { final state = bytes[8] | (bytes[9] << 8); final blackToMove = state & 1 != 0; + // Square indices: a1 = 0, e1 = 4, h1 = 7, a8 = 56, e8 = 60, h8 = 63. final castling = StringBuffer(); - if (state & (1 << 1) != 0) castling.write('K'); - if (state & (1 << 2) != 0) castling.write('Q'); - if (state & (1 << 3) != 0) castling.write('k'); - if (state & (1 << 4) != 0) castling.write('q'); + if (state & (1 << 1) != 0 && board[4] == 'K' && board[7] == 'R') { + castling.write('K'); + } + if (state & (1 << 2) != 0 && board[4] == 'K' && board[0] == 'R') { + castling.write('Q'); + } + if (state & (1 << 3) != 0 && board[60] == 'k' && board[63] == 'r') { + castling.write('k'); + } + if (state & (1 << 4) != 0 && board[60] == 'k' && board[56] == 'r') { + castling.write('q'); + } final epFile = (state >> 5) & 0x0F; if (epFile > 8) return null; - final ep = epFile == 0 - ? '-' - : '${String.fromCharCode('a'.codeUnitAt(0) + epFile - 1)}' - '${blackToMove ? 3 : 6}'; + var ep = '-'; + if (epFile != 0) { + final file = epFile - 1; + // The pawn that just moved two squares, and the two squares it passed. + final pawnSq = (blackToMove ? 3 : 4) * 8 + file; + final passed = (blackToMove ? 2 : 5) * 8 + file; + final start = (blackToMove ? 1 : 6) * 8 + file; + if (board[pawnSq] == (blackToMove ? 'P' : 'p') && + board[passed] == null && + board[start] == null) { + ep = + '${String.fromCharCode('a'.codeUnitAt(0) + file)}' + '${blackToMove ? 3 : 6}'; + } + } final halfmove = (state >> 9) & 0x7F; return '${rows.join('/')} ${blackToMove ? 'b' : 'w'} ' diff --git a/lib/games/chess/chess_service.dart b/lib/games/chess/chess_service.dart index c33424b9..e09ae044 100644 --- a/lib/games/chess/chess_service.dart +++ b/lib/games/chess/chess_service.dart @@ -1,8 +1,9 @@ import 'dart:async'; import 'dart:math'; +import 'dart:typed_data'; import 'package:crypto/crypto.dart'; -import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import '../hash_chain.dart'; import 'chess_game.dart'; @@ -14,8 +15,8 @@ import 'chess_store.dart'; /// Chess games played and watched on channels. /// /// Packets arrive through [ChessLink.incoming]; every handler is idempotent, -/// so duplicates and repeats are harmless. Our own actions are sent first -/// and applied locally once the radio accepted them. +/// so duplicates and repeats are harmless. Each chain value counts once: the +/// first packet heard with it uses it up. class ChessService extends ChangeNotifier { static const Duration inviteLifetime = Duration(hours: 24); static const Duration timeoutGrace = Duration(minutes: 10); @@ -29,6 +30,7 @@ class ChessService extends ChangeNotifier { final Random _random; final Duration _answerDelayMin; final Duration _answerDelayMax; + final bool Function() _isForeground; final Map _games = {}; final Set _sending = {}; @@ -47,11 +49,13 @@ class ChessService extends ChangeNotifier { Duration answerDelayMin = const Duration(seconds: 2), Duration answerDelayMax = const Duration(seconds: 10), bool startHousekeeping = true, + bool Function()? isForeground, }) : store = store ?? ChessStore(), _clock = clock ?? DateTime.now, _random = random ?? Random.secure(), _answerDelayMin = answerDelayMin, - _answerDelayMax = answerDelayMax { + _answerDelayMax = answerDelayMax, + _isForeground = isForeground ?? _appResumed { _sub = link.incoming.listen(handleIncoming); link.addListener(_onLinkChanged); _loadScope(link.storageScope); @@ -65,6 +69,15 @@ class ChessService extends ChangeNotifier { int get _now => _clock().millisecondsSinceEpoch; + static bool _appResumed() { + try { + final state = WidgetsBinding.instance.lifecycleState; + return state == null || state == AppLifecycleState.resumed; + } catch (_) { + return true; + } + } + // ---- queries --------------------------------------------------------------- /// Games on [channelId], newest activity first. @@ -72,9 +85,19 @@ class ChessService extends ChangeNotifier { _games.values.where((g) => g.channelId == channelId).toList() ..sort((a, b) => b.lastActivityMs.compareTo(a.lastActivityMs)); - /// Live games plus open invites on [channelId]. - int openCountForChannel(String channelId) => - _games.values.where((g) => g.channelId == channelId && g.isOpen).length; + /// Live games plus open invites on [channelId], as the games sheet lists + /// them. + int openCountForChannel(String channelId) => _games.values + .where((g) => g.channelId == channelId && g.isOpen && isListed(g)) + .length; + + /// False for an open challenge between two other people, which the games + /// sheet does not show. + bool isListed(ChessGame game) => + game.status != ChessGameStatus.invite || + game.iAmInviter || + game.targetName == null || + _isMe(game.targetName); ChessGame? game(String channelId, int gameId) => _games[ChessGame.gameKey(channelId, gameId)]; @@ -101,7 +124,8 @@ class ChessService extends ChangeNotifier { return at != null && _clock().isAfter(at.add(timeoutGrace)); } - /// The screen showing [game] (no notifications for it), or null. + /// The screen showing [game] (no notifications for it while the app is in + /// the foreground), or null. set viewing(ChessGame? game) => _viewingKey = game?.key; // ---- our actions ----------------------------------------------------------- @@ -129,9 +153,15 @@ class ChessService extends ChangeNotifier { status: ChessGameStatus.invite, deadline: deadline, colourPreference: colour, - inviter: ChessPlayer(name: link.selfName, commitment: chain.commitment), + inviter: ChessPlayer.inviter( + name: link.selfName, + commitment: chain.commitment, + ), targetName: targetName, mySeedHex: bytesToHex(chain.seed), + // Value 1 is the game info's; actions start at 2. + myNextChainIndex: 2, + inviterInfoValue: chain.valueAt(1), iAmInviter: true, createdAtMs: _now, ); @@ -143,27 +173,39 @@ class ChessService extends ChangeNotifier { Future accept(ChessGame game) async { if (game.status != ChessGameStatus.invite || game.iAmInviter) return false; - final chain = HashChain.generate(_random); - final packet = ChessAcceptPacket( - gameId: game.gameId, - commitment: chain.commitment, - accepterName: link.selfName, - ); - if (!await _send(game, packet)) return false; + if (isSending(game) || !link.canSend) return false; + // Reuse the chain of an earlier attempt: that accept may have gone out. + game.mySeedHex ??= bytesToHex(HashChain.generate(_random).seed); + // Waiting from now on, so a confirmation heard mid-send is ours. game - ..mySeedHex = bytesToHex(chain.seed) - ..myNextChainIndex = 1 ..status = ChessGameStatus.starting ..lastActivityMs = _now; _changed(); - return true; + final ok = await _send( + game, + ChessAcceptPacket( + gameId: game.gameId, + commitment: game.myChain!.commitment, + accepterName: link.selfName, + ), + ); + if (!ok && game.status == ChessGameStatus.starting) { + game.status = ChessGameStatus.invite; + _changed(); + } + return ok; } - /// Re-sends our accept while waiting for the inviter's confirmation. + /// Re-sends our accept while waiting for the inviter's confirmation, or + /// after a game info listed someone else. The inviter answers with the + /// game info, which lists us if ours was the accept that counted. Future resendAccept(ChessGame game) async { - if (game.status != ChessGameStatus.starting) return false; final chain = game.myChain; - if (chain == null) return false; + if (chain == null || game.iAmInviter) return false; + final waiting = + game.status == ChessGameStatus.starting || + (game.status == ChessGameStatus.active && !game.isPlayer); + if (!waiting) return false; return _send( game, ChessAcceptPacket( @@ -193,40 +235,45 @@ class ChessService extends ChangeNotifier { }, allowedStatus: ChessGameStatus.invite); /// Plays [uci] (e.g. `e2e4`, `e7e8q`). + /// + /// Returns false when the radio did not confirm the send. The move is + /// still applied then, since it may have gone out; [requestUpdate] sends + /// it again. Future makeMove(ChessGame game, String uci) async { - if (!game.isMyTurn || isSending(game)) return false; + if (!game.isMyTurn || isSending(game) || !link.canSend) return false; final legal = game.legalUci(); final index = legal.indexOf(uci); if (index < 0 || index > 255) return false; - final value = game.takeMyChainValue(); - if (value == null) return false; - // Work on a copy of the position so a failed send changes nothing. final probe = ChessGame.fromJson(game.toJson())!; - probe.applyUci(uci); + if (!probe.applyUci(uci)) return false; + final chain = game.takeMyChainValue(); + if (chain == null) return false; final packet = ChessMovePacket( gameId: game.gameId, - ply: probe.ply & 0xFF, - minutes: game.minutesSinceStart(_now), + ply: probe.ply, moveIndex: index, - chainValue: value, + chainValue: chain.value, position: probe.packedPosition(), ); - if (!await _send(game, packet)) { - game.myNextChainIndex--; - return false; + final plyBefore = game.ply; + final ok = await _send(game, packet); + if (game.status != ChessGameStatus.active || game.ply != plyBefore) { + _changed(); + return ok; } game.applyUci(uci); - game.playerOf(game.mySide!)?.verifyAndAdvance(value); + game.playerOf(game.mySide!)?.use(chain.index); game ..lastMovePacket = packet.encode() - ..lastMoveAtMs = _now; + ..lastMoveAtMs = _now + ..moveUnconfirmed = !ok; _touch(game); - return true; + return ok; } Future resign(ChessGame game) => _sendAction(game, ChessPacketKind.resign, (g, side) { - g.finish(ChessEndReason.resignation, winner: side.other); + g.finish(ChessEndReason.resignation, winner: side!.other); }); Future offerDraw(ChessGame game) => @@ -235,7 +282,8 @@ class ChessService extends ChangeNotifier { }); Future acceptDraw(ChessGame game) { - if (game.drawOfferedBy == null || game.drawOfferedBy == game.mySide) { + final side = game.mySide; + if (side == null || game.drawOfferedBy != side.other) { return Future.value(false); } return _sendAction(game, ChessPacketKind.drawAccept, (g, _) { @@ -250,15 +298,25 @@ class ChessService extends ChangeNotifier { }); } - /// Asks the players for whatever we are missing: the game info when we - /// cannot verify the players, the latest move otherwise. + /// 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 + /// missed it). Otherwise asks the players for what we are missing: the + /// game info when we cannot verify the players, and the latest move. Future requestUpdate(ChessGame game) { - if (game.status == ChessGameStatus.starting) return resendAccept(game); + if (game.status == ChessGameStatus.starting || + (game.status == ChessGameStatus.active && + !game.isPlayer && + game.isMine)) { + return resendAccept(game); + } + if (_latestMoveIsMine(game) && game.status == ChessGameStatus.active) { + return _resendLatestMove(game); + } return _send( game, ChessRequestPacket( gameId: game.gameId, - ply: game.ply & 0xFF, + ply: game.ply, wantsInfo: !game.hasPlayers, wantsLatestMove: true, ), @@ -273,44 +331,81 @@ class ChessService extends ChangeNotifier { Future _sendAction( ChessGame game, ChessPacketKind kind, - void Function(ChessGame game, ChessSide side) apply, { + void Function(ChessGame game, ChessSide? side) apply, { ChessGameStatus allowedStatus = ChessGameStatus.active, }) async { if (game.status != allowedStatus || isSending(game)) return false; + if (!link.canSend) return false; final side = game.mySide; - if (side == null && !(kind == ChessPacketKind.cancel && game.iAmInviter)) { - return false; - } - final value = game.takeMyChainValue(); - if (value == null) return false; - final packet = ChessActionPacket( - kind: kind, - gameId: game.gameId, - ply: game.ply & 0xFF, - minutes: game.minutesSinceStart(_now), - chainValue: value, + final record = kind == ChessPacketKind.cancel + ? (game.iAmInviter ? game.inviter : null) + : (side == null ? null : game.playerOf(side)); + if (record == null) return false; + final chain = game.takeMyChainValue(); + 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 (!await _send(game, packet)) { - game.myNextChainIndex--; + if (!ok || game.status != allowedStatus) { + _changed(); return false; } - if (side != null) { - game.playerOf(side)?.verifyAndAdvance(value); - apply(game, side); - } else { - game.inviter?.verifyAndAdvance(value); - apply(game, ChessSide.white); - } + apply(game, side); _touch(game); return true; } - Future _send(ChessGame game, ChessPacket packet) async { + bool _latestMoveIsMine(ChessGame game) => + game.isPlayer && + game.ply > 0 && + ChessSide.moverOfPly(game.ply) == game.mySide && + game.lastMovePacket != null; + + /// Sends our latest move again. After we revealed a later chain value + /// (a draw offer, say), receivers refuse the old value, so the move goes + /// out with the next value instead. + Future _resendLatestMove(ChessGame game) async { + final raw = game.lastMovePacket; + final chain = game.myChain; + final old = raw == null ? null : ChessPacket.decode(raw); + if (old is! ChessMovePacket || chain == null || !link.canSend) { + return false; + } + var packet = raw!; + final latest = chain.valueAt(game.myNextChainIndex - 1); + if (!bytesEqual(old.chainValue, latest)) { + final next = game.takeMyChainValue(); + if (next == null) return false; + game.playerOf(game.mySide!)?.use(next.index); + packet = old.withChainValue(next.value).encode(); + game.lastMovePacket = packet; + _changed(); + } + final ok = await _sendRaw(game, packet); + if (ok && game.moveUnconfirmed) { + game.moveUnconfirmed = false; + _changed(); + } + return ok; + } + + Future _send(ChessGame game, ChessPacket packet) => + _sendRaw(game, packet.encode()); + + Future _sendRaw(ChessGame game, Uint8List payload) async { if (!link.canSend) return false; _sending.add(game.key); notifyListeners(); try { - return await link.send(game.channelId, packet.encode()); + return await link.send(game.channelId, payload); } finally { _sending.remove(game.key); if (!_disposed) notifyListeners(); @@ -328,10 +423,25 @@ class ChessService extends ChangeNotifier { @visibleForTesting void handleIncoming(ChessIncoming incoming) { + try { + _handle(incoming); + } catch (e) { + // A malformed packet must never break the stream listener. + debugPrint('Chess: ignored packet: $e'); + } + } + + void _handle(ChessIncoming incoming) { final packet = ChessPacket.decode(incoming.payload); 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))) { + // Someone answered; our own pending answer is no longer needed. + _pendingAnswers.remove(existing.key)?.cancel(); + } final changed = switch (packet) { ChessInvitePacket p => _onInvite(channelId, existing, p), ChessAcceptPacket p => _onAccept(existing, p), @@ -341,11 +451,6 @@ class ChessService extends ChangeNotifier { ChessInfoPacket p => _onInfo(channelId, existing, p), ChessRequestPacket p => _onRequest(existing, p), }; - if ((packet is ChessInfoPacket || packet is ChessMovePacket) && - existing != null) { - // Someone answered; our own pending answer is no longer needed. - _pendingAnswers.remove(existing.key)?.cancel(); - } if (changed) _changed(); } @@ -357,7 +462,10 @@ class ChessService extends ChangeNotifier { status: ChessGameStatus.invite, deadline: p.deadline, colourPreference: p.colour, - inviter: ChessPlayer(name: p.inviterName, commitment: p.commitment), + inviter: ChessPlayer.inviter( + name: p.inviterName, + commitment: p.commitment, + ), targetName: p.targetName, createdAtMs: _now, ); @@ -371,16 +479,10 @@ class ChessService extends ChangeNotifier { bool _onAccept(ChessGame? game, ChessAcceptPacket p) { if (game == null) return false; if (game.iAmInviter && game.status == ChessGameStatus.active) { - // A repeated accept: the accepter may have missed our confirmation. - final accepted = game.playerOf(game.mySide!.other); - if (accepted != null && bytesEqual(accepted.commitment, p.commitment)) { - _scheduleAnswer( - game, - info: true, - latestMove: game.ply > 0, - immediate: true, - ); - } + // A repeated accept: the accepter missed our confirmation, or lost to + // another accept without hearing it. The game info and the latest + // move answer both. Rate-limited like any answer. + _scheduleAnswer(game, info: true, latestMove: game.ply > 0); return false; } if (game.status != ChessGameStatus.invite) return false; @@ -421,29 +523,65 @@ class ChessService extends ChangeNotifier { } bool _onDecline(ChessGame? game, ChessDeclinePacket p) { - if (game == null || game.status != ChessGameStatus.invite) return false; + // Anyone can send a decline, so only the inviter acts on it. + if (game == null || !game.iAmInviter) return false; + if (game.status != ChessGameStatus.invite) return false; final target = game.targetName; if (target == null || !_sameName(target, p.declinerName)) return false; - game.finish(ChessEndReason.declined); - game.lastActivityMs = _now; - if (game.iAmInviter) { - _notify(game, link.l10n.chess_notifyDeclined(p.declinerName)); - } + game + ..finish(ChessEndReason.declined) + ..lastActivityMs = _now; + _notify(game, link.l10n.chess_notifyDeclined(p.declinerName)); return true; } bool _onInfo(String channelId, ChessGame? game, ChessInfoPacket p) { if (game != null && game.iAmInviter) return false; // We send these. - final inviter = game?.inviter; - if (inviter != null && - !bytesEqual(inviter.commitment, p.whiteCommitment) && - !bytesEqual(inviter.commitment, p.blackCommitment)) { - return false; // Not from this game's inviter. + if (game?.status == ChessGameStatus.finished) return false; + // Value 1 of the inviter's chain hashes to the inviter's commitment. + final step = hashChainStep(p.inviterValue); + final ChessSide inviterSide; + if (bytesEqual(step, p.whiteCommitment)) { + inviterSide = ChessSide.white; + } else if (bytesEqual(step, p.blackCommitment)) { + inviterSide = ChessSide.black; + } else { + return false; } - final white = ChessPlayer(name: p.whiteName, commitment: p.whiteCommitment); - final black = ChessPlayer(name: p.blackName, commitment: p.blackCommitment); + final inviterWhite = inviterSide == ChessSide.white; + final inviterCommitment = inviterWhite + ? p.whiteCommitment + : p.blackCommitment; + final accepterCommitment = inviterWhite + ? p.blackCommitment + : p.whiteCommitment; + final known = game?.inviter; + if (known != null) { + if (!bytesEqual(known.commitment, inviterCommitment)) return false; + // Colours follow from the invite; don't take the packet's word. + final expected = _inviterIsWhite( + game!.colourPreference, + inviterCommitment, + accepterCommitment, + ); + if (expected != inviterWhite) return false; + } + final inviter = + known ?? + ChessPlayer.inviter( + name: inviterWhite ? p.whiteName : p.blackName, + commitment: inviterCommitment, + ); + final accepter = ChessPlayer( + name: inviterWhite ? p.blackName : p.whiteName, + commitment: accepterCommitment, + ); + final white = inviterWhite ? inviter : accepter; + final black = inviterWhite ? accepter : inviter; + final startedAtMs = p.startedAtUnix * 1000; if (game == null) { + // We never heard the invite, so nothing ties these players to it. final created = ChessGame( channelId: channelId, gameId: p.gameId, @@ -451,8 +589,10 @@ class ChessService extends ChangeNotifier { deadline: p.deadline, white: white, black: black, + playersConfirmed: false, + inviterInfoValue: p.inviterValue, createdAtMs: _now, - startedAtMs: p.startedAtUnix * 1000, + startedAtMs: startedAtMs, hasPosition: p.ply == 0, ply: p.ply, sanMoves: List.filled(p.ply, null, growable: true), @@ -461,45 +601,85 @@ class ChessService extends ChangeNotifier { return true; } + final mine = game.myChain?.commitment; + final listsMe = mine != null && bytesEqual(mine, accepterCommitment); switch (game.status) { case ChessGameStatus.invite: - _start(game, white: white, black: black, mySide: null); - game.startedAtMs = p.startedAtUnix * 1000; - return true; case ChessGameStatus.starting: - final mine = game.myChain?.commitment; - ChessSide? side; - if (mine != null && bytesEqual(mine, p.whiteCommitment)) { - side = ChessSide.white; - } else if (mine != null && bytesEqual(mine, p.blackCommitment)) { - side = ChessSide.black; + final accepted = game.mySeedHex != null; + _start( + game, + white: white, + black: black, + mySide: listsMe ? inviterSide.other : null, + ); + game + ..startedAtMs = startedAtMs + ..inviterInfoValue = p.inviterValue; + if (!listsMe && p.ply > 0) { + // Watching a game already under way: the board comes with the + // next move. + game + ..ply = p.ply + ..hasPosition = false + ..sanMoves = List.filled(p.ply, null, growable: true); } - if (side == null) { - // Someone else's accept won. Keep watching the game. - game.mySeedHex = null; - _start(game, white: white, black: black, mySide: null); + if (listsMe && inviterSide == ChessSide.black) { + _notify(game, link.l10n.chess_notifyGameStartedYourMove); + } else if (accepted && !listsMe) { + // Someone else's accept won. Keep watching, and keep our chain in + // case a later game info lists us after all. _notify(game, link.l10n.chess_notifyTaken); - } else { - _start(game, white: white, black: black, mySide: side); - if (side == ChessSide.white) { - _notify(game, link.l10n.chess_notifyGameStartedYourMove); - } } - game.startedAtMs = p.startedAtUnix * 1000; return true; case ChessGameStatus.active: - if (game.hasPlayers) return false; + if (game.mySide == null && listsMe) { + // An earlier game info listed someone else; this one lists us. + // Whoever sent it, it puts us against the real inviter. + game + ..white = white + ..black = black + ..mySide = inviterSide.other + ..playersConfirmed = true + ..inviterInfoValue = p.inviterValue + ..lastActivityMs = _now; + return true; + } + if (game.hasPlayers) return false; // First heard wins. + // Followed from a move. Our inviter record, if any, must stay on + // the side we saw it move for. + for (final side in ChessSide.values) { + final seen = game.playerOf(side); + if (seen != null && identical(seen, known) && side != inviterSide) { + return false; + } + } game ..white = white ..black = black - ..startedAtMs ??= p.startedAtUnix * 1000 + ..playersConfirmed = known != null + ..deadline = p.deadline + ..inviterInfoValue = p.inviterValue + ..startedAtMs ??= startedAtMs ..lastActivityMs = _now; + _useLastMoveValue(game); return true; case ChessGameStatus.finished: return false; } } + /// Uses up the chain value of the move we followed before we knew the + /// players. + void _useLastMoveValue(ChessGame game) { + final raw = game.lastMovePacket; + final move = raw == null ? null : ChessPacket.decode(raw); + if (move is! ChessMovePacket) return; + final player = game.playerOf(ChessSide.moverOfPly(move.ply)); + final index = player?.freshIndex(move.chainValue); + if (index != null) player!.use(index); + } + void _start( ChessGame game, { required ChessPlayer white, @@ -522,13 +702,12 @@ class ChessService extends ChangeNotifier { ChessMovePacket p, Uint8List raw, ) { + final ply = p.ply; + if (ply < 1) return false; + final mover = ChessSide.moverOfPly(ply); if (game == null) { // A game we never heard start: follow it from this position. - final fullPly = p.ply == 0 ? 256 : p.ply; - final fen = ChessPositionCodec.decodeToFen( - p.position, - fullMoveNumber: fullPly ~/ 2 + 1, - ); + final fen = _decodePosition(p); if (fen == null || !isValidFen(fen)) return false; final created = ChessGame( channelId: channelId, @@ -536,37 +715,44 @@ class ChessService extends ChangeNotifier { status: ChessGameStatus.active, deadline: ChessDeadline.none, createdAtMs: _now, - )..adoptPosition(fen, fullPly); + )..adoptPosition(fen, ply); created ..lastMovePacket = raw ..lastMoveAtMs = _now; _games[created.key] = created; return true; } - if (game.status == ChessGameStatus.invite) { - // We missed the accept and confirmation; follow from here. - game - ..status = ChessGameStatus.active - ..startedAtMs = _now; + switch (game.status) { + case ChessGameStatus.finished: + case ChessGameStatus.starting: // Wait for the inviter's confirmation. + return false; + case ChessGameStatus.invite: + return _onMoveBeforeStart(game, p, raw); + case ChessGameStatus.active: + break; } - if (game.status != ChessGameStatus.active) return false; - - final fullPly = _unwrapPly(game.ply, p.ply); - if (fullPly <= game.ply) return false; // Old or duplicate. - final mover = ChessSide.moverOfPly(fullPly); if (game.mySide == mover) return false; // Our own move echoed. + if (game.isPlayer && ply < game.ply) { + // The opponent is behind (our reply got lost); they need our move. + _scheduleAnswer(game, info: false, latestMove: true); + } final player = game.playerOf(mover); - if (player != null && !player.owns(p.chainValue)) return false; + int? index; + if (player != null) { + index = player.freshIndex(p.chainValue); + if (index == null) return false; // Forged, replayed or already used. + } + if (ply < game.ply || (ply == game.ply && game.hasPosition)) { + // A move we have, sent again with a new value: just use the value up. + if (index != null) player!.use(index); + return index != null; + } - final fen = ChessPositionCodec.decodeToFen( - p.position, - fullMoveNumber: fullPly ~/ 2 + 1, - ); + final fen = _decodePosition(p); if (fen == null) return false; - var applied = false; - if (fullPly == game.ply + 1 && game.hasPosition) { + if (ply == game.ply + 1 && game.hasPosition) { final legal = game.legalUci(); if (p.moveIndex < legal.length) { final probe = ChessGame.fromJson(game.toJson())!; @@ -576,21 +762,24 @@ class ChessService extends ChangeNotifier { applied = true; } } - if (!applied && game.isPlayer) return false; // Does not match our board. + // Does not match our board. The value stays unused, so the real move + // can still be accepted if this one was forged. + if (!applied && game.isPlayer) return false; } else if (game.isPlayer && game.hasPosition) { return false; // Players cannot skip moves. } if (!applied) { if (!isValidFen(fen)) return false; - game.adoptPosition(fen, fullPly); + game.adoptPosition(fen, ply); } - player?.verifyAndAdvance(p.chainValue); + if (index != null) player!.use(index); game ..lastMovePacket = raw ..lastMoveAtMs = _now ..lastActivityMs = _now; if (game.isPlayer) { + game.moveUnconfirmed = false; // Their move answers ours. final opponent = game.nameOf(mover) ?? ''; final san = game.sanMoves.isEmpty ? null : game.sanMoves.last; if (game.status == ChessGameStatus.finished) { @@ -602,58 +791,108 @@ class ChessService extends ChangeNotifier { return true; } + /// A move for an invite we watched but never saw start. Only the + /// inviter's chain can prove the game began; the other player stays + /// unknown until the game info. + bool _onMoveBeforeStart(ChessGame game, ChessMovePacket p, Uint8List raw) { + if (game.isMine) return false; // Ours, or waiting for our confirmation. + final inviter = game.inviter; + final index = inviter?.freshIndex(p.chainValue); + if (index == null) return false; + final fen = _decodePosition(p); + if (fen == null || !isValidFen(fen)) return false; + inviter!.use(index); + if (ChessSide.moverOfPly(p.ply) == ChessSide.white) { + game.white = inviter; + } else { + game.black = inviter; + } + game + ..status = ChessGameStatus.active + ..startedAtMs = _now + ..adoptPosition(fen, p.ply); + game + ..lastMovePacket = raw + ..lastMoveAtMs = _now + ..lastActivityMs = _now; + return true; + } + + static String? _decodePosition(ChessMovePacket p) => + ChessPositionCodec.decodeToFen( + p.position, + fullMoveNumber: p.ply ~/ 2 + 1, + ); + bool _onAction(ChessGame? game, ChessActionPacket p) { if (game == null) return false; if (p.kind == ChessPacketKind.cancel) { - final inviter = game.inviter; - if (game.status != ChessGameStatus.invite || inviter == null) { + if (game.iAmInviter) return false; + if (game.status != ChessGameStatus.invite && + game.status != ChessGameStatus.starting) { return false; } - if (!inviter.verifyAndAdvance(p.chainValue)) return false; + final inviter = game.inviter; + final index = inviter?.freshIndex(p.chainValue); + if (index == null) return false; + inviter!.use(index); game ..finish(ChessEndReason.cancelled) ..lastActivityMs = _now; return true; } if (game.status != ChessGameStatus.active) return false; - final side = game.sideOwning(p.chainValue); - if (side == null || side == game.mySide) return false; - if (!game.playerOf(side)!.verifyAndAdvance(p.chainValue)) return false; + final found = game.freshSide(p.chainValue); + if (found == null) return false; + final (side, index) = found; + if (side == game.mySide) return false; + // The value is genuine and now used up, whether or not the action + // applies to the game as we see it. + game.playerOf(side)!.use(index); + game.lastActivityMs = _now; + final current = p.ply == game.ply; final name = game.nameOf(side) ?? ''; switch (p.kind) { case ChessPacketKind.resign: game.finish(ChessEndReason.resignation, winner: side.other); if (game.isPlayer) _notify(game, link.l10n.chess_notifyResigned(name)); case ChessPacketKind.drawOffer: + if (!current) break; game.drawOfferedBy = side; if (game.isPlayer) { _notify(game, link.l10n.chess_notifyDrawOffered(name)); } case ChessPacketKind.drawAccept: + if (!current || game.drawOfferedBy != side.other) break; game.finish(ChessEndReason.drawAgreed); if (game.isPlayer) { _notify(game, link.l10n.chess_notifyDrawAccepted(name)); } case ChessPacketKind.timeoutClaim: - // Only the side waiting for a move can claim. - if (game.hasPosition && game.sideToMove == side) return false; + if (!current || !_deadlinePassed(game, side)) break; game.finish(ChessEndReason.timeout, winner: side); if (game.isPlayer) _notify(game, link.l10n.chess_notifyTimeout(name)); default: - return false; + break; } - game.lastActivityMs = _now; return true; } + /// Whether [claimer]'s opponent is to move and the deadline has passed + /// here since the last move. No grace: the claimer already waited it out, + /// and our clock may run behind theirs. + bool _deadlinePassed(ChessGame game, ChessSide claimer) { + final d = game.deadline.duration; + if (d == null || game.sideToMove == claimer) return false; + return _now - game.lastMoveAtMs >= d.inMilliseconds; + } + bool _onRequest(ChessGame? game, ChessRequestPacket p) { if (game == null || !game.isPlayer) return false; - if (game.status == ChessGameStatus.starting) return false; - final behind = _unwrapPly(game.ply, p.ply) < game.ply; _scheduleAnswer( game, info: p.wantsInfo, - latestMove: p.wantsLatestMove && behind, + latestMove: p.wantsLatestMove && p.ply < game.ply, ); return false; } @@ -688,9 +927,12 @@ 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 (latestMove && move != null && link.canSend) { - await link.send(game.channelId, move); + if (_latestMoveIsMine(game)) { + await _resendLatestMove(game); + } else if (move != null) { + await _sendRaw(game, move); } }); } @@ -698,16 +940,18 @@ class ChessService extends ChangeNotifier { Future _sendInfo(ChessGame game) async { final white = game.white; final black = game.black; - if (white == null || black == null) return; + final value = game.inviterInfoValue; + if (white == null || black == null || value == null) return; await _send( game, ChessInfoPacket( gameId: game.gameId, - ply: game.ply & 0xFF, + ply: game.ply, startedAtUnix: (game.startedAtMs ?? game.createdAtMs) ~/ 1000, deadline: game.deadline, whiteCommitment: white.commitment, blackCommitment: black.commitment, + inviterValue: value, whiteName: white.name, blackName: black.name, ), @@ -716,13 +960,6 @@ class ChessService extends ChangeNotifier { // ---- helpers --------------------------------------------------------------- - /// The full ply nearest [known] whose low byte is [wire]. - static int _unwrapPly(int known, int wire) { - var delta = (wire - known) & 0xFF; - if (delta >= 128) delta -= 256; - return known + delta; - } - /// Colour rule for invites: a fixed preference wins, "random" uses bit 0 /// of SHA-256(inviter commitment ‖ accepter commitment). static bool _inviterIsWhite( @@ -740,16 +977,17 @@ class ChessService extends ChangeNotifier { } } - bool _isMe(String? name) => - name != null && - link.selfName.isNotEmpty && - _sameName(name, link.selfName); + /// Whether [name] is our advert name (case and spacing aside). + bool isSelf(String name) => + link.selfName.isNotEmpty && _sameName(name, link.selfName); + + bool _isMe(String? name) => name != null && isSelf(name); static bool _sameName(String a, String b) => a.trim().toLowerCase() == b.trim().toLowerCase(); void _notify(ChessGame game, String text) { - if (game.key == _viewingKey) return; + if (game.key == _viewingKey && _isForeground()) return; link.notify(game.channelId, text); } @@ -792,9 +1030,9 @@ class ChessService extends ChangeNotifier { if (_games.length > maxStoredGames) { final byAge = _games.values.toList() ..sort((a, b) { - // Our open games last. - final ao = a.isOpen && a.isPlayer ? 1 : 0; - final bo = b.isOpen && b.isPlayer ? 1 : 0; + // Our open games (including our invites) last. + final ao = a.isOpen && a.isMine ? 1 : 0; + final bo = b.isOpen && b.isMine ? 1 : 0; if (ao != bo) return ao - bo; return a.lastActivityMs.compareTo(b.lastActivityMs); }); diff --git a/lib/games/chess/ui/chess_board.dart b/lib/games/chess/ui/chess_board.dart index 507ef77a..3ac5ce9a 100644 --- a/lib/games/chess/ui/chess_board.dart +++ b/lib/games/chess/ui/chess_board.dart @@ -197,6 +197,22 @@ class _ChessBoardViewState extends State { ); } + /// Screen reader label of an occupied square, e.g. "e4: Pawn, white". + static String _pieceLabel(BuildContext context, String square, String piece) { + final l10n = context.l10n; + final name = switch (piece.toLowerCase()) { + 'k' => l10n.chess_pieceKing, + 'q' => l10n.chess_pieceQueen, + 'r' => l10n.chess_pieceRook, + 'b' => l10n.chess_pieceBishop, + 'n' => l10n.chess_pieceKnight, + _ => l10n.chess_piecePawn, + }; + return piece == piece.toUpperCase() + ? l10n.chess_squareWhitePiece(square, name) + : l10n.chess_squareBlackPiece(square, name); + } + Widget _square( BuildContext context, { required ColorScheme scheme, @@ -225,7 +241,7 @@ class _ChessBoardViewState extends State { behavior: HitTestBehavior.opaque, onTap: () => _onTap(square), child: Semantics( - label: piece == null ? square : '$square $piece', + label: piece == null ? square : _pieceLabel(context, square, piece), button: isTarget || (_interactive && piece != null), selected: isSelected, child: SizedBox( diff --git a/lib/games/chess/ui/chess_game_screen.dart b/lib/games/chess/ui/chess_game_screen.dart index b3c04f9a..c99c02d0 100644 --- a/lib/games/chess/ui/chess_game_screen.dart +++ b/lib/games/chess/ui/chess_game_screen.dart @@ -267,7 +267,12 @@ class _StatusCard extends StatelessWidget { ), ); } - if (!game.hasPlayers) lines.add(l10n.chess_statusUnverified); + if (game.moveUnconfirmed) lines.add(l10n.chess_statusMoveUnconfirmed); + if (!game.hasPlayers) { + lines.add(l10n.chess_statusUnverified); + } else if (!game.playersConfirmed) { + lines.add(l10n.chess_statusPlayersUnchecked); + } } return MeshCard( child: Column( diff --git a/lib/games/chess/ui/chess_games_sheet.dart b/lib/games/chess/ui/chess_games_sheet.dart index 46752793..5c25846d 100644 --- a/lib/games/chess/ui/chess_games_sheet.dart +++ b/lib/games/chess/ui/chess_games_sheet.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../../helpers/snack_bar_builder.dart'; +import '../../../l10n/app_localizations.dart'; import '../../../l10n/l10n.dart'; import '../../../models/channel.dart'; import '../../../utils/radio_guard.dart'; @@ -96,8 +97,7 @@ class _ChessGamesSheetBody extends StatelessWidget { (g) => g.status == ChessGameStatus.invite && !g.iAmInviter && - (g.targetName == null || - _sameName(g.targetName!, service.selfName)), + service.isListed(g), ) .toList(); final live = games @@ -170,9 +170,6 @@ class _ChessGamesSheetBody extends StatelessWidget { } } -bool _sameName(String a, String b) => - a.trim().toLowerCase() == b.trim().toLowerCase(); - class _ActionCard extends StatelessWidget { final IconData icon; final String title; @@ -251,7 +248,9 @@ class _GameCard extends StatelessWidget { : l10n.chess_statusToMove(toMove); subtitle = l10n.chess_rowMoveTurn((game.ply ~/ 2) + 1, turn); case ChessGameStatus.finished: - title = l10n.chessPlayers(game); + title = game.hasPlayers || game.inviter == null + ? l10n.chessPlayers(game) + : _inviteTitle(l10n, service); subtitle = l10n.chessResult(game); } return MeshCard( @@ -302,6 +301,21 @@ class _GameCard extends StatelessWidget { ); } + /// An invite that never became a game: who invited whom. + String _inviteTitle(AppLocalizations l10n, ChessService service) { + final target = game.targetName; + if (game.iAmInviter) { + return target == null + ? l10n.chess_rowYourOpenInvite + : l10n.chess_rowYourChallenge(target); + } + final inviter = game.inviter?.name ?? l10n.chess_unknownPlayer; + if (target == null) return l10n.chess_rowOpenInvite(inviter); + return service.isSelf(target) + ? l10n.chess_rowChallengedYou(inviter) + : l10n.chess_rowChallenge(inviter, target); + } + Future _confirmCancel( BuildContext context, ChessService service, diff --git a/lib/games/game_packet.dart b/lib/games/game_packet.dart index fa19b221..6cf23cbe 100644 --- a/lib/games/game_packet.dart +++ b/lib/games/game_packet.dart @@ -22,10 +22,10 @@ abstract final class GameApp { static const int chess = 1; } -/// The 4-byte header every game packet starts with: -/// `[app << 4 | kind][gameId LE16][ply mod 256]`. +/// The 5-byte header every game packet starts with: +/// `[app << 4 | kind][gameId LE16][ply LE16]`. class GamePacketHeader { - static const int length = 4; + static const int length = 5; final int app; final int kind; @@ -44,7 +44,8 @@ class GamePacketHeader { ..addByte(((app & 0x0F) << 4) | (kind & 0x0F)) ..addByte(gameId & 0xFF) ..addByte((gameId >> 8) & 0xFF) - ..addByte(ply & 0xFF); + ..addByte(ply & 0xFF) + ..addByte((ply >> 8) & 0xFF); } static GamePacketHeader? parse(Uint8List bytes) { @@ -53,7 +54,7 @@ class GamePacketHeader { app: bytes[0] >> 4, kind: bytes[0] & 0x0F, gameId: bytes[1] | (bytes[2] << 8), - ply: bytes[3], + ply: bytes[3] | (bytes[4] << 8), ); } diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index b35483e1..df9b3866 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3908,5 +3908,12 @@ "chess_notifyResigned": "{name} се предаде. Вие печелите.", "chess_notifyDrawOffered": "{name} предлага реми", "chess_notifyDrawAccepted": "{name} прие реми", - "chess_notifyTimeout": "{name} поиска победа по време" + "chess_notifyTimeout": "{name} поиска победа по време", + "chess_rowChallenge": "{inviter} предизвиква {target}", + "chess_statusPlayersUnchecked": "Играчите не са потвърдени: този телефон не е чул поканата.", + "chess_statusMoveUnconfirmed": "Ходът ви може да не е изпратен. Докоснете „Поискай обновяване“, за да го изпратите отново.", + "chess_pieceKing": "Цар", + "chess_piecePawn": "Пешка", + "chess_squareWhitePiece": "{square}: {piece}, бели", + "chess_squareBlackPiece": "{square}: {piece}, черни" } diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index 3d365f65..64555f50 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -4521,5 +4521,12 @@ "chess_notifyResigned": "Hráč {name} se vzdal. Vyhráváte.", "chess_notifyDrawOffered": "{name} nabízí remízu", "chess_notifyDrawAccepted": "Hráč {name} přijal remízu", - "chess_notifyTimeout": "Hráč {name} uplatnil výhru na čas" + "chess_notifyTimeout": "Hráč {name} uplatnil výhru na čas", + "chess_rowChallenge": "{inviter} vyzývá hráče {target}", + "chess_statusPlayersUnchecked": "Hráči nepotvrzeni: tento telefon výzvu neslyšel.", + "chess_statusMoveUnconfirmed": "Váš tah možná neodešel. Klepnutím na „Vyžádat aktualizaci“ ho odešlete znovu.", + "chess_pieceKing": "Král", + "chess_piecePawn": "Pěšec", + "chess_squareWhitePiece": "{square}: {piece}, bílá", + "chess_squareBlackPiece": "{square}: {piece}, černá" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 88cf5844..88dcc378 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4043,5 +4043,12 @@ "chess_notifyResigned": "{name} hat aufgegeben. Sie gewinnen.", "chess_notifyDrawOffered": "{name} bietet Remis an", "chess_notifyDrawAccepted": "{name} hat das Remis angenommen", - "chess_notifyTimeout": "{name} hat den Sieg wegen Zeit beansprucht" + "chess_notifyTimeout": "{name} hat den Sieg wegen Zeit beansprucht", + "chess_rowChallenge": "{inviter} hat {target} herausgefordert", + "chess_statusPlayersUnchecked": "Spieler nicht bestätigt: Dieses Telefon hat die Einladung nicht gehört.", + "chess_statusMoveUnconfirmed": "Ihr Zug wurde möglicherweise nicht gesendet. Tippen Sie auf „Aktualisierung anfordern“, um ihn erneut zu senden.", + "chess_pieceKing": "König", + "chess_piecePawn": "Bauer", + "chess_squareWhitePiece": "{square}: {piece}, weiß", + "chess_squareBlackPiece": "{square}: {piece}, schwarz" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 566bd4dd..3bba7bc2 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4498,6 +4498,17 @@ } }, "chess_unknownPlayer": "Unknown", + "chess_rowChallenge": "{inviter} challenged {target}", + "@chess_rowChallenge": { + "placeholders": { + "inviter": { + "type": "String" + }, + "target": { + "type": "String" + } + } + }, "chess_rowYourOpenInvite": "Your open invite", "chess_rowYourChallenge": "You challenged {name}", "@chess_rowYourChallenge": { @@ -4627,6 +4638,8 @@ }, "chess_statusUnknownPosition": "The board appears with the next move.", "chess_statusUnverified": "Players not confirmed yet. Ask for an update to check them.", + "chess_statusPlayersUnchecked": "Players not confirmed: this phone didn't hear the invite.", + "chess_statusMoveUnconfirmed": "Your move may not have gone out. Tap Ask for update to send it again.", "chess_actionResign": "Resign", "chess_actionOfferDraw": "Offer draw", "chess_actionAcceptDraw": "Accept draw", @@ -4643,6 +4656,30 @@ "chess_pieceRook": "Rook", "chess_pieceBishop": "Bishop", "chess_pieceKnight": "Knight", + "chess_pieceKing": "King", + "chess_piecePawn": "Pawn", + "chess_squareWhitePiece": "{square}: {piece}, white", + "@chess_squareWhitePiece": { + "placeholders": { + "square": { + "type": "String" + }, + "piece": { + "type": "String" + } + } + }, + "chess_squareBlackPiece": "{square}: {piece}, black", + "@chess_squareBlackPiece": { + "placeholders": { + "square": { + "type": "String" + }, + "piece": { + "type": "String" + } + } + }, "chess_resultDraw": "Draw", "chess_resultWon": "{name} won", "@chess_resultWon": { diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index b0569177..40d81bce 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4094,5 +4094,12 @@ "chess_notifyResigned": "{name} abandonó. Ganas tú.", "chess_notifyDrawOffered": "{name} ofrece tablas", "chess_notifyDrawAccepted": "{name} ha aceptado las tablas", - "chess_notifyTimeout": "{name} reclamó la victoria por tiempo" + "chess_notifyTimeout": "{name} reclamó la victoria por tiempo", + "chess_rowChallenge": "{inviter} ha retado a {target}", + "chess_statusPlayersUnchecked": "Jugadores sin confirmar: este teléfono no oyó la invitación.", + "chess_statusMoveUnconfirmed": "Es posible que tu jugada no se haya enviado. Toca «Pedir actualización» para enviarla de nuevo.", + "chess_pieceKing": "Rey", + "chess_piecePawn": "Peón", + "chess_squareWhitePiece": "{square}: {piece}, blancas", + "chess_squareBlackPiece": "{square}: {piece}, negras" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index c0074bc9..8d3b89b6 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4042,5 +4042,12 @@ "chess_notifyResigned": "{name} a abandonné. Vous gagnez.", "chess_notifyDrawOffered": "{name} propose la nulle", "chess_notifyDrawAccepted": "{name} a accepté la nulle", - "chess_notifyTimeout": "{name} a réclamé la victoire au temps" + "chess_notifyTimeout": "{name} a réclamé la victoire au temps", + "chess_rowChallenge": "{inviter} a défié {target}", + "chess_statusPlayersUnchecked": "Joueurs non confirmés : ce téléphone n'a pas entendu l'invitation.", + "chess_statusMoveUnconfirmed": "Votre coup n'est peut-être pas parti. Appuyez sur « Demander une mise à jour » pour le renvoyer.", + "chess_pieceKing": "Roi", + "chess_piecePawn": "Pion", + "chess_squareWhitePiece": "{square} : {piece}, blancs", + "chess_squareBlackPiece": "{square} : {piece}, noirs" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 64e2f636..5a8a2a35 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3999,5 +3999,12 @@ "chess_notifyResigned": "{name} feladta. Te nyertél.", "chess_notifyDrawOffered": "{name} döntetlent ajánl", "chess_notifyDrawAccepted": "{name} elfogadta a döntetlent", - "chess_notifyTimeout": "{name} időtúllépés miatt nyerést követelt" + "chess_notifyTimeout": "{name} időtúllépés miatt nyerést követelt", + "chess_rowChallenge": "{inviter} kihívta: {target}", + "chess_statusPlayersUnchecked": "A játékosok nincsenek megerősítve: ez a telefon nem hallotta a felkérést.", + "chess_statusMoveUnconfirmed": "Előfordulhat, hogy a lépésed nem ment el. Koppints a „Frissítés kérése” gombra az újraküldéshez.", + "chess_pieceKing": "Király", + "chess_piecePawn": "Gyalog", + "chess_squareWhitePiece": "{square}: {piece}, világos", + "chess_squareBlackPiece": "{square}: {piece}, sötét" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 5492e8ce..6d0f1554 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -4042,5 +4042,12 @@ "chess_notifyResigned": "{name} ha abbandonato. Hai vinto.", "chess_notifyDrawOffered": "{name} offre la patta", "chess_notifyDrawAccepted": "{name} ha accettato la patta", - "chess_notifyTimeout": "{name} ha rivendicato la vittoria a tempo" + "chess_notifyTimeout": "{name} ha rivendicato la vittoria a tempo", + "chess_rowChallenge": "{inviter} ha sfidato {target}", + "chess_statusPlayersUnchecked": "Giocatori non confermati: questo telefono non ha sentito l'invito.", + "chess_statusMoveUnconfirmed": "La tua mossa potrebbe non essere partita. Tocca «Chiedi aggiornamento» per inviarla di nuovo.", + "chess_pieceKing": "Re", + "chess_piecePawn": "Pedone", + "chess_squareWhitePiece": "{square}: {piece}, bianco", + "chess_squareBlackPiece": "{square}: {piece}, nero" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 10dfc490..cf6dfe38 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -4248,5 +4248,12 @@ "chess_notifyResigned": "{name} が投了しました。あなたの勝ちです。", "chess_notifyDrawOffered": "{name} が引き分けを提案しています", "chess_notifyDrawAccepted": "{name} が引き分けを承諾しました", - "chess_notifyTimeout": "{name} が時間切れによる勝ちを申請しました" + "chess_notifyTimeout": "{name} が時間切れによる勝ちを申請しました", + "chess_rowChallenge": "{inviter} が {target} に挑戦しました", + "chess_statusPlayersUnchecked": "対局者の確認ができていません: この端末は募集を受信していません。", + "chess_statusMoveUnconfirmed": "あなたの手が送信されていない可能性があります。「更新を依頼」をタップして再送してください。", + "chess_pieceKing": "キング", + "chess_piecePawn": "ポーン", + "chess_squareWhitePiece": "{square}: 白の{piece}", + "chess_squareBlackPiece": "{square}: 黒の{piece}" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 656cd6eb..22eb258a 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3384,7 +3384,7 @@ "translation_downloadProgressBytes": "{fileName}: {current} MB", "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", "translation_downloadedModelDetails": "{size} MB • {source}", - "repeater_radioDisconnected": "라디오 연결 끊김", + "repeater_radioDisconnected": "무전기 연결 끊김", "repeater_radioDisconnectedHint": "명령을 보내거나 새로고침 또는 변경 사항을 저장하려면 무전기에 다시 연결하세요.", "repeater_cliSend": "명령 보내기", "repeater_cliCopyTranscript": "기록 복사", @@ -4111,7 +4111,7 @@ "appBar_offlineSubtitle": "오프라인 · {name}", "appBar_offline": "오프라인", "appBar_reconnecting": "다시 연결 중…", - "connectSheet_title": "라디오 연결", + "connectSheet_title": "무전기 연결", "connectSheet_reconnect": "{name}에 다시 연결", "connectSheet_chooseRadio": "무전기 선택", "connectSheet_chooseRadioSubtitle": "Bluetooth, USB 또는 TCP", @@ -4248,5 +4248,12 @@ "chess_notifyResigned": "{name}님이 기권했습니다. 승리했습니다.", "chess_notifyDrawOffered": "{name}님이 무승부를 제안했습니다", "chess_notifyDrawAccepted": "{name}님이 무승부를 수락했습니다", - "chess_notifyTimeout": "{name}님이 시간 초과 승리를 요청했습니다" + "chess_notifyTimeout": "{name}님이 시간 초과 승리를 요청했습니다", + "chess_rowChallenge": "{inviter}님이 {target}님에게 도전했습니다", + "chess_statusPlayersUnchecked": "플레이어 미확인: 이 휴대폰이 초대를 수신하지 못했습니다.", + "chess_statusMoveUnconfirmed": "내 수가 전송되지 않았을 수 있습니다. \"업데이트 요청\"을 눌러 다시 보내세요.", + "chess_pieceKing": "킹", + "chess_piecePawn": "폰", + "chess_squareWhitePiece": "{square}: 백 {piece}", + "chess_squareBlackPiece": "{square}: 흑 {piece}" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index bd9156cd..1b7b8d34 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -13084,6 +13084,12 @@ abstract class AppLocalizations { /// **'Unknown'** String get chess_unknownPlayer; + /// No description provided for @chess_rowChallenge. + /// + /// In en, this message translates to: + /// **'{inviter} challenged {target}'** + String chess_rowChallenge(String inviter, String target); + /// No description provided for @chess_rowYourOpenInvite. /// /// In en, this message translates to: @@ -13336,6 +13342,18 @@ abstract class AppLocalizations { /// **'Players not confirmed yet. Ask for an update to check them.'** String get chess_statusUnverified; + /// No description provided for @chess_statusPlayersUnchecked. + /// + /// In en, this message translates to: + /// **'Players not confirmed: this phone didn\'t hear the invite.'** + String get chess_statusPlayersUnchecked; + + /// No description provided for @chess_statusMoveUnconfirmed. + /// + /// In en, this message translates to: + /// **'Your move may not have gone out. Tap Ask for update to send it again.'** + String get chess_statusMoveUnconfirmed; + /// No description provided for @chess_actionResign. /// /// In en, this message translates to: @@ -13432,6 +13450,30 @@ abstract class AppLocalizations { /// **'Knight'** String get chess_pieceKnight; + /// No description provided for @chess_pieceKing. + /// + /// In en, this message translates to: + /// **'King'** + String get chess_pieceKing; + + /// No description provided for @chess_piecePawn. + /// + /// In en, this message translates to: + /// **'Pawn'** + String get chess_piecePawn; + + /// No description provided for @chess_squareWhitePiece. + /// + /// In en, this message translates to: + /// **'{square}: {piece}, white'** + String chess_squareWhitePiece(String square, String piece); + + /// No description provided for @chess_squareBlackPiece. + /// + /// In en, this message translates to: + /// **'{square}: {piece}, black'** + String chess_squareBlackPiece(String square, String piece); + /// No description provided for @chess_resultDraw. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index f2807c65..a4671af6 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -7850,6 +7850,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chess_unknownPlayer => 'Неизвестен'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter предизвиква $target'; + } + @override String get chess_rowYourOpenInvite => 'Вашата отворена покана'; @@ -8003,6 +8008,14 @@ class AppLocalizationsBg extends AppLocalizations { String get chess_statusUnverified => 'Играчите още не са потвърдени. Поискайте обновяване, за да ги проверите.'; + @override + String get chess_statusPlayersUnchecked => + 'Играчите не са потвърдени: този телефон не е чул поканата.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Ходът ви може да не е изпратен. Докоснете „Поискай обновяване“, за да го изпратите отново.'; + @override String get chess_actionResign => 'Предай се'; @@ -8052,6 +8065,22 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chess_pieceKnight => 'Кон'; + @override + String get chess_pieceKing => 'Цар'; + + @override + String get chess_piecePawn => 'Пешка'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, бели'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, черни'; + } + @override String get chess_resultDraw => 'Реми'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 045a1bfb..34b464ac 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -7822,6 +7822,11 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chess_unknownPlayer => 'Neznámý'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter vyzývá hráče $target'; + } + @override String get chess_rowYourOpenInvite => 'Vaše otevřená výzva'; @@ -7975,6 +7980,14 @@ class AppLocalizationsCs extends AppLocalizations { String get chess_statusUnverified => 'Hráči zatím nejsou potvrzeni. Vyžádejte si aktualizaci a ověřte je.'; + @override + String get chess_statusPlayersUnchecked => + 'Hráči nepotvrzeni: tento telefon výzvu neslyšel.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Váš tah možná neodešel. Klepnutím na „Vyžádat aktualizaci“ ho odešlete znovu.'; + @override String get chess_actionResign => 'Vzdát se'; @@ -8024,6 +8037,22 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chess_pieceKnight => 'Jezdec'; + @override + String get chess_pieceKing => 'Král'; + + @override + String get chess_piecePawn => 'Pěšec'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, bílá'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, černá'; + } + @override String get chess_resultDraw => 'Remíza'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index e79bb619..50c96b20 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -7865,6 +7865,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chess_unknownPlayer => 'Unbekannt'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter hat $target herausgefordert'; + } + @override String get chess_rowYourOpenInvite => 'Ihre offene Einladung'; @@ -8019,6 +8024,14 @@ class AppLocalizationsDe extends AppLocalizations { String get chess_statusUnverified => 'Spieler noch nicht bestätigt. Aktualisierung anfordern, um sie zu prüfen.'; + @override + String get chess_statusPlayersUnchecked => + 'Spieler nicht bestätigt: Dieses Telefon hat die Einladung nicht gehört.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Ihr Zug wurde möglicherweise nicht gesendet. Tippen Sie auf „Aktualisierung anfordern“, um ihn erneut zu senden.'; + @override String get chess_actionResign => 'Aufgeben'; @@ -8068,6 +8081,22 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chess_pieceKnight => 'Springer'; + @override + String get chess_pieceKing => 'König'; + + @override + String get chess_piecePawn => 'Bauer'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, weiß'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, schwarz'; + } + @override String get chess_resultDraw => 'Remis'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 8f974e84..863143ab 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -7735,6 +7735,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chess_unknownPlayer => 'Unknown'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter challenged $target'; + } + @override String get chess_rowYourOpenInvite => 'Your open invite'; @@ -7888,6 +7893,14 @@ class AppLocalizationsEn extends AppLocalizations { String get chess_statusUnverified => 'Players not confirmed yet. Ask for an update to check them.'; + @override + String get chess_statusPlayersUnchecked => + 'Players not confirmed: this phone didn\'t hear the invite.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Your move may not have gone out. Tap Ask for update to send it again.'; + @override String get chess_actionResign => 'Resign'; @@ -7937,6 +7950,22 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chess_pieceKnight => 'Knight'; + @override + String get chess_pieceKing => 'King'; + + @override + String get chess_piecePawn => 'Pawn'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, white'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, black'; + } + @override String get chess_resultDraw => 'Draw'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 3874c388..cdf807dd 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -7843,6 +7843,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chess_unknownPlayer => 'Desconocido'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter ha retado a $target'; + } + @override String get chess_rowYourOpenInvite => 'Tu invitación abierta'; @@ -7997,6 +8002,14 @@ class AppLocalizationsEs extends AppLocalizations { String get chess_statusUnverified => 'Jugadores aún sin confirmar. Pide una actualización para comprobarlos.'; + @override + String get chess_statusPlayersUnchecked => + 'Jugadores sin confirmar: este teléfono no oyó la invitación.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Es posible que tu jugada no se haya enviado. Toca «Pedir actualización» para enviarla de nuevo.'; + @override String get chess_actionResign => 'Abandonar'; @@ -8046,6 +8059,22 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chess_pieceKnight => 'Caballo'; + @override + String get chess_pieceKing => 'Rey'; + + @override + String get chess_piecePawn => 'Peón'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, blancas'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, negras'; + } + @override String get chess_resultDraw => 'Tablas'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 90352f71..31ac4dae 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -7871,6 +7871,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chess_unknownPlayer => 'Inconnu'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter a défié $target'; + } + @override String get chess_rowYourOpenInvite => 'Votre invitation ouverte'; @@ -8025,6 +8030,14 @@ class AppLocalizationsFr extends AppLocalizations { String get chess_statusUnverified => 'Joueurs pas encore confirmés. Demandez une mise à jour pour les vérifier.'; + @override + String get chess_statusPlayersUnchecked => + 'Joueurs non confirmés : ce téléphone n\'a pas entendu l\'invitation.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Votre coup n\'est peut-être pas parti. Appuyez sur « Demander une mise à jour » pour le renvoyer.'; + @override String get chess_actionResign => 'Abandonner'; @@ -8074,6 +8087,22 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chess_pieceKnight => 'Cavalier'; + @override + String get chess_pieceKing => 'Roi'; + + @override + String get chess_piecePawn => 'Pion'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square : $piece, blancs'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square : $piece, noirs'; + } + @override String get chess_resultDraw => 'Nulle'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index b3fcd4e6..4ffc6af6 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -7834,6 +7834,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chess_unknownPlayer => 'Ismeretlen'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter kihívta: $target'; + } + @override String get chess_rowYourOpenInvite => 'Nyitott felkérésed'; @@ -7987,6 +7992,14 @@ class AppLocalizationsHu extends AppLocalizations { String get chess_statusUnverified => 'A játékosok még nincsenek megerősítve. Kérj frissítést az ellenőrzésükhöz.'; + @override + String get chess_statusPlayersUnchecked => + 'A játékosok nincsenek megerősítve: ez a telefon nem hallotta a felkérést.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Előfordulhat, hogy a lépésed nem ment el. Koppints a „Frissítés kérése” gombra az újraküldéshez.'; + @override String get chess_actionResign => 'Feladás'; @@ -8036,6 +8049,22 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chess_pieceKnight => 'Huszár'; + @override + String get chess_pieceKing => 'Király'; + + @override + String get chess_piecePawn => 'Gyalog'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, világos'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, sötét'; + } + @override String get chess_resultDraw => 'Döntetlen'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index f310db09..d214d87d 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -7854,6 +7854,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chess_unknownPlayer => 'Sconosciuto'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter ha sfidato $target'; + } + @override String get chess_rowYourOpenInvite => 'Il tuo invito aperto'; @@ -8008,6 +8013,14 @@ class AppLocalizationsIt extends AppLocalizations { String get chess_statusUnverified => 'Giocatori non ancora confermati. Chiedi un aggiornamento per verificarli.'; + @override + String get chess_statusPlayersUnchecked => + 'Giocatori non confermati: questo telefono non ha sentito l\'invito.'; + + @override + String get chess_statusMoveUnconfirmed => + 'La tua mossa potrebbe non essere partita. Tocca «Chiedi aggiornamento» per inviarla di nuovo.'; + @override String get chess_actionResign => 'Abbandona'; @@ -8057,6 +8070,22 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chess_pieceKnight => 'Cavallo'; + @override + String get chess_pieceKing => 'Re'; + + @override + String get chess_piecePawn => 'Pedone'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, bianco'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, nero'; + } + @override String get chess_resultDraw => 'Patta'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index af523f49..ab090eba 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -7493,6 +7493,11 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chess_unknownPlayer => '不明'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter が $target に挑戦しました'; + } + @override String get chess_rowYourOpenInvite => 'あなたの募集'; @@ -7643,6 +7648,14 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chess_statusUnverified => '対局者がまだ確認されていません。更新を依頼して確認してください。'; + @override + String get chess_statusPlayersUnchecked => + '対局者の確認ができていません: この端末は募集を受信していません。'; + + @override + String get chess_statusMoveUnconfirmed => + 'あなたの手が送信されていない可能性があります。「更新を依頼」をタップして再送してください。'; + @override String get chess_actionResign => '投了'; @@ -7691,6 +7704,22 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chess_pieceKnight => 'ナイト'; + @override + String get chess_pieceKing => 'キング'; + + @override + String get chess_piecePawn => 'ポーン'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: 白の$piece'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: 黒の$piece'; + } + @override String get chess_resultDraw => '引き分け'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index d120e08d..11d8aed4 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -6849,7 +6849,7 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get repeater_radioDisconnected => '라디오 연결 끊김'; + String get repeater_radioDisconnected => '무전기 연결 끊김'; @override String get repeater_radioDisconnectedHint => @@ -7300,7 +7300,7 @@ class AppLocalizationsKo extends AppLocalizations { String get appBar_reconnecting => '다시 연결 중…'; @override - String get connectSheet_title => '라디오 연결'; + String get connectSheet_title => '무전기 연결'; @override String connectSheet_reconnect(String name) { @@ -7506,6 +7506,11 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chess_unknownPlayer => '알 수 없음'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter님이 $target님에게 도전했습니다'; + } + @override String get chess_rowYourOpenInvite => '내 공개 초대'; @@ -7656,6 +7661,13 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chess_statusUnverified => '플레이어가 아직 확인되지 않았습니다. 업데이트를 요청해 확인하세요.'; + @override + String get chess_statusPlayersUnchecked => '플레이어 미확인: 이 휴대폰이 초대를 수신하지 못했습니다.'; + + @override + String get chess_statusMoveUnconfirmed => + '내 수가 전송되지 않았을 수 있습니다. \"업데이트 요청\"을 눌러 다시 보내세요.'; + @override String get chess_actionResign => '기권'; @@ -7704,6 +7716,22 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chess_pieceKnight => '나이트'; + @override + String get chess_pieceKing => '킹'; + + @override + String get chess_piecePawn => '폰'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: 백 $piece'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: 흑 $piece'; + } + @override String get chess_resultDraw => '무승부'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 5f8a91bc..ee981bb3 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -7810,6 +7810,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chess_unknownPlayer => 'Onbekend'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter heeft $target uitgedaagd'; + } + @override String get chess_rowYourOpenInvite => 'Je open uitnodiging'; @@ -7964,6 +7969,14 @@ class AppLocalizationsNl extends AppLocalizations { String get chess_statusUnverified => 'Spelers nog niet bevestigd. Vraag om een update om ze te controleren.'; + @override + String get chess_statusPlayersUnchecked => + 'Spelers niet bevestigd: deze telefoon heeft de uitnodiging niet gehoord.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Je zet is mogelijk niet verstuurd. Tik op ‘Om update vragen’ om hem opnieuw te versturen.'; + @override String get chess_actionResign => 'Opgeven'; @@ -8013,6 +8026,22 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chess_pieceKnight => 'Paard'; + @override + String get chess_pieceKing => 'Koning'; + + @override + String get chess_piecePawn => 'Pion'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, wit'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, zwart'; + } + @override String get chess_resultDraw => 'Remise'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index ed5b0085..6d10a122 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -7887,6 +7887,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chess_unknownPlayer => 'Nieznany'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter rzuca wyzwanie: $target'; + } + @override String get chess_rowYourOpenInvite => 'Twoje otwarte zaproszenie'; @@ -8040,6 +8045,14 @@ class AppLocalizationsPl extends AppLocalizations { String get chess_statusUnverified => 'Gracze nie zostali jeszcze potwierdzeni. Poproś o aktualizację, aby ich sprawdzić.'; + @override + String get chess_statusPlayersUnchecked => + 'Gracze niepotwierdzeni: ten telefon nie słyszał zaproszenia.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Twój ruch mógł nie zostać wysłany. Dotknij „Poproś o aktualizację”, aby wysłać go ponownie.'; + @override String get chess_actionResign => 'Poddaj się'; @@ -8089,6 +8102,22 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chess_pieceKnight => 'Skoczek'; + @override + String get chess_pieceKing => 'Król'; + + @override + String get chess_piecePawn => 'Pion'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, białe'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, czarne'; + } + @override String get chess_resultDraw => 'Remis'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 890b39cb..1979c31d 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -7832,6 +7832,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chess_unknownPlayer => 'Desconhecido'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter desafiou $target'; + } + @override String get chess_rowYourOpenInvite => 'Seu convite aberto'; @@ -7986,6 +7991,14 @@ class AppLocalizationsPt extends AppLocalizations { String get chess_statusUnverified => 'Jogadores ainda não confirmados. Peça uma atualização para verificá-los.'; + @override + String get chess_statusPlayersUnchecked => + 'Jogadores não confirmados: este telefone não ouviu o convite.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Sua jogada pode não ter sido enviada. Toque em “Pedir atualização” para enviá-la novamente.'; + @override String get chess_actionResign => 'Desistir'; @@ -8035,6 +8048,22 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chess_pieceKnight => 'Cavalo'; + @override + String get chess_pieceKing => 'Rei'; + + @override + String get chess_piecePawn => 'Peão'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, brancas'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, pretas'; + } + @override String get chess_resultDraw => 'Empate'; @@ -15754,6 +15783,11 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get chess_unknownPlayer => 'Desconhecido'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter desafiou $target'; + } + @override String get chess_rowYourOpenInvite => 'O seu convite aberto'; @@ -15908,6 +15942,14 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { String get chess_statusUnverified => 'Jogadores ainda não confirmados. Peça uma atualização para os verificar.'; + @override + String get chess_statusPlayersUnchecked => + 'Jogadores não confirmados: este telemóvel não ouviu o convite.'; + + @override + String get chess_statusMoveUnconfirmed => + 'A sua jogada pode não ter sido enviada. Toque em “Pedir atualização” para a enviar de novo.'; + @override String get chess_actionResign => 'Desistir'; @@ -15957,6 +15999,22 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get chess_pieceKnight => 'Cavalo'; + @override + String get chess_pieceKing => 'Rei'; + + @override + String get chess_piecePawn => 'Peão'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, brancas'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, pretas'; + } + @override String get chess_resultDraw => 'Empate'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 0973944f..b5ad4b10 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -7868,6 +7868,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chess_unknownPlayer => 'Неизвестный'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter бросает вызов: $target'; + } + @override String get chess_rowYourOpenInvite => 'Ваше открытое приглашение'; @@ -8021,6 +8026,14 @@ class AppLocalizationsRu extends AppLocalizations { String get chess_statusUnverified => 'Участники ещё не подтверждены. Запросите обновление, чтобы проверить их.'; + @override + String get chess_statusPlayersUnchecked => + 'Игроки не подтверждены: этот телефон не слышал приглашение.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Ваш ход мог не уйти. Нажмите «Запросить обновление», чтобы отправить его снова.'; + @override String get chess_actionResign => 'Сдаться'; @@ -8070,6 +8083,22 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chess_pieceKnight => 'Конь'; + @override + String get chess_pieceKing => 'Король'; + + @override + String get chess_piecePawn => 'Пешка'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, белые'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, чёрные'; + } + @override String get chess_resultDraw => 'Ничья'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 086bfac1..c155702e 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -7835,6 +7835,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chess_unknownPlayer => 'Neznámy'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter vyzýva hráča $target'; + } + @override String get chess_rowYourOpenInvite => 'Vaša otvorená výzva'; @@ -7988,6 +7993,14 @@ class AppLocalizationsSk extends AppLocalizations { String get chess_statusUnverified => 'Hráči zatiaľ nie sú potvrdení. Vyžiadajte si aktualizáciu a overte ich.'; + @override + String get chess_statusPlayersUnchecked => + 'Hráči nepotvrdení: tento telefón výzvu nepočul.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Váš ťah možno neodišiel. Ťuknutím na „Vyžiadať aktualizáciu“ ho odošlete znova.'; + @override String get chess_actionResign => 'Vzdať sa'; @@ -8037,6 +8050,22 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chess_pieceKnight => 'Jazdec'; + @override + String get chess_pieceKing => 'Kráľ'; + + @override + String get chess_piecePawn => 'Pešiak'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, biela'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, čierna'; + } + @override String get chess_resultDraw => 'Remíza'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 41281008..46b9b96e 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -7827,6 +7827,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chess_unknownPlayer => 'Neznan'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter izziva igralca $target'; + } + @override String get chess_rowYourOpenInvite => 'Vaše odprto povabilo'; @@ -7980,6 +7985,14 @@ class AppLocalizationsSl extends AppLocalizations { String get chess_statusUnverified => 'Igralci še niso potrjeni. Zahtevajte posodobitev, da jih preverite.'; + @override + String get chess_statusPlayersUnchecked => + 'Igralca nista potrjena: ta telefon povabila ni slišal.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Vaša poteza morda ni bila poslana. Tapnite »Zahtevaj posodobitev«, da jo pošljete znova.'; + @override String get chess_actionResign => 'Vdaj se'; @@ -8029,6 +8042,22 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chess_pieceKnight => 'Konj'; + @override + String get chess_pieceKing => 'Kralj'; + + @override + String get chess_piecePawn => 'Kmet'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, bela'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, črna'; + } + @override String get chess_resultDraw => 'Remi'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9ed591cd..e33febe5 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -7787,6 +7787,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chess_unknownPlayer => 'Okänd'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter utmanade $target'; + } + @override String get chess_rowYourOpenInvite => 'Din öppna inbjudan'; @@ -7940,6 +7945,14 @@ class AppLocalizationsSv extends AppLocalizations { String get chess_statusUnverified => 'Spelarna är inte bekräftade ännu. Be om en uppdatering för att kontrollera dem.'; + @override + String get chess_statusPlayersUnchecked => + 'Spelare ej bekräftade: den här telefonen hörde inte inbjudan.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Ditt drag kanske inte gick iväg. Tryck på ”Be om uppdatering” för att skicka det igen.'; + @override String get chess_actionResign => 'Ge upp'; @@ -7989,6 +8002,22 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chess_pieceKnight => 'Springare'; + @override + String get chess_pieceKing => 'Kung'; + + @override + String get chess_piecePawn => 'Bonde'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, vit'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, svart'; + } + @override String get chess_resultDraw => 'Remi'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 2d3d7280..7221f6ce 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -7880,6 +7880,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chess_unknownPlayer => 'Невідомий'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter кидає виклик: $target'; + } + @override String get chess_rowYourOpenInvite => 'Ваше відкрите запрошення'; @@ -8033,6 +8038,14 @@ class AppLocalizationsUk extends AppLocalizations { String get chess_statusUnverified => 'Учасників ще не підтверджено. Запросіть оновлення, щоб перевірити їх.'; + @override + String get chess_statusPlayersUnchecked => + 'Гравців не підтверджено: цей телефон не чув запрошення.'; + + @override + String get chess_statusMoveUnconfirmed => + 'Ваш хід міг не піти. Натисніть «Запросити оновлення», щоб надіслати його знову.'; + @override String get chess_actionResign => 'Здатися'; @@ -8082,6 +8095,22 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chess_pieceKnight => 'Кінь'; + @override + String get chess_pieceKing => 'Король'; + + @override + String get chess_piecePawn => 'Пішак'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square: $piece, білі'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square: $piece, чорні'; + } + @override String get chess_resultDraw => 'Нічия'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 8a5404ee..6b011a45 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -7335,6 +7335,11 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chess_unknownPlayer => '未知'; + @override + String chess_rowChallenge(String inviter, String target) { + return '$inviter 向 $target 发起了挑战'; + } + @override String get chess_rowYourOpenInvite => '你的公开邀请'; @@ -7485,6 +7490,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chess_statusUnverified => '尚未确认对局双方。请求更新以进行确认。'; + @override + String get chess_statusPlayersUnchecked => '对局双方未确认:这部手机没有收到邀请。'; + + @override + String get chess_statusMoveUnconfirmed => '你的这一步可能没有发出。请点按“请求更新”重新发送。'; + @override String get chess_actionResign => '认输'; @@ -7533,6 +7544,22 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chess_pieceKnight => '马'; + @override + String get chess_pieceKing => '王'; + + @override + String get chess_piecePawn => '兵'; + + @override + String chess_squareWhitePiece(String square, String piece) { + return '$square:白$piece'; + } + + @override + String chess_squareBlackPiece(String square, String piece) { + return '$square:黑$piece'; + } + @override String get chess_resultDraw => '和棋'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index e6678624..bc132ffd 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3809,5 +3809,12 @@ "chess_notifyResigned": "{name} heeft opgegeven. Jij wint.", "chess_notifyDrawOffered": "{name} biedt remise aan", "chess_notifyDrawAccepted": "{name} heeft de remise geaccepteerd", - "chess_notifyTimeout": "{name} heeft winst op tijd geclaimd" + "chess_notifyTimeout": "{name} heeft winst op tijd geclaimd", + "chess_rowChallenge": "{inviter} heeft {target} uitgedaagd", + "chess_statusPlayersUnchecked": "Spelers niet bevestigd: deze telefoon heeft de uitnodiging niet gehoord.", + "chess_statusMoveUnconfirmed": "Je zet is mogelijk niet verstuurd. Tik op ‘Om update vragen’ om hem opnieuw te versturen.", + "chess_pieceKing": "Koning", + "chess_piecePawn": "Pion", + "chess_squareWhitePiece": "{square}: {piece}, wit", + "chess_squareBlackPiece": "{square}: {piece}, zwart" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index dd14a340..5990d8b2 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -4147,5 +4147,12 @@ "chess_notifyResigned": "{name} poddał(a) się. Wygrywasz.", "chess_notifyDrawOffered": "{name} proponuje remis", "chess_notifyDrawAccepted": "{name} przyjął(-ęła) remis", - "chess_notifyTimeout": "{name} zgłosił(a) wygraną na czas" + "chess_notifyTimeout": "{name} zgłosił(a) wygraną na czas", + "chess_rowChallenge": "{inviter} rzuca wyzwanie: {target}", + "chess_statusPlayersUnchecked": "Gracze niepotwierdzeni: ten telefon nie słyszał zaproszenia.", + "chess_statusMoveUnconfirmed": "Twój ruch mógł nie zostać wysłany. Dotknij „Poproś o aktualizację”, aby wysłać go ponownie.", + "chess_pieceKing": "Król", + "chess_piecePawn": "Pion", + "chess_squareWhitePiece": "{square}: {piece}, białe", + "chess_squareBlackPiece": "{square}: {piece}, czarne" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index a5863316..49b33601 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3960,5 +3960,12 @@ "chess_notifyResigned": "{name} desistiu. Você venceu.", "chess_notifyDrawOffered": "{name} oferece empate", "chess_notifyDrawAccepted": "{name} aceitou o empate", - "chess_notifyTimeout": "{name} reivindicou vitória por tempo" + "chess_notifyTimeout": "{name} reivindicou vitória por tempo", + "chess_rowChallenge": "{inviter} desafiou {target}", + "chess_statusPlayersUnchecked": "Jogadores não confirmados: este telefone não ouviu o convite.", + "chess_statusMoveUnconfirmed": "Sua jogada pode não ter sido enviada. Toque em “Pedir atualização” para enviá-la novamente.", + "chess_pieceKing": "Rei", + "chess_piecePawn": "Peão", + "chess_squareWhitePiece": "{square}: {piece}, brancas", + "chess_squareBlackPiece": "{square}: {piece}, pretas" } diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 048979f6..da253bf3 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -2187,5 +2187,12 @@ "chess_notifyResigned": "{name} desistiu. Venceu.", "chess_notifyDrawOffered": "{name} oferece empate", "chess_notifyDrawAccepted": "{name} aceitou o empate", - "chess_notifyTimeout": "{name} reclamou vitória por tempo" + "chess_notifyTimeout": "{name} reclamou vitória por tempo", + "chess_rowChallenge": "{inviter} desafiou {target}", + "chess_statusPlayersUnchecked": "Jogadores não confirmados: este telemóvel não ouviu o convite.", + "chess_statusMoveUnconfirmed": "A sua jogada pode não ter sido enviada. Toque em “Pedir atualização” para a enviar de novo.", + "chess_pieceKing": "Rei", + "chess_piecePawn": "Peão", + "chess_squareWhitePiece": "{square}: {piece}, brancas", + "chess_squareBlackPiece": "{square}: {piece}, pretas" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index d35f8166..7a891b51 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -3205,5 +3205,12 @@ "chess_notifyResigned": "{name} сдался. Вы победили.", "chess_notifyDrawOffered": "{name} предлагает ничью", "chess_notifyDrawAccepted": "{name} принимает ничью", - "chess_notifyTimeout": "{name} требует победу по времени" + "chess_notifyTimeout": "{name} требует победу по времени", + "chess_rowChallenge": "{inviter} бросает вызов: {target}", + "chess_statusPlayersUnchecked": "Игроки не подтверждены: этот телефон не слышал приглашение.", + "chess_statusMoveUnconfirmed": "Ваш ход мог не уйти. Нажмите «Запросить обновление», чтобы отправить его снова.", + "chess_pieceKing": "Король", + "chess_piecePawn": "Пешка", + "chess_squareWhitePiece": "{square}: {piece}, белые", + "chess_squareBlackPiece": "{square}: {piece}, чёрные" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index 3d12a1be..b05a9973 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3998,5 +3998,12 @@ "chess_notifyResigned": "Hráč {name} sa vzdal. Vyhrávate.", "chess_notifyDrawOffered": "{name} ponúka remízu", "chess_notifyDrawAccepted": "Hráč {name} prijal remízu", - "chess_notifyTimeout": "Hráč {name} uplatnil výhru na čas" + "chess_notifyTimeout": "Hráč {name} uplatnil výhru na čas", + "chess_rowChallenge": "{inviter} vyzýva hráča {target}", + "chess_statusPlayersUnchecked": "Hráči nepotvrdení: tento telefón výzvu nepočul.", + "chess_statusMoveUnconfirmed": "Váš ťah možno neodišiel. Ťuknutím na „Vyžiadať aktualizáciu“ ho odošlete znova.", + "chess_pieceKing": "Kráľ", + "chess_piecePawn": "Pešiak", + "chess_squareWhitePiece": "{square}: {piece}, biela", + "chess_squareBlackPiece": "{square}: {piece}, čierna" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index e2b7e312..00734520 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -4115,5 +4115,12 @@ "chess_notifyResigned": "Igralec {name} se je vdal. Zmagali ste.", "chess_notifyDrawOffered": "{name} ponuja remi", "chess_notifyDrawAccepted": "Igralec {name} je sprejel remi", - "chess_notifyTimeout": "Igralec {name} je zahteval zmago na čas" + "chess_notifyTimeout": "Igralec {name} je zahteval zmago na čas", + "chess_rowChallenge": "{inviter} izziva igralca {target}", + "chess_statusPlayersUnchecked": "Igralca nista potrjena: ta telefon povabila ni slišal.", + "chess_statusMoveUnconfirmed": "Vaša poteza morda ni bila poslana. Tapnite »Zahtevaj posodobitev«, da jo pošljete znova.", + "chess_pieceKing": "Kralj", + "chess_piecePawn": "Kmet", + "chess_squareWhitePiece": "{square}: {piece}, bela", + "chess_squareBlackPiece": "{square}: {piece}, črna" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 5d994b03..00a95047 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3955,5 +3955,12 @@ "chess_notifyResigned": "{name} gav upp. Du vinner.", "chess_notifyDrawOffered": "{name} erbjuder remi", "chess_notifyDrawAccepted": "{name} accepterade remin", - "chess_notifyTimeout": "{name} krävde vinst på tid" + "chess_notifyTimeout": "{name} krävde vinst på tid", + "chess_rowChallenge": "{inviter} utmanade {target}", + "chess_statusPlayersUnchecked": "Spelare ej bekräftade: den här telefonen hörde inte inbjudan.", + "chess_statusMoveUnconfirmed": "Ditt drag kanske inte gick iväg. Tryck på ”Be om uppdatering” för att skicka det igen.", + "chess_pieceKing": "Kung", + "chess_piecePawn": "Bonde", + "chess_squareWhitePiece": "{square}: {piece}, vit", + "chess_squareBlackPiece": "{square}: {piece}, svart" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 2d490bde..10f97978 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3888,5 +3888,12 @@ "chess_notifyResigned": "{name} здався. Ви перемогли.", "chess_notifyDrawOffered": "{name} пропонує нічию", "chess_notifyDrawAccepted": "{name} приймає нічию", - "chess_notifyTimeout": "{name} вимагає перемогу за часом" + "chess_notifyTimeout": "{name} вимагає перемогу за часом", + "chess_rowChallenge": "{inviter} кидає виклик: {target}", + "chess_statusPlayersUnchecked": "Гравців не підтверджено: цей телефон не чув запрошення.", + "chess_statusMoveUnconfirmed": "Ваш хід міг не піти. Натисніть «Запросити оновлення», щоб надіслати його знову.", + "chess_pieceKing": "Король", + "chess_piecePawn": "Пішак", + "chess_squareWhitePiece": "{square}: {piece}, білі", + "chess_squareBlackPiece": "{square}: {piece}, чорні" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 03e76c4b..453f382e 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3965,5 +3965,12 @@ "chess_notifyResigned": "{name} 认输了。你获胜。", "chess_notifyDrawOffered": "{name} 提议和棋", "chess_notifyDrawAccepted": "{name} 接受了和棋", - "chess_notifyTimeout": "{name} 申请超时判胜" + "chess_notifyTimeout": "{name} 申请超时判胜", + "chess_rowChallenge": "{inviter} 向 {target} 发起了挑战", + "chess_statusPlayersUnchecked": "对局双方未确认:这部手机没有收到邀请。", + "chess_statusMoveUnconfirmed": "你的这一步可能没有发出。请点按“请求更新”重新发送。", + "chess_pieceKing": "王", + "chess_piecePawn": "兵", + "chess_squareWhitePiece": "{square}:白{piece}", + "chess_squareBlackPiece": "{square}:黑{piece}" } diff --git a/test/games/chess_protocol_test.dart b/test/games/chess_protocol_test.dart index 0e599522..40968554 100644 --- a/test/games/chess_protocol_test.dart +++ b/test/games/chess_protocol_test.dart @@ -52,6 +52,35 @@ void main() { expect(positions, greaterThan(1000)); }); + test('drops castling and en passant rights the pieces rule out', () { + // Kings on e1/e8 but the h1 rook gone; an en passant file with no pawn. + const fen = 'r3k2r/8/8/8/8/8/8/R3K3 w KQkq e6 0 1'; + final packed = ChessPositionCodec.encodeFen(fen); + final decoded = ChessPositionCodec.decodeToFen(packed, fullMoveNumber: 1); + expect(decoded, 'r3k2r/8/8/8/8/8/8/R3K3 w Qkq - 0 1'); + // The rules engine can list moves for it without throwing. + final game = ChessGame( + channelId: 'c', + gameId: 1, + status: ChessGameStatus.active, + deadline: ChessDeadline.none, + createdAtMs: 0, + )..adoptPosition(decoded!, 0); + expect(game.legalUci(), contains('e1c1')); + expect(game.legalUci(), isNot(contains('e1g1'))); + + // A real en passant chance survives. + const ep = + 'rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3'; + expect( + ChessPositionCodec.decodeToFen( + ChessPositionCodec.encodeFen(ep), + fullMoveNumber: 3, + ), + ep, + ); + }); + test('rejects a length that does not match the occupancy', () { final packed = ChessPositionCodec.encodeFen(ChessGame.startFen); expect( @@ -84,13 +113,26 @@ void main() { expect(hashChainDistance(other.valueAt(1), chain.commitment), isNull); }); - test('player advances only on new values', () { + test('player values count once and only in order', () { final player = ChessPlayer(name: 'A', commitment: chain.commitment); - expect(player.verifyAndAdvance(chain.valueAt(1)), isTrue); - expect(player.verifyAndAdvance(chain.valueAt(1)), isFalse); - expect(player.verifyAndAdvance(chain.valueAt(4)), isTrue); + expect(player.freshIndex(chain.valueAt(1)), 1); + player.use(1); + expect(player.freshIndex(chain.valueAt(1)), isNull); + expect(player.freshIndex(chain.valueAt(4)), 4); + player.use(4); + // Index 3 was never used, but anyone can compute it from value 4. + expect(player.freshIndex(chain.valueAt(3)), isNull); expect(player.lastIndex, 4); }); + + test('the inviter chain keeps value 1 for the game info', () { + final inviter = ChessPlayer.inviter( + name: 'A', + commitment: chain.commitment, + ); + expect(inviter.freshIndex(chain.valueAt(1)), isNull); + expect(inviter.freshIndex(chain.valueAt(2)), 2); + }); }); group('packets', () { @@ -101,19 +143,17 @@ void main() { test('move packet fits one 64-byte encrypted block run', () { final packet = ChessMovePacket( gameId: 0xBEEF, - ply: 37, - minutes: 1234, + ply: 300, moveIndex: 17, chainValue: value, position: ChessPositionCodec.encodeFen(ChessGame.startFen), ); final bytes = packet.encode(); - expect(bytes.length, 49); + expect(bytes.length, 48); expect(encryptedGamePayloadSize(bytes.length), 64); final decoded = ChessPacket.decode(bytes) as ChessMovePacket; expect(decoded.gameId, 0xBEEF); - expect(decoded.ply, 37); - expect(decoded.minutes, 1234); + expect(decoded.ply, 300); expect(decoded.moveIndex, 17); expect(decoded.chainValue, value); expect(decoded.position, packet.position); @@ -127,7 +167,7 @@ void main() { commitment: commitment, inviterName: longName, ).encode(); - expect(open.length, 54); + expect(open.length, 55); expect(encryptedGamePayloadSize(open.length), 64); final direct = ChessInvitePacket( gameId: 1, @@ -138,12 +178,23 @@ void main() { targetName: longName, ); final bytes = direct.encode(); - expect(bytes.length, 86); + expect(bytes.length, 87); final decoded = ChessPacket.decode(bytes) as ChessInvitePacket; expect(decoded.inviterName, 'N' * maxGameNameBytes); expect(decoded.targetName, 'N' * maxGameNameBytes); expect(decoded.deadline, ChessDeadline.days3); expect(decoded.isDirect, isTrue); + final accept = ChessAcceptPacket( + gameId: 1, + commitment: commitment, + accepterName: longName, + ).encode(); + expect(accept.length, 53); + final decline = ChessDeclinePacket( + gameId: 1, + declinerName: longName, + ).encode(); + expect(decline.length, 37); }); test('names are cut on a character boundary', () { @@ -157,10 +208,9 @@ void main() { kind: ChessPacketKind.resign, gameId: 9, ply: 4, - minutes: 3, chainValue: value, ).encode(); - expect(action.length, 22); + expect(action.length, 21); expect(encryptedGamePayloadSize(action.length), 32); expect( (ChessPacket.decode(action) as ChessActionPacket).kind, @@ -174,13 +224,16 @@ void main() { deadline: ChessDeadline.hour1, whiteCommitment: commitment, blackCommitment: value, + inviterValue: value, whiteName: longName, blackName: longName, ).encode(); - expect(info.length, 106); + expect(info.length, 122); + expect(info.length, lessThanOrEqualTo(maxGamePayloadBytes)); final decodedInfo = ChessPacket.decode(info) as ChessInfoPacket; expect(decodedInfo.startedAtUnix, 1700000000); expect(decodedInfo.blackCommitment, value); + expect(decodedInfo.inviterValue, value); final request = ChessRequestPacket( gameId: 9, @@ -188,7 +241,7 @@ void main() { wantsInfo: true, wantsLatestMove: true, ).encode(); - expect(request.length, 5); + expect(request.length, 6); final decodedRequest = ChessPacket.decode(request) as ChessRequestPacket; expect(decodedRequest.wantsInfo, isTrue); expect(decodedRequest.wantsLatestMove, isTrue); diff --git a/test/games/chess_service_test.dart b/test/games/chess_service_test.dart index 94fe8c90..81c009ae 100644 --- a/test/games/chess_service_test.dart +++ b/test/games/chess_service_test.dart @@ -9,6 +9,7 @@ import 'package:meshcore_open/games/chess/chess_link.dart'; import 'package:meshcore_open/games/chess/chess_packets.dart'; import 'package:meshcore_open/games/chess/chess_service.dart'; import 'package:meshcore_open/games/chess/chess_store.dart'; +import 'package:meshcore_open/games/hash_chain.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -44,6 +45,14 @@ class _FakeLink extends ChangeNotifier implements ChessLink { final List notifications = []; bool connected = true; + /// The radio does not confirm the next send; [deliverFailed] says whether + /// the packet went out anyway. + bool failNext = false; + bool deliverFailed = false; + + /// Lets other timers run while our send is in flight. + bool slow = false; + _FakeLink(this.mesh, this.selfName, this.storageScope) { mesh.links.add(this); } @@ -54,8 +63,14 @@ class _FakeLink extends ChangeNotifier implements ChessLink { @override Future send(String channelId, Uint8List payload) async { if (!connected) return false; + if (failNext) { + failNext = false; + if (deliverFailed) mesh.deliver(this, payload); + return false; + } sent.add(payload); mesh.deliver(this, payload); + if (slow) await Future.delayed(Duration.zero); return true; } @@ -99,7 +114,7 @@ void main() { }); var nextSeed = 100; - _Player player(String name, {int? seed}) { + _Player player(String name, {int? seed, bool Function()? isForeground}) { final link = _FakeLink( mesh, name, @@ -113,6 +128,7 @@ void main() { answerDelayMin: Duration.zero, answerDelayMax: Duration.zero, startHousekeeping: false, + isForeground: isForeground, ); final p = _Player(link, service); created.add(p); @@ -269,7 +285,6 @@ void main() { final forged = ChessMovePacket( gameId: real.gameId, ply: 2, - minutes: 0, moveIndex: 0, chainValue: real.chainValue, position: real.position, @@ -280,7 +295,6 @@ void main() { final random = ChessMovePacket( gameId: real.gameId, ply: 2, - minutes: 0, moveIndex: 0, chainValue: Uint8List(16), position: real.position, @@ -341,4 +355,472 @@ void main() { bob.service.housekeeping(); expect(bob.game!.endReason, ChessEndReason.expired); }); + + /// The packets [p] sent of type [T]. + List sentOf(_Player p) => + p.link.sent.map(ChessPacket.decode).whereType().toList(); + + void feed(_Player p, ChessPacket packet) => + p.service.handleIncoming(ChessIncoming(_channel, packet.encode())); + + /// A legal move on [game]'s board as the next half-move, carrying [value]. + ChessMovePacket craftMove(ChessGame game, String uci, Uint8List value) { + final probe = ChessGame.fromJson(game.toJson())!; + final index = probe.legalUci().indexOf(uci); + probe.applyUci(uci); + return ChessMovePacket( + gameId: game.gameId, + ply: probe.ply, + moveIndex: index, + chainValue: value, + position: probe.packedPosition(), + ); + } + + group('review regressions', () { + test('a replayed chain value cannot carry a later move', () 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'); + final first = sentOf(white).last; + await black.service.makeMove(black.game!, 'e7e5'); + + // White's ply-1 value with a legal ply-3 move. + final replay = craftMove(black.game!, 'd1h5', first.chainValue); + feed(black, replay); + feed(carol, replay); + expect(black.game!.ply, 2); + expect(carol.game!.ply, 2); + + // A spectator two moves behind does not adopt it either. + final dave = player('Dave'); + feed(dave, sentOf(black).last); + final ahead = ChessMovePacket( + gameId: first.gameId, + ply: 5, + moveIndex: 0, + chainValue: first.chainValue, + position: first.position, + ); + feed(carol, ahead); + expect(carol.game!.ply, 2); + + // The real move is accepted, and a different move with the same value + // heard afterwards is not: the first one heard wins. + await white.service.makeMove(white.game!, 'g1f3'); + final real = sentOf(white).last; + final copy = craftMove( + ChessGame.fromJson(carol.game!.toJson())! + ..adoptPosition(black.game!.fen, 2), + 'd2d4', + real.chainValue, + ); + feed(carol, copy); + expect(carol.game!.ply, 3); + expect(carol.game!.sanMoves.last, 'Nf3'); + }); + + test('a forged game info is ignored', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + final mallory = HashChain(Uint8List(16)..[0] = 66); + // Nobody hears Alice's confirmation. + mesh.filter = (from, to, payload) => + !(from == alice.link && + ChessPacket.decode(payload) is ChessInfoPacket); + await alice.service.createInvite( + channelId: _channel, + colour: ChessColourPreference.white, + ); + await bob.service.accept(bob.game!); + await settle(); + final real = sentOf(alice).single; + final inviter = alice.game!.inviter!.commitment; + + // Without the inviter's value: lists Mallory and swaps colours. + ChessInfoPacket info({ + required Uint8List white, + required Uint8List black, + required Uint8List value, + }) => ChessInfoPacket( + gameId: real.gameId, + ply: 0, + startedAtUnix: 0, + deadline: ChessDeadline.days3, + whiteCommitment: white, + blackCommitment: black, + inviterValue: value, + whiteName: 'Alice', + blackName: 'Mallory', + ); + final noValue = info( + white: inviter, + black: mallory.commitment, + value: Uint8List(16), + ); + feed(bob, noValue); + feed(carol, noValue); + expect(bob.game!.status, ChessGameStatus.starting); + expect(bob.game!.mySeedHex, isNotNull); + expect(carol.game!.status, ChessGameStatus.invite); + + // The real value, but colours the invite does not allow. + final swapped = info( + white: real.blackCommitment, + black: inviter, + value: real.inviterValue, + ); + feed(bob, swapped); + feed(carol, swapped); + expect(bob.game!.status, ChessGameStatus.starting); + expect(carol.game!.status, ChessGameStatus.invite); + + // A copied value listing Mallory: Bob watches but keeps his chain, and + // asking again gets him the real game. + final copied = info( + white: inviter, + black: mallory.commitment, + value: real.inviterValue, + ); + feed(bob, copied); + expect(bob.game!.isPlayer, isFalse); + expect(bob.game!.mySeedHex, isNotNull); + mesh.filter = null; + await bob.service.requestUpdate(bob.game!); + await settle(); + expect(bob.game!.mySide, ChessSide.black); + expect(bob.game!.nameOf(ChessSide.white), 'Alice'); + + // A late joiner can't tie the info to an invite: not confirmed. + final dave = player('Dave'); + feed(dave, real); + expect(dave.game!.hasPlayers, isTrue); + expect(dave.game!.playersConfirmed, isFalse); + expect(carol.game!.playersConfirmed, isTrue); + }); + + test('a forged move never starts an invite', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + await alice.service.createInvite( + channelId: _channel, + colour: ChessColourPreference.white, + ); + final forged = craftMove(alice.game!, 'e2e4', Uint8List(16)); + feed(alice, forged); + feed(carol, forged); + expect(alice.game!.status, ChessGameStatus.invite); + expect(carol.game!.status, ChessGameStatus.invite); + + // A real accept still starts the game, and a repeat is answered. + await bob.service.accept(bob.game!); + await settle(); + expect(alice.game!.mySide, ChessSide.white); + feed(alice, sentOf(bob).single); + await settle(); + expect(alice.game!.status, ChessGameStatus.active); + + // A spectator who missed the start follows the inviter's first move. + final dave = player('Dave'); + feed(dave, sentOf(alice).single); + await alice.service.makeMove(alice.game!, 'e2e4'); + expect(dave.game!.status, ChessGameStatus.active); + expect(dave.game!.ply, 1); + expect(dave.game!.white, same(dave.game!.inviter)); + }); + + test('a confirmation heard while our accept is sending counts', () async { + final alice = player('Alice'); + final bob = player('Bob'); + await alice.service.createInvite(channelId: _channel); + bob.link.slow = true; + await bob.service.accept(bob.game!); + expect(bob.game!.status, ChessGameStatus.active); + expect(bob.game!.isPlayer, isTrue); + }); + + test('a losing accepter who missed the info learns it by asking', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + await alice.service.createInvite(channelId: _channel); + mesh.filter = (from, to, _) => to != carol.link; + await bob.service.accept(bob.game!); + await settle(); + mesh.filter = (from, to, payload) => + !(to == carol.link && ChessPacket.decode(payload) is ChessInfoPacket); + await carol.service.accept(carol.game!); + await settle(); + expect(carol.game!.status, ChessGameStatus.starting); + + // Alice answered (unheard); she answers again after a minute. + mesh.filter = null; + now = now.add(ChessService.requestAnswerInterval); + await carol.service.requestUpdate(carol.game!); + await settle(); + expect(carol.game!.status, ChessGameStatus.active); + expect(carol.game!.isPlayer, isFalse); + expect(carol.game!.hasPlayers, isTrue); + }); + + test('repeated accepts are answered at most once a minute', () async { + final alice = player('Alice'); + final bob = player('Bob'); + await startGame(alice, bob); + final before = sentOf(alice).length; + final accept = sentOf(bob).single; + for (var i = 0; i < 5; i++) { + feed(alice, accept); + await settle(); + } + expect(sentOf(alice).length, before + 1); + }); + + test('a lost move followed by a draw offer still gets through', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + mesh.filter = (from, to, payload) => + !(to == black.link && ChessPacket.decode(payload) is ChessMovePacket); + await white.service.makeMove(white.game!, 'e2e4'); + mesh.filter = null; + await white.service.offerDraw(white.game!); + expect(black.game!.ply, 0); + // The offer was for a position Black has not seen. + expect(black.game!.drawOfferedBy, isNull); + + await black.service.requestUpdate(black.game!); + await settle(); + expect(black.game!.ply, 1); + expect(black.game!.isMyTurn, isTrue); + await black.service.makeMove(black.game!, 'e7e5'); + expect(white.game!.ply, 2); + }); + + test('a move the radio did not confirm is kept and sent again', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + final next = white.game!.myNextChainIndex; + white.link.failNext = true; + expect(await white.service.makeMove(white.game!, 'e2e4'), isFalse); + // Applied, with its chain value used up. + expect(white.game!.ply, 1); + expect(white.game!.moveUnconfirmed, isTrue); + expect(white.game!.myNextChainIndex, next + 1); + expect(black.game!.ply, 0); + + await white.service.requestUpdate(white.game!); + expect(black.game!.ply, 1); + expect(white.game!.moveUnconfirmed, isFalse); + + // A failed action does not give its chain value back either. + black.link.failNext = true; + final before = black.game!.myNextChainIndex; + expect(await black.service.offerDraw(black.game!), isFalse); + expect(black.game!.myNextChainIndex, before + 1); + expect(await black.service.makeMove(black.game!, 'e7e5'), isTrue); + expect(white.game!.ply, 2); + }); + + test( + 'a move that went out despite a failed send is not replaced', + () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + white.link + ..failNext = true + ..deliverFailed = true; + await white.service.makeMove(white.game!, 'e2e4'); + expect(black.game!.ply, 1); + expect(white.game!.isMyTurn, isFalse); + expect(await white.service.makeMove(white.game!, 'd2d4'), isFalse); + expect(white.game!.fen, black.game!.fen); + }, + ); + + test('draw accepts and timeout claims need their preconditions', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + final (white, black) = await startGame(alice, bob); + final whiteChain = white.game!.myChain!; + var next = white.game!.myNextChainIndex; + ChessActionPacket action(ChessPacketKind kind) => ChessActionPacket( + kind: kind, + gameId: white.game!.gameId, + ply: white.game!.ply, + chainValue: whiteChain.valueAt(next++), + ); + + // No draw offer pending. + final accept = action(ChessPacketKind.drawAccept); + feed(black, accept); + feed(carol, accept); + expect(black.game!.status, ChessGameStatus.active); + expect(carol.game!.status, ChessGameStatus.active); + + // Black to move, but the hour is not up yet. + white.game!.myNextChainIndex = next; + await white.service.makeMove(white.game!, 'e2e4'); + next = white.game!.myNextChainIndex; + now = now.add(const Duration(minutes: 30)); + feed(black, action(ChessPacketKind.timeoutClaim)); + expect(black.game!.status, ChessGameStatus.active); + // Past the deadline it counts. + now = now.add(const Duration(minutes: 31)); + feed(black, action(ChessPacketKind.timeoutClaim)); + expect(black.game!.endReason, ChessEndReason.timeout); + + // No deadline at all: never. + final erin = player('Erin'); + final finn = player('Finn'); + final invite = await erin.service.createInvite( + channelId: _channel, + deadline: ChessDeadline.none, + colour: ChessColourPreference.white, + ); + await finn.service.accept(finn.service.game(_channel, invite!.gameId)!); + await settle(); + final e = erin.service.game(_channel, invite.gameId)!; + await erin.service.makeMove(e, 'e2e4'); + now = now.add(const Duration(days: 30)); + final claim = ChessActionPacket( + kind: ChessPacketKind.timeoutClaim, + gameId: e.gameId, + ply: e.ply, + chainValue: e.myChain!.valueAt(e.myNextChainIndex), + ); + feed(finn, claim); + expect( + finn.service.game(_channel, invite.gameId)!.status, + ChessGameStatus.active, + ); + }); + + test('notifications for the open game resume in the background', () async { + var foreground = true; + final alice = player('Alice'); + final bob = player('Bob', isForeground: () => foreground); + final (white, black) = await startGame(alice, bob); + expect(black, same(bob)); + bob.service.viewing = bob.game; + await white.service.makeMove(white.game!, 'e2e4'); + expect(bob.link.notifications, isEmpty); + await black.service.makeMove(black.game!, 'e7e5'); + foreground = false; + await white.service.makeMove(white.game!, 'd2d4'); + expect(bob.link.notifications, hasLength(1)); + }); + + test('the game cap keeps our own invites and accepts', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final mine = await alice.service.createInvite(channelId: _channel); + final theirs = await bob.service.createInvite(channelId: _channel); + await alice.service.accept(alice.service.game(_channel, theirs!.gameId)!); + now = now.add(const Duration(minutes: 1)); + for (var i = 0; i < ChessService.maxStoredGames + 5; i++) { + feed( + alice, + ChessInvitePacket( + gameId: 1000 + i, + deadline: ChessDeadline.hour1, + colour: ChessColourPreference.random, + commitment: Uint8List(16)..[0] = i, + inviterName: 'Spam $i', + ), + ); + } + alice.service.housekeeping(); + expect(alice.service.game(_channel, mine!.gameId), isNotNull); + expect(alice.service.game(_channel, theirs.gameId), isNotNull); + }); + + test('only the inviter acts on a decline', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final carol = player('Carol'); + await alice.service.createInvite(channelId: _channel, targetName: 'Bob'); + feed( + carol, + ChessDeclinePacket(gameId: alice.game!.gameId, declinerName: 'Bob'), + ); + expect(carol.game!.status, ChessGameStatus.invite); + expect(bob.game!.status, ChessGameStatus.invite); + // The challenge to Bob is neither listed nor counted for Carol. + expect(carol.service.isListed(carol.game!), isFalse); + expect(carol.service.openCountForChannel(_channel), 0); + expect(bob.service.openCountForChannel(_channel), 1); + }); + + test('a late joiner keeps the full ply and takes the deadline from the ' + 'game info', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, _) = await startGame(alice, bob); + final g = white.game!; + final move = ChessMovePacket( + gameId: g.gameId, + ply: 301, + moveIndex: 0, + chainValue: Uint8List(16), + position: g.packedPosition(), + ); + final dave = player('Dave'); + feed(dave, move); + expect(dave.game!.ply, 301); + expect(dave.game!.deadline, ChessDeadline.none); + feed(dave, sentOf(alice).single); + expect(dave.game!.hasPlayers, isTrue); + expect(dave.game!.deadline, ChessDeadline.hour1); + }); + + test('a spectator who hears the game info mid-game takes the board from ' + 'the latest move', () async { + final alice = player('Alice'); + final bob = player('Bob'); + final (white, black) = await startGame(alice, bob); + await white.service.makeMove(white.game!, 'e2e4'); + await black.service.makeMove(black.game!, 'e7e5'); + final dave = player('Dave'); + await dave.service.requestUpdate( + ChessGame( + channelId: _channel, + gameId: alice.game!.gameId, + status: ChessGameStatus.active, + deadline: ChessDeadline.none, + hasPosition: false, + createdAtMs: 0, + ), + ); + await settle(); + expect(dave.game!.hasPlayers, isTrue); + expect(dave.game!.ply, 2); + expect(dave.game!.hasPosition, isTrue); + expect(dave.game!.fen, alice.game!.fen); + }); + + test('a malformed position never throws out of the listener', () { + final carol = player('Carol'); + final packet = Uint8List.fromList( + ChessMovePacket( + gameId: 5, + ply: 1, + moveIndex: 0, + chainValue: Uint8List(16), + position: Uint8List(10), + ).encode(), + ); + expect( + () => carol.service.handleIncoming(ChessIncoming(_channel, packet)), + returnsNormally, + ); + }); + }); } diff --git a/test/games/chess_ui_test.dart b/test/games/chess_ui_test.dart index 4b8abec6..e6569471 100644 --- a/test/games/chess_ui_test.dart +++ b/test/games/chess_ui_test.dart @@ -118,6 +118,11 @@ void main() { ); testWidgets('sheet lists our game and the open invite', (tester) async { + // A cancelled invite of ours, listed under Finished. + final cancelled = await tester.runAsync( + () => service.createInvite(channelId: channelId), + ); + await tester.runAsync(() => service.cancelInvite(cancelled!)); tester.view.physicalSize = const Size(400, 2000); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); @@ -139,6 +144,9 @@ void main() { expect(find.text(_l10n.chess_vs('Me', 'Bob')), findsOne); expect(find.text(_l10n.chess_rowOpenInvite('Carol')), findsOne); expect(find.text(_l10n.chess_accept), findsOne); + expect(find.text(_l10n.chess_rowYourOpenInvite), findsOne); + expect(find.text(_l10n.chess_endCancelled), findsOne); + expect(find.text(_l10n.chess_vs('Unknown', 'Unknown')), findsNothing); }); testWidgets('tapping a piece and a target sends the move', (tester) async { @@ -152,7 +160,11 @@ void main() { expect(find.byType(ChessBoardView), findsOne); expect(find.text(_l10n.chess_statusYourMove), findsWidgets); - await tester.tap(find.bySemanticsLabel('e2 P')); + await tester.tap( + find.bySemanticsLabel( + _l10n.chess_squareWhitePiece('e2', _l10n.chess_piecePawn), + ), + ); await tester.pump(); await tester.tap(find.bySemanticsLabel('e4')); await tester.pumpAndSettle(); diff --git a/test/screens/small_screen_layout_test.dart b/test/screens/small_screen_layout_test.dart index fef25628..a0d66913 100644 --- a/test/screens/small_screen_layout_test.dart +++ b/test/screens/small_screen_layout_test.dart @@ -154,6 +154,7 @@ void _seedChessGames(ChessService chess, String channelId) { deadline: ChessDeadline.hour1, whiteCommitment: white.commitment, blackCommitment: black.commitment, + inviterValue: white.valueAt(1), whiteName: 'Alexandra the Long-Named', blackName: 'Bartholomew Repeater Fan', ), @@ -167,9 +168,11 @@ void _seedChessGames(ChessService chess, String channelId) { ChessMovePacket( gameId: _chessGameId, ply: i + 1, - minutes: i, moveIndex: index, - chainValue: (i.isEven ? white : black).valueAt(i ~/ 2 + 1), + // White invited, so its value 1 belongs to the game info. + chainValue: i.isEven + ? white.valueAt(i ~/ 2 + 2) + : black.valueAt(i ~/ 2 + 1), position: probe.packedPosition(), ), );