Add chess games over channel data

Play and watch chess on a channel via the Chess games entry in the
channel overflow menu. Moves travel as GRP_DATA packets (type 0x0100)
carrying the full position and a hash-chain value for authentication.
Includes translations for all locales.
This commit is contained in:
zjs81 committed 2026-11-22 17:00:35 -07:00
1 parent 9ac915bdf2
commit 185b026a0d
66 files changed
+15314 -25

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/games/chess/chess_link.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/game_packet.dart';
import 'package:meshcore_open/services/image_chunk_transport.dart';
class _Connector extends MeshCoreConnector {
final frames = StreamController<Uint8List>.broadcast(sync: true);
bool mapConfirmed = false;
@override
Stream<Uint8List> get receivedFrames => frames.stream;
@override
bool get channelMapConfirmed => mapConfirmed;
@override
String? channelIdForSlot(int slot) => slot == 2 ? 'chan-two' : null;
void confirm() {
mapConfirmed = true;
notifyListeners();
}
}
/// A RESP_CODE_CHANNEL_DATA_RECV frame for [payload] on [slot].
Uint8List _frame(int slot, int dataType, Uint8List payload) =>
Uint8List.fromList([
respCodeChannelDataRecv,
8, // SNR
0,
0,
slot,
0xFF,
dataType & 0xFF,
dataType >> 8,
payload.length,
...payload,
]);
void main() {
final payload = ChessDeclinePacket(gameId: 5, declinerName: 'Bob').encode();
test('passes chess payloads through, keyed by channel id', () async {
final connector = _Connector()..mapConfirmed = true;
final link = ConnectorChessLink(connector);
final heard = <ChessIncoming>[];
link.incoming.listen(heard.add);
connector.frames.add(_frame(2, meshcoreOpenDataType, payload));
connector.frames.add(_frame(2, 0xAE1C, payload)); // images
connector.frames.add(_frame(3, meshcoreOpenDataType, payload)); // unknown
connector.frames.add(
_frame(2, meshcoreOpenDataType, Uint8List.fromList([0x20, 0, 0, 0])),
); // another app nibble
await Future<void>.delayed(Duration.zero);
expect(heard, hasLength(1));
expect(heard.single.channelId, 'chan-two');
expect(heard.single.payload, payload);
link.dispose();
});
test('holds frames until the channel map is confirmed', () async {
final connector = _Connector();
final link = ConnectorChessLink(connector);
final heard = <ChessIncoming>[];
link.incoming.listen(heard.add);
connector.frames.add(_frame(2, meshcoreOpenDataType, payload));
expect(heard, isEmpty);
connector.confirm();
// The connector batches change notifications.
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(heard, hasLength(1));
link.dispose();
});
}
+208
View File
@@ -0,0 +1,208 @@
import 'dart:math';
import 'dart:typed_data';
import 'package:chess/chess.dart' as rules;
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/chess/chess_position_codec.dart';
import 'package:meshcore_open/games/game_packet.dart';
import 'package:meshcore_open/games/hash_chain.dart';
Uint8List _bytes(int n, int seed) =>
Uint8List.fromList(List.generate(n, (i) => (i * 31 + seed) & 0xFF));
/// FEN without the full-move number, which the codec does not carry.
String _withoutMoveNumber(String fen) => fen.split(' ').sublist(0, 5).join(' ');
void main() {
group('position codec', () {
test('start position packs to 26 bytes and round-trips', () {
final packed = ChessPositionCodec.encodeFen(ChessGame.startFen);
expect(packed.length, 26);
expect(
ChessPositionCodec.decodeToFen(packed, fullMoveNumber: 1),
ChessGame.startFen,
);
});
test('round-trips positions from random games', () {
final rng = Random(7);
var positions = 0;
for (var game = 0; game < 40; game++) {
final board = rules.Chess();
for (var ply = 0; ply < 120 && !board.game_over; ply++) {
final moves = board.moves({'asObjects': true}).cast<rules.Move>();
board.move(moves[rng.nextInt(moves.length)]);
final fen = board.fen;
final packed = ChessPositionCodec.encodeFen(fen);
expect(packed.length, lessThanOrEqualTo(ChessPositionCodec.maxBytes));
final decoded = ChessPositionCodec.decodeToFen(
packed,
fullMoveNumber: board.move_number,
);
expect(
_withoutMoveNumber(decoded!),
_withoutMoveNumber(fen),
reason: fen,
);
positions++;
}
}
expect(positions, greaterThan(1000));
});
test('rejects a length that does not match the occupancy', () {
final packed = ChessPositionCodec.encodeFen(ChessGame.startFen);
expect(
ChessPositionCodec.decodeToFen(
Uint8List.fromList(packed.sublist(0, 20)),
fullMoveNumber: 1,
),
isNull,
);
});
});
group('hash chain', () {
final chain = HashChain(_bytes(16, 3));
test('each value hashes to the previous one', () {
expect(hashChainStep(chain.valueAt(1)), chain.valueAt(0));
expect(hashChainStep(chain.valueAt(10)), chain.valueAt(9));
});
test('distance counts skipped values and flags duplicates', () {
expect(hashChainDistance(chain.valueAt(1), chain.commitment), 1);
expect(hashChainDistance(chain.valueAt(5), chain.valueAt(2)), 3);
expect(hashChainDistance(chain.valueAt(2), chain.valueAt(2)), 0);
});
test('rejects older values and other chains', () {
expect(hashChainDistance(chain.valueAt(2), chain.valueAt(5)), isNull);
final other = HashChain(_bytes(16, 9));
expect(hashChainDistance(other.valueAt(1), chain.commitment), isNull);
});
test('player advances only on new values', () {
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.lastIndex, 4);
});
});
group('packets', () {
final commitment = _bytes(16, 1);
final value = _bytes(16, 2);
final longName = 'N' * 40;
test('move packet fits one 64-byte encrypted block run', () {
final packet = ChessMovePacket(
gameId: 0xBEEF,
ply: 37,
minutes: 1234,
moveIndex: 17,
chainValue: value,
position: ChessPositionCodec.encodeFen(ChessGame.startFen),
);
final bytes = packet.encode();
expect(bytes.length, 49);
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.moveIndex, 17);
expect(decoded.chainValue, value);
expect(decoded.position, packet.position);
});
test('invite sizes and names are capped', () {
final open = ChessInvitePacket(
gameId: 1,
deadline: ChessDeadline.hour1,
colour: ChessColourPreference.black,
commitment: commitment,
inviterName: longName,
).encode();
expect(open.length, 54);
expect(encryptedGamePayloadSize(open.length), 64);
final direct = ChessInvitePacket(
gameId: 1,
deadline: ChessDeadline.days3,
colour: ChessColourPreference.random,
commitment: commitment,
inviterName: longName,
targetName: longName,
);
final bytes = direct.encode();
expect(bytes.length, 86);
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);
});
test('names are cut on a character boundary', () {
final name = '${'a' * 29}é'; // 29 + 2 bytes = 31: fits.
expect(truncateUtf8(name, 31).length, 31);
expect(truncateUtf8('${'a' * 30}é', 31).length, 30);
});
test('actions, info and requests round-trip', () {
final action = ChessActionPacket(
kind: ChessPacketKind.resign,
gameId: 9,
ply: 4,
minutes: 3,
chainValue: value,
).encode();
expect(action.length, 22);
expect(encryptedGamePayloadSize(action.length), 32);
expect(
(ChessPacket.decode(action) as ChessActionPacket).kind,
ChessPacketKind.resign,
);
final info = ChessInfoPacket(
gameId: 9,
ply: 4,
startedAtUnix: 1700000000,
deadline: ChessDeadline.hour1,
whiteCommitment: commitment,
blackCommitment: value,
whiteName: longName,
blackName: longName,
).encode();
expect(info.length, 106);
final decodedInfo = ChessPacket.decode(info) as ChessInfoPacket;
expect(decodedInfo.startedAtUnix, 1700000000);
expect(decodedInfo.blackCommitment, value);
final request = ChessRequestPacket(
gameId: 9,
ply: 4,
wantsInfo: true,
wantsLatestMove: true,
).encode();
expect(request.length, 5);
final decodedRequest = ChessPacket.decode(request) as ChessRequestPacket;
expect(decodedRequest.wantsInfo, isTrue);
expect(decodedRequest.wantsLatestMove, isTrue);
});
test('rejects other apps and truncated packets', () {
final bytes = ChessAcceptPacket(
gameId: 2,
commitment: commitment,
accepterName: 'Bob',
).encode();
expect(ChessPacket.decode(bytes.sublist(0, 10)), isNull);
final otherApp = Uint8List.fromList(bytes)..[0] = 0x21;
expect(ChessPacket.decode(otherApp), isNull);
});
});
}
+344
View File
@@ -0,0 +1,344 @@
import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
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/l10n/app_localizations.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _channel = 'abcdef0123456789';
/// A shared channel: whatever one link sends, every other link hears.
class _Mesh {
final List<_FakeLink> links = [];
/// Return false to drop a packet before it reaches [to].
bool Function(_FakeLink from, _FakeLink to, Uint8List payload)? filter;
void deliver(_FakeLink from, Uint8List payload) {
for (final to in links) {
if (identical(to, from)) continue;
if (filter != null && !filter!(from, to, payload)) continue;
to.controller.add(ChessIncoming(_channel, payload));
}
}
}
class _FakeLink extends ChangeNotifier implements ChessLink {
final _Mesh mesh;
@override
final String selfName;
@override
final String storageScope;
final StreamController<ChessIncoming> controller = StreamController.broadcast(
sync: true,
);
final List<Uint8List> sent = [];
final List<String> notifications = [];
bool connected = true;
_FakeLink(this.mesh, this.selfName, this.storageScope) {
mesh.links.add(this);
}
@override
Stream<ChessIncoming> get incoming => controller.stream;
@override
Future<bool> send(String channelId, Uint8List payload) async {
if (!connected) return false;
sent.add(payload);
mesh.deliver(this, payload);
return true;
}
@override
bool get canSend => connected;
@override
void notify(String channelId, String text) => notifications.add(text);
@override
AppLocalizations get l10n => lookupAppLocalizations(const Locale('en'));
}
class _Player {
final _FakeLink link;
final ChessService service;
_Player(this.link, this.service);
ChessGame? get game => service.gamesForChannel(_channel).firstOrNull;
}
void main() {
late _Mesh mesh;
late DateTime now;
final created = <_Player>[];
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
mesh = _Mesh();
now = DateTime(2026, 11, 21, 12);
});
tearDown(() {
for (final p in created) {
p.service.dispose();
}
created.clear();
});
var nextSeed = 100;
_Player player(String name, {int? seed}) {
final link = _FakeLink(
mesh,
name,
'${name.toLowerCase()}000000000'.substring(0, 10),
);
final service = ChessService(
link: link,
store: ChessStore(),
clock: () => now,
random: Random(seed ?? nextSeed++),
answerDelayMin: Duration.zero,
answerDelayMax: Duration.zero,
startHousekeeping: false,
);
final p = _Player(link, service);
created.add(p);
return p;
}
/// Lets zero-delay answer timers fire.
Future<void> settle() => Future<void>.delayed(Duration.zero);
Future<(_Player white, _Player black)> startGame(
_Player alice,
_Player bob, {
ChessColourPreference colour = ChessColourPreference.white,
}) async {
final invite = await alice.service.createInvite(
channelId: _channel,
colour: colour,
);
expect(invite, isNotNull);
expect(await bob.service.accept(bob.game!), isTrue);
await settle(); // Alice's confirmation (game info).
expect(alice.game!.status, ChessGameStatus.active);
expect(bob.game!.status, ChessGameStatus.active);
final aliceWhite = alice.game!.mySide == ChessSide.white;
return aliceWhite ? (alice, bob) : (bob, alice);
}
test(
'open invite, accept, and Scholar\'s mate seen by a spectator',
() async {
final alice = player('Alice', seed: 1);
final bob = player('Bob', seed: 2);
final carol = player('Carol', seed: 3);
final (white, black) = await startGame(alice, bob);
expect(white, same(alice));
expect(carol.game!.status, ChessGameStatus.active);
expect(carol.game!.isPlayer, isFalse);
expect(carol.game!.hasPlayers, isTrue);
expect(bob.link.notifications, isEmpty);
const moves = ['e2e4', 'e7e5', 'f1c4', 'b8c6', 'd1h5', 'g8f6', 'h5f7'];
for (var i = 0; i < moves.length; i++) {
final mover = i.isEven ? white : black;
expect(
await mover.service.makeMove(mover.game!, moves[i]),
isTrue,
reason: moves[i],
);
}
for (final p in [alice, bob, carol]) {
final g = p.game!;
expect(g.status, ChessGameStatus.finished);
expect(g.endReason, ChessEndReason.checkmate);
expect(g.winner, ChessSide.white);
expect(g.sanMoves.last, 'Qxf7#');
}
expect(bob.link.notifications.last, contains('Alice'));
},
);
test('random colour gives both sides the same answer', () async {
final alice = player('Alice', seed: 4);
final bob = player('Bob', seed: 5);
await startGame(alice, bob, colour: ChessColourPreference.random);
expect(alice.game!.mySide, isNotNull);
expect(bob.game!.mySide, alice.game!.mySide!.other);
});
test('direct challenge notifies only the target, who can decline', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(channelId: _channel, targetName: 'bob');
expect(bob.link.notifications.single, contains('Alice'));
expect(carol.link.notifications, isEmpty);
expect(await bob.service.decline(bob.game!), isTrue);
expect(alice.game!.status, ChessGameStatus.finished);
expect(alice.game!.endReason, ChessEndReason.declined);
});
test('only the first confirmed accept gets the game', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(
channelId: _channel,
colour: ChessColourPreference.white,
);
// Carol does not hear Bob's accept, and accepts too.
mesh.filter = (from, to, _) => !(from == bob.link && to == carol.link);
await bob.service.accept(bob.game!);
mesh.filter = null;
await carol.service.accept(carol.game!);
await settle();
expect(alice.game!.nameOf(ChessSide.black), 'Bob');
expect(bob.game!.mySide, ChessSide.black);
expect(carol.game!.isPlayer, isFalse);
expect(carol.game!.status, ChessGameStatus.active);
});
test(
'a spectator that missed moves takes the position from the next one',
() async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'd2d4');
await black.service.makeMove(black.game!, 'd7d5');
final dave = player('Dave');
await white.service.makeMove(white.game!, 'c2c4');
final g = dave.game!;
expect(g.ply, 3);
expect(g.fen, white.game!.fen);
expect(g.sanMoves, [null, null, null]);
expect(g.hasPlayers, isFalse);
// Asking for an update fetches the players.
await dave.service.requestUpdate(g);
await settle();
expect(dave.game!.hasPlayers, isTrue);
await black.service.makeMove(black.game!, 'e7e6');
expect(dave.game!.ply, 4);
expect(dave.game!.sanMoves.last, 'e6');
},
);
test('a player who missed a move gets it back by asking', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
mesh.filter = (from, to, _) => !(from == white.link && to == black.link);
await white.service.makeMove(white.game!, 'e2e4');
mesh.filter = null;
expect(black.game!.ply, 0);
expect(black.game!.isMyTurn, isFalse);
await black.service.requestUpdate(black.game!);
await settle();
expect(black.game!.ply, 1);
expect(black.game!.isMyTurn, isTrue);
});
test('forged moves and conflicting duplicates are rejected', () 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 real = ChessPacket.decode(white.link.sent.last) as ChessMovePacket;
// Mallory replays White's chain value with a different move as Black's.
final forged = ChessMovePacket(
gameId: real.gameId,
ply: 2,
minutes: 0,
moveIndex: 0,
chainValue: real.chainValue,
position: real.position,
);
carol.service.handleIncoming(ChessIncoming(_channel, forged.encode()));
expect(carol.game!.ply, 1);
// And a made-up chain value.
final random = ChessMovePacket(
gameId: real.gameId,
ply: 2,
minutes: 0,
moveIndex: 0,
chainValue: Uint8List(16),
position: real.position,
);
carol.service.handleIncoming(ChessIncoming(_channel, random.encode()));
black.service.handleIncoming(ChessIncoming(_channel, random.encode()));
expect(carol.game!.ply, 1);
expect(black.game!.ply, 1);
});
test('resign, draw and timeout claims', () async {
final alice = player('Alice');
final bob = player('Bob');
var (white, black) = await startGame(alice, bob);
await white.service.offerDraw(white.game!);
expect(black.game!.drawOfferedBy, ChessSide.white);
await black.service.acceptDraw(black.game!);
expect(white.game!.endReason, ChessEndReason.drawAgreed);
final carol = player('Carol', seed: 8);
final dan = player('Dan', seed: 9);
(white, black) = await startGame(carol, dan);
await black.service.resign(black.game!);
expect(white.game!.winner, ChessSide.white);
expect(white.game!.endReason, ChessEndReason.resignation);
final erin = player('Erin', seed: 10);
final finn = player('Finn', seed: 11);
(white, black) = await startGame(erin, finn);
await white.service.makeMove(white.game!, 'e2e4');
expect(white.service.canClaimTimeout(white.game!), isFalse);
now = now.add(const Duration(hours: 1, minutes: 11));
expect(white.service.canClaimTimeout(white.game!), isTrue);
expect(await white.service.claimTimeout(white.game!), isTrue);
expect(black.game!.endReason, ChessEndReason.timeout);
expect(black.game!.winner, ChessSide.white);
});
test('games persist per radio scope', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, _) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'g1f3');
await alice.service.store.flush();
final reloaded = ChessStore().load(alice.link.storageScope).single;
expect(reloaded.ply, 1);
expect(reloaded.mySide, alice.game!.mySide);
expect(reloaded.mySeedHex, isNotNull);
expect(ChessStore().load('other00000'), isEmpty);
});
test('invites expire after a day', () async {
final alice = player('Alice');
final bob = player('Bob');
await alice.service.createInvite(channelId: _channel);
now = now.add(const Duration(hours: 25));
bob.service.housekeeping();
expect(bob.game!.endReason, ChessEndReason.expired);
});
}
+165
View File
@@ -0,0 +1,165 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
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/ui/chess_board.dart';
import 'package:meshcore_open/games/chess/ui/chess_game_screen.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/games/chess/ui/chess_games_sheet.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
class _ConnectedConnector extends MeshCoreConnector {
@override
bool get isConnected => true;
}
class _Link extends ChangeNotifier implements ChessLink {
final controller = StreamController<ChessIncoming>.broadcast(sync: true);
final sent = <Uint8List>[];
@override
Stream<ChessIncoming> get incoming => controller.stream;
@override
Future<bool> send(String channelId, Uint8List payload) async {
sent.add(payload);
return true;
}
@override
String get selfName => 'Me';
@override
String get storageScope => 'ui00000000';
@override
bool get canSend => true;
@override
void notify(String channelId, String text) {}
@override
AppLocalizations get l10n => _l10n;
}
void main() {
late Channel channel;
late String channelId;
late _Link link;
late ChessService service;
late ChessGame myGame;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
channel = Channel(index: 0, name: 'Public', psk: Uint8List(16)..[0] = 9);
channelId = channel.storageId!;
link = _Link();
service = ChessService(link: link, startHousekeeping: false);
// Our own invite, accepted by Bob, so we play white.
myGame = (await service.createInvite(
channelId: channelId,
colour: ChessColourPreference.white,
))!;
link.controller.add(
ChessIncoming(
channelId,
ChessAcceptPacket(
gameId: myGame.gameId,
commitment: Uint8List(16)..[3] = 7,
accepterName: 'Bob',
).encode(),
),
);
link.controller.add(
ChessIncoming(
channelId,
ChessInvitePacket(
gameId: 4242,
deadline: ChessDeadline.day1,
colour: ChessColourPreference.random,
commitment: Uint8List(16)..[1] = 1,
inviterName: 'Carol',
).encode(),
),
);
});
tearDown(() => service.dispose());
Widget app(Widget home) => MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(
value: _ConnectedConnector(),
),
ChangeNotifierProvider.value(value: service),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
);
testWidgets('sheet lists our game and the open invite', (tester) async {
tester.view.physicalSize = const Size(400, 2000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
app(
Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => showChessGamesSheet(context, channel),
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chess_sectionYourGames.toUpperCase()), findsOne);
expect(find.text(_l10n.chess_vs('Me', 'Bob')), findsOne);
expect(find.text(_l10n.chess_rowOpenInvite('Carol')), findsOne);
expect(find.text(_l10n.chess_accept), findsOne);
});
testWidgets('tapping a piece and a target sends the move', (tester) async {
tester.view.physicalSize = const Size(400, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
app(ChessGameScreen(channelId: channelId, gameId: myGame.gameId)),
);
await tester.pump();
expect(find.byType(ChessBoardView), findsOne);
expect(find.text(_l10n.chess_statusYourMove), findsWidgets);
await tester.tap(find.bySemanticsLabel('e2 P'));
await tester.pump();
await tester.tap(find.bySemanticsLabel('e4'));
await tester.pumpAndSettle();
final move = ChessPacket.decode(link.sent.last);
expect(move, isA<ChessMovePacket>());
expect(myGame.sanMoves, ['e4']);
expect(find.text(_l10n.chess_statusWaiting('Bob')), findsOne);
});
}
@@ -12,6 +12,13 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
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/ui/chess_game_screen.dart';
import 'package:meshcore_open/games/chess/ui/chess_games_sheet.dart';
import 'package:meshcore_open/games/hash_chain.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
@@ -81,8 +88,13 @@ Future<_Env> _connect(WidgetTester tester) async {
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
final chess = ChessService(
link: ConnectorChessLink(connector, settings: settings),
startHousekeeping: false,
);
final env = _Env(connector, [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: chess),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
@@ -122,9 +134,57 @@ Future<_Env> _connect(WidgetTester tester) async {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
_seedChessGames(chess, connector.channels.first.storageId!);
return env;
}
const _chessGameId = 77;
/// A game in progress (long names, a few moves) and an open invite.
void _seedChessGames(ChessService chess, String channelId) {
void feed(ChessPacket p) =>
chess.handleIncoming(ChessIncoming(channelId, p.encode()));
final white = HashChain(Uint8List(16));
final black = HashChain(Uint8List(16)..[0] = 1);
feed(
ChessInfoPacket(
gameId: _chessGameId,
ply: 0,
startedAtUnix: 1700000000,
deadline: ChessDeadline.hour1,
whiteCommitment: white.commitment,
blackCommitment: black.commitment,
whiteName: 'Alexandra the Long-Named',
blackName: 'Bartholomew Repeater Fan',
),
);
final game = chess.game(channelId, _chessGameId)!;
for (final (i, uci) in ['e2e4', 'e7e5', 'g1f3'].indexed) {
final probe = ChessGame.fromJson(game.toJson())!;
final index = probe.legalUci().indexOf(uci);
probe.applyUci(uci);
feed(
ChessMovePacket(
gameId: _chessGameId,
ply: i + 1,
minutes: i,
moveIndex: index,
chainValue: (i.isEven ? white : black).valueAt(i ~/ 2 + 1),
position: probe.packedPosition(),
),
);
}
feed(
ChessInvitePacket(
gameId: 78,
deadline: ChessDeadline.day1,
colour: ChessColourPreference.random,
commitment: HashChain(Uint8List(16)..[0] = 2).commitment,
inviterName: 'Cornelius Openinvite',
),
);
}
Contact _contactOfType(MeshCoreConnector c, int type) => c.contacts.firstWhere(
(x) => x.type == type,
orElse: () => c.contacts.first,
@@ -151,6 +211,14 @@ _interactions = {
await t.tap(find.byType(FloatingActionButton));
},
// Four routing modes (Auto, Flood, Direct, Manual) share one row.
'Chess games sheet': (t, c) async {
unawaited(
showChessGamesSheet(
t.element(find.byType(ChannelChatScreen)),
c.channels.first,
),
);
},
'Routing sheet': (t, c) async {
unawaited(
ContactRoutingSheet.show(
@@ -183,6 +251,11 @@ final Map<String, _ScreenBuilder> _screens = {
'Map': (_) => const MapScreen(),
'Chat': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)),
'ChannelChat': (c) => ChannelChatScreen(channel: c.channels.first),
'Chess games sheet': (c) => ChannelChatScreen(channel: c.channels.first),
'ChessGame': (c) => ChessGameScreen(
channelId: c.channels.first.storageId!,
gameId: _chessGameId,
),
'ChannelMessagePath': (c) {
final msgs = c.getChannelMessages(c.channels.first);
return ChannelMessagePathScreen(message: msgs.last);
@@ -261,6 +334,7 @@ void main() {
'Map',
'Chat',
'ChannelChat',
'ChessGame',
'Settings',
}.contains(entry.key))
(entry, true),