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:
1 parent
9ac915bdf2
commit
185b026a0d
66 files changed
+15314
-25
No files matched your search
@@ -0,0 +1,450 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:chess/chess.dart' as rules;
|
||||
|
||||
import '../hash_chain.dart';
|
||||
import 'chess_packets.dart';
|
||||
import 'chess_position_codec.dart';
|
||||
|
||||
enum ChessSide {
|
||||
white,
|
||||
black;
|
||||
|
||||
ChessSide get other => this == white ? black : white;
|
||||
|
||||
/// Side that makes half-move [ply] (ply 1 is white's first move).
|
||||
static ChessSide moverOfPly(int ply) => ply.isOdd ? white : black;
|
||||
}
|
||||
|
||||
enum ChessGameStatus {
|
||||
/// An invite nobody has accepted yet.
|
||||
invite,
|
||||
|
||||
/// We accepted; waiting for the inviter's confirmation (a game info
|
||||
/// packet listing our commitment).
|
||||
starting,
|
||||
active,
|
||||
finished,
|
||||
}
|
||||
|
||||
enum ChessEndReason {
|
||||
checkmate,
|
||||
resignation,
|
||||
timeout,
|
||||
drawAgreed,
|
||||
stalemate,
|
||||
insufficientMaterial,
|
||||
fiftyMoves,
|
||||
repetition,
|
||||
cancelled,
|
||||
declined,
|
||||
expired,
|
||||
|
||||
/// Someone else's accept was confirmed for an invite we accepted.
|
||||
taken,
|
||||
}
|
||||
|
||||
/// One player's identity in a game: their name (unauthenticated) and the
|
||||
/// hash chain values verified so far.
|
||||
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;
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'name': name,
|
||||
'commitment': _hex(commitment),
|
||||
'last': _hex(lastValue),
|
||||
'index': lastIndex,
|
||||
};
|
||||
|
||||
static ChessPlayer? fromJson(Object? json) {
|
||||
if (json is! Map) return null;
|
||||
final name = json['name'];
|
||||
final commitment = _unhex(json['commitment']);
|
||||
if (name is! String || commitment == null) return null;
|
||||
return ChessPlayer(
|
||||
name: name,
|
||||
commitment: commitment,
|
||||
lastValue: _unhex(json['last']) ?? commitment,
|
||||
lastIndex: json['index'] is int ? json['index'] as int : 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// State of one chess game on one channel, as seen from this radio.
|
||||
class ChessGame {
|
||||
static const String startFen =
|
||||
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
|
||||
|
||||
final String channelId;
|
||||
final int gameId;
|
||||
|
||||
ChessGameStatus status;
|
||||
ChessDeadline deadline;
|
||||
ChessColourPreference colourPreference;
|
||||
|
||||
/// From the invite. Null when we only heard the game later.
|
||||
ChessPlayer? inviter;
|
||||
String? targetName;
|
||||
ChessPlayer? white;
|
||||
ChessPlayer? black;
|
||||
|
||||
/// Our own chain seed (hex) when we are a player or the inviter.
|
||||
String? mySeedHex;
|
||||
int myNextChainIndex;
|
||||
|
||||
/// Which side we play, or null when watching.
|
||||
ChessSide? mySide;
|
||||
|
||||
/// True when we posted the invite.
|
||||
bool iAmInviter;
|
||||
|
||||
/// Position the move history below starts from: the start position, or a
|
||||
/// position adopted after missed moves.
|
||||
String baseFen;
|
||||
List<String> uciSinceBase;
|
||||
|
||||
/// SAN of each half-move so far; null for moves we never heard.
|
||||
List<String?> sanMoves;
|
||||
int ply;
|
||||
String fen;
|
||||
|
||||
/// Whether [fen] is known. False for a game first heard through a game
|
||||
/// info packet, until a move arrives.
|
||||
bool hasPosition;
|
||||
String? lastMoveUci;
|
||||
|
||||
/// Latest move packet heard or sent, kept so any holder can re-send it.
|
||||
Uint8List? lastMovePacket;
|
||||
|
||||
ChessSide? drawOfferedBy;
|
||||
ChessSide? winner;
|
||||
ChessEndReason? endReason;
|
||||
|
||||
int createdAtMs;
|
||||
int? startedAtMs;
|
||||
int lastMoveAtMs;
|
||||
int lastActivityMs;
|
||||
int? lastAnsweredRequestAtMs;
|
||||
|
||||
rules.Chess? _board;
|
||||
|
||||
ChessGame({
|
||||
required this.channelId,
|
||||
required this.gameId,
|
||||
required this.status,
|
||||
required this.deadline,
|
||||
this.colourPreference = ChessColourPreference.random,
|
||||
this.inviter,
|
||||
this.targetName,
|
||||
this.white,
|
||||
this.black,
|
||||
this.mySeedHex,
|
||||
this.myNextChainIndex = 1,
|
||||
this.mySide,
|
||||
this.iAmInviter = false,
|
||||
String? baseFen,
|
||||
List<String>? uciSinceBase,
|
||||
List<String?>? sanMoves,
|
||||
this.ply = 0,
|
||||
String? fen,
|
||||
this.hasPosition = true,
|
||||
this.lastMoveUci,
|
||||
this.lastMovePacket,
|
||||
this.drawOfferedBy,
|
||||
this.winner,
|
||||
this.endReason,
|
||||
required this.createdAtMs,
|
||||
this.startedAtMs,
|
||||
int? lastMoveAtMs,
|
||||
int? lastActivityMs,
|
||||
this.lastAnsweredRequestAtMs,
|
||||
}) : baseFen = baseFen ?? startFen,
|
||||
uciSinceBase = uciSinceBase ?? <String>[],
|
||||
sanMoves = sanMoves ?? <String?>[],
|
||||
fen = fen ?? startFen,
|
||||
lastMoveAtMs = lastMoveAtMs ?? createdAtMs,
|
||||
lastActivityMs = lastActivityMs ?? createdAtMs;
|
||||
|
||||
String get key => gameKey(channelId, gameId);
|
||||
|
||||
static String gameKey(String channelId, int gameId) => '$channelId:$gameId';
|
||||
|
||||
bool get isPlayer => mySide != null;
|
||||
bool get isOpen => status != ChessGameStatus.finished;
|
||||
|
||||
/// Players are known (we can verify their actions).
|
||||
bool get hasPlayers => white != null && black != null;
|
||||
|
||||
ChessSide get sideToMove => ChessSide.moverOfPly(ply + 1);
|
||||
|
||||
bool get isMyTurn =>
|
||||
status == ChessGameStatus.active && hasPosition && mySide == sideToMove;
|
||||
|
||||
ChessPlayer? playerOf(ChessSide side) =>
|
||||
side == ChessSide.white ? white : black;
|
||||
|
||||
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;
|
||||
return null;
|
||||
}
|
||||
|
||||
HashChain? get myChain {
|
||||
final seed = _unhex(mySeedHex);
|
||||
return seed == null ? null : HashChain(seed);
|
||||
}
|
||||
|
||||
/// The next value of our chain, advancing the counter.
|
||||
Uint8List? takeMyChainValue() {
|
||||
final chain = myChain;
|
||||
if (chain == null || myNextChainIndex > HashChain.length) return null;
|
||||
return chain.valueAt(myNextChainIndex++);
|
||||
}
|
||||
|
||||
/// Rules engine at the current position, with as much history as we have
|
||||
/// (needed for repetition).
|
||||
rules.Chess get board {
|
||||
final cached = _board;
|
||||
if (cached != null) return cached;
|
||||
final b = rules.Chess.fromFEN(baseFen, check_validity: false);
|
||||
for (final uci in uciSinceBase) {
|
||||
final move = findLegalMove(b, uci);
|
||||
if (move == null) break;
|
||||
b.move(move);
|
||||
}
|
||||
if (b.fen != fen) {
|
||||
// History did not replay cleanly; fall back to the position alone.
|
||||
return _board = rules.Chess.fromFEN(fen, check_validity: false);
|
||||
}
|
||||
return _board = b;
|
||||
}
|
||||
|
||||
/// Legal moves in the current position as UCI strings, sorted. A move's
|
||||
/// index in this list is what a move packet carries.
|
||||
List<String> legalUci() => sortedLegalUci(board);
|
||||
|
||||
/// Applies the move with UCI [uci] by [side] as half-move [ply] + 1.
|
||||
/// Returns false when it is not legal.
|
||||
bool applyUci(String uci) {
|
||||
final b = board;
|
||||
final move = findLegalMove(b, uci);
|
||||
if (move == null) return false;
|
||||
final san = b.move_to_san(move);
|
||||
b.move(move);
|
||||
ply++;
|
||||
sanMoves.add(san);
|
||||
uciSinceBase.add(uci);
|
||||
fen = b.fen;
|
||||
lastMoveUci = uci;
|
||||
drawOfferedBy = null;
|
||||
_checkGameOver(b);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Takes [newFen] as the position after half-move [newPly], marking the
|
||||
/// moves in between as unknown.
|
||||
void adoptPosition(String newFen, int newPly) {
|
||||
while (sanMoves.length < newPly) {
|
||||
sanMoves.add(null);
|
||||
}
|
||||
if (sanMoves.length > newPly) sanMoves.removeRange(newPly, sanMoves.length);
|
||||
ply = newPly;
|
||||
baseFen = newFen;
|
||||
fen = newFen;
|
||||
uciSinceBase = <String>[];
|
||||
lastMoveUci = null;
|
||||
hasPosition = true;
|
||||
drawOfferedBy = null;
|
||||
_board = null;
|
||||
_checkGameOver(board);
|
||||
}
|
||||
|
||||
void _checkGameOver(rules.Chess b) {
|
||||
if (status != ChessGameStatus.active) return;
|
||||
ChessEndReason? reason;
|
||||
if (b.in_checkmate) {
|
||||
reason = ChessEndReason.checkmate;
|
||||
winner = ChessSide.moverOfPly(ply);
|
||||
} else if (b.in_stalemate) {
|
||||
reason = ChessEndReason.stalemate;
|
||||
} else if (b.insufficient_material) {
|
||||
reason = ChessEndReason.insufficientMaterial;
|
||||
} else if (b.half_moves >= 100) {
|
||||
reason = ChessEndReason.fiftyMoves;
|
||||
} else if (b.in_threefold_repetition) {
|
||||
reason = ChessEndReason.repetition;
|
||||
}
|
||||
if (reason != null) finish(reason, winner: winner);
|
||||
}
|
||||
|
||||
void finish(ChessEndReason reason, {ChessSide? winner}) {
|
||||
status = ChessGameStatus.finished;
|
||||
endReason = reason;
|
||||
this.winner = winner;
|
||||
drawOfferedBy = null;
|
||||
}
|
||||
|
||||
/// 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<String, dynamic> toJson() => {
|
||||
'channel': channelId,
|
||||
'id': gameId,
|
||||
'status': status.name,
|
||||
'deadline': deadline.code,
|
||||
'colour': colourPreference.code,
|
||||
if (inviter != null) 'inviter': inviter!.toJson(),
|
||||
if (targetName != null) 'target': targetName,
|
||||
if (white != null) 'white': white!.toJson(),
|
||||
if (black != null) 'black': black!.toJson(),
|
||||
if (mySeedHex != null) 'seed': mySeedHex,
|
||||
'nextChain': myNextChainIndex,
|
||||
if (mySide != null) 'side': mySide!.name,
|
||||
'inviterSelf': iAmInviter,
|
||||
'baseFen': baseFen,
|
||||
'uci': uciSinceBase,
|
||||
'san': sanMoves,
|
||||
'ply': ply,
|
||||
'fen': fen,
|
||||
'hasPosition': hasPosition,
|
||||
if (lastMoveUci != null) 'lastUci': lastMoveUci,
|
||||
if (lastMovePacket != null) 'lastPacket': base64Encode(lastMovePacket!),
|
||||
if (drawOfferedBy != null) 'draw': drawOfferedBy!.name,
|
||||
if (winner != null) 'winner': winner!.name,
|
||||
if (endReason != null) 'end': endReason!.name,
|
||||
'created': createdAtMs,
|
||||
if (startedAtMs != null) 'started': startedAtMs,
|
||||
'lastMove': lastMoveAtMs,
|
||||
'activity': lastActivityMs,
|
||||
};
|
||||
|
||||
static ChessGame? fromJson(Object? json) {
|
||||
if (json is! Map) return null;
|
||||
try {
|
||||
final channel = json['channel'];
|
||||
final id = json['id'];
|
||||
final created = json['created'];
|
||||
if (channel is! String || id is! int || created is! int) return null;
|
||||
final packet = json['lastPacket'];
|
||||
return ChessGame(
|
||||
channelId: channel,
|
||||
gameId: id,
|
||||
status: _enumByName(
|
||||
ChessGameStatus.values,
|
||||
json['status'],
|
||||
ChessGameStatus.finished,
|
||||
),
|
||||
deadline: ChessDeadline.fromCode(_int(json['deadline']) ?? 0),
|
||||
colourPreference: ChessColourPreference.fromCode(
|
||||
_int(json['colour']) ?? 0,
|
||||
),
|
||||
inviter: ChessPlayer.fromJson(json['inviter']),
|
||||
targetName: json['target'] as String?,
|
||||
white: ChessPlayer.fromJson(json['white']),
|
||||
black: ChessPlayer.fromJson(json['black']),
|
||||
mySeedHex: json['seed'] as String?,
|
||||
myNextChainIndex: _int(json['nextChain']) ?? 1,
|
||||
mySide: _enumByNameOrNull(ChessSide.values, json['side']),
|
||||
iAmInviter: json['inviterSelf'] == true,
|
||||
baseFen: json['baseFen'] as String?,
|
||||
uciSinceBase: (json['uci'] as List?)?.whereType<String>().toList(),
|
||||
sanMoves: (json['san'] as List?)?.map((e) => e as String?).toList(),
|
||||
ply: _int(json['ply']) ?? 0,
|
||||
fen: json['fen'] as String?,
|
||||
hasPosition: json['hasPosition'] != false,
|
||||
lastMoveUci: json['lastUci'] as String?,
|
||||
lastMovePacket: packet is String ? base64Decode(packet) : null,
|
||||
drawOfferedBy: _enumByNameOrNull(ChessSide.values, json['draw']),
|
||||
winner: _enumByNameOrNull(ChessSide.values, json['winner']),
|
||||
endReason: _enumByNameOrNull(ChessEndReason.values, json['end']),
|
||||
createdAtMs: created,
|
||||
startedAtMs: _int(json['started']),
|
||||
lastMoveAtMs: _int(json['lastMove']),
|
||||
lastActivityMs: _int(json['activity']),
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Legal moves of [board] as sorted UCI strings.
|
||||
List<String> sortedLegalUci(rules.Chess board) {
|
||||
final moves = board.moves({'asObjects': true}).cast<rules.Move>();
|
||||
return moves.map(moveToUci).toList()..sort();
|
||||
}
|
||||
|
||||
String moveToUci(rules.Move m) =>
|
||||
'${m.fromAlgebraic}${m.toAlgebraic}${m.promotion?.name ?? ''}';
|
||||
|
||||
rules.Move? findLegalMove(rules.Chess board, String uci) {
|
||||
for (final m in board.moves({'asObjects': true}).cast<rules.Move>()) {
|
||||
if (moveToUci(m) == uci) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Whether [fen] describes a position the rules engine accepts.
|
||||
bool isValidFen(String fen) => rules.Chess.validate_fen(fen)['valid'] == true;
|
||||
|
||||
int? _int(Object? v) => v is int ? v : null;
|
||||
|
||||
T _enumByName<T extends Enum>(List<T> values, Object? name, T fallback) =>
|
||||
_enumByNameOrNull(values, name) ?? fallback;
|
||||
|
||||
T? _enumByNameOrNull<T extends Enum>(List<T> values, Object? name) {
|
||||
if (name is! String) return null;
|
||||
for (final v in values) {
|
||||
if (v.name == name) return v;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _hex(List<int> bytes) =>
|
||||
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
Uint8List? _unhex(Object? hex) {
|
||||
if (hex is! String || hex.length.isOdd) return null;
|
||||
final out = Uint8List(hex.length ~/ 2);
|
||||
for (var i = 0; i < out.length; i++) {
|
||||
final v = int.tryParse(hex.substring(i * 2, i * 2 + 2), radix: 16);
|
||||
if (v == null) return null;
|
||||
out[i] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
String bytesToHex(List<int> bytes) => _hex(bytes);
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui' show Locale;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../../l10n/locale_tag.dart';
|
||||
import '../../services/app_settings_service.dart';
|
||||
import '../../services/image_chunk_transport.dart';
|
||||
import '../../services/notification_reply.dart';
|
||||
import '../../services/notification_service.dart';
|
||||
import '../../storage/prefs_manager.dart';
|
||||
import '../game_packet.dart';
|
||||
|
||||
/// A game payload heard on a channel.
|
||||
class ChessIncoming {
|
||||
final String channelId;
|
||||
final Uint8List payload;
|
||||
|
||||
const ChessIncoming(this.channelId, this.payload);
|
||||
}
|
||||
|
||||
/// What the chess service needs from the radio. [ConnectorChessLink] is the
|
||||
/// app's implementation; tests use an in-memory one.
|
||||
abstract class ChessLink implements Listenable {
|
||||
Stream<ChessIncoming> get incoming;
|
||||
|
||||
/// Sends [payload] on the channel with storage id [channelId].
|
||||
Future<bool> send(String channelId, Uint8List payload);
|
||||
|
||||
/// Our advert name.
|
||||
String get selfName;
|
||||
|
||||
/// Per-radio storage scope (10 hex chars), or '' when unknown.
|
||||
String get storageScope;
|
||||
|
||||
bool get canSend;
|
||||
|
||||
/// Shows a notification for a game event on [channelId], honouring the
|
||||
/// channel's notification mode.
|
||||
void notify(String channelId, String text);
|
||||
|
||||
/// Localized strings for notification text.
|
||||
AppLocalizations get l10n;
|
||||
}
|
||||
|
||||
/// [ChessLink] over [MeshCoreConnector]. Listens to the public frame stream
|
||||
/// for GRP_DATA with [meshcoreOpenDataType] and sends with
|
||||
/// [MeshCoreConnector.sendChannelData]; nothing else in the connector is
|
||||
/// involved.
|
||||
class ConnectorChessLink extends ChangeNotifier implements ChessLink {
|
||||
static const int _maxBuffered = 64;
|
||||
|
||||
final MeshCoreConnector connector;
|
||||
final AppSettingsService? settings;
|
||||
final StreamController<ChessIncoming> _incoming =
|
||||
StreamController<ChessIncoming>.broadcast();
|
||||
final List<ParsedChannelData> _awaitingMap = [];
|
||||
StreamSubscription<Uint8List>? _frames;
|
||||
String _lastScope = '';
|
||||
String _lastName = '';
|
||||
bool _lastCanSend = false;
|
||||
|
||||
ConnectorChessLink(this.connector, {this.settings}) {
|
||||
_frames = connector.receivedFrames.listen(_onFrame);
|
||||
connector.addListener(_onConnectorChanged);
|
||||
_lastScope = storageScope;
|
||||
_lastName = selfName;
|
||||
_lastCanSend = canSend;
|
||||
}
|
||||
|
||||
void _onFrame(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != respCodeChannelDataRecv) return;
|
||||
final parsed = parseChannelDataFrame(frame);
|
||||
if (parsed == null || parsed.dataType != meshcoreOpenDataType) return;
|
||||
if (GamePacketHeader.appOf(parsed.payload) != GameApp.chess) return;
|
||||
if (!connector.channelMapConfirmed) {
|
||||
// Slot numbers are not trustworthy until the channel list is loaded.
|
||||
if (_awaitingMap.length >= _maxBuffered) _awaitingMap.removeAt(0);
|
||||
_awaitingMap.add(parsed);
|
||||
return;
|
||||
}
|
||||
_emit(parsed);
|
||||
}
|
||||
|
||||
void _emit(ParsedChannelData parsed) {
|
||||
final channelId = connector.channelIdForSlot(parsed.channelIndex);
|
||||
if (channelId == null) return;
|
||||
_incoming.add(ChessIncoming(channelId, parsed.payload));
|
||||
}
|
||||
|
||||
void _onConnectorChanged() {
|
||||
if (connector.channelMapConfirmed && _awaitingMap.isNotEmpty) {
|
||||
final pending = List.of(_awaitingMap);
|
||||
_awaitingMap.clear();
|
||||
pending.forEach(_emit);
|
||||
}
|
||||
final scope = storageScope;
|
||||
final name = selfName;
|
||||
final can = canSend;
|
||||
if (scope != _lastScope || name != _lastName || can != _lastCanSend) {
|
||||
_lastScope = scope;
|
||||
_lastName = name;
|
||||
_lastCanSend = can;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<ChessIncoming> get incoming => _incoming.stream;
|
||||
|
||||
@override
|
||||
Future<bool> send(String channelId, Uint8List payload) async {
|
||||
final slot = connector.channels
|
||||
.where((c) => c.storageId == channelId)
|
||||
.map((c) => c.index)
|
||||
.firstOrNull;
|
||||
if (slot == null) return false;
|
||||
try {
|
||||
return await connector.sendChannelData(
|
||||
channelIndex: slot,
|
||||
dataType: meshcoreOpenDataType,
|
||||
payload: payload,
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String get selfName => connector.selfName ?? '';
|
||||
|
||||
@override
|
||||
String get storageScope {
|
||||
final key = connector.storageKeyHex;
|
||||
return key.length >= 10 ? key.substring(0, 10) : '';
|
||||
}
|
||||
|
||||
@override
|
||||
bool get canSend => connector.supportsChannelData;
|
||||
|
||||
@override
|
||||
void notify(String channelId, String text) {
|
||||
final s = settings?.settings;
|
||||
if (s == null || !s.notificationsEnabled || !s.notifyOnNewChannelMessage) {
|
||||
return;
|
||||
}
|
||||
final channel = connector.channels
|
||||
.where((c) => c.storageId == channelId)
|
||||
.firstOrNull;
|
||||
if (channel == null) return;
|
||||
final mode = settings!.getChannelNotificationMode(channel.muteKey);
|
||||
if (mode == ChannelNotificationMode.muted) return;
|
||||
unawaited(
|
||||
NotificationService().showChannelMessageNotification(
|
||||
channelName: channel.muteKey,
|
||||
senderName: l10n.chess_notificationSender,
|
||||
message: text,
|
||||
urlImagesEnabled: false,
|
||||
channelIndex: channel.index,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
AppLocalizations get l10n {
|
||||
try {
|
||||
final tag = PrefsManager.instance.getString(notificationLanguagePrefsKey);
|
||||
if (tag != null && tag.isNotEmpty) {
|
||||
return lookupAppLocalizations(localeFromTag(tag));
|
||||
}
|
||||
} catch (_) {}
|
||||
return lookupAppLocalizations(const Locale('en'));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_frames?.cancel();
|
||||
connector.removeListener(_onConnectorChanged);
|
||||
_incoming.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../game_packet.dart';
|
||||
import '../hash_chain.dart';
|
||||
|
||||
/// Packet kinds of chess v1 (the low nibble of the first payload byte).
|
||||
enum ChessPacketKind {
|
||||
invite(0),
|
||||
accept(1),
|
||||
decline(2),
|
||||
move(3),
|
||||
resign(4),
|
||||
drawOffer(5),
|
||||
drawAccept(6),
|
||||
cancel(7),
|
||||
timeoutClaim(8),
|
||||
info(9),
|
||||
request(10);
|
||||
|
||||
final int code;
|
||||
const ChessPacketKind(this.code);
|
||||
|
||||
static ChessPacketKind? fromCode(int code) {
|
||||
for (final k in values) {
|
||||
if (k.code == code) return k;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour the inviter wants to play.
|
||||
enum ChessColourPreference {
|
||||
random(0),
|
||||
white(1),
|
||||
black(2);
|
||||
|
||||
final int code;
|
||||
const ChessColourPreference(this.code);
|
||||
|
||||
static ChessColourPreference fromCode(int code) =>
|
||||
values.firstWhere((v) => v.code == code, orElse: () => random);
|
||||
}
|
||||
|
||||
/// Per-move deadline choices, carried as one byte.
|
||||
enum ChessDeadline {
|
||||
none(0, null),
|
||||
min15(1, Duration(minutes: 15)),
|
||||
hour1(2, Duration(hours: 1)),
|
||||
hours6(3, Duration(hours: 6)),
|
||||
day1(4, Duration(days: 1)),
|
||||
days3(5, Duration(days: 3));
|
||||
|
||||
final int code;
|
||||
final Duration? duration;
|
||||
const ChessDeadline(this.code, this.duration);
|
||||
|
||||
static const ChessDeadline defaultValue = hour1;
|
||||
|
||||
static ChessDeadline fromCode(int code) =>
|
||||
values.firstWhere((v) => v.code == code, orElse: () => defaultValue);
|
||||
}
|
||||
|
||||
/// A decoded chess packet. [ply] is the half-move number modulo 256.
|
||||
sealed class ChessPacket {
|
||||
final int gameId;
|
||||
final int ply;
|
||||
|
||||
const ChessPacket({required this.gameId, required this.ply});
|
||||
|
||||
ChessPacketKind get kind;
|
||||
|
||||
Uint8List encode() {
|
||||
final out = BytesBuilder();
|
||||
GamePacketHeader(
|
||||
app: GameApp.chess,
|
||||
kind: kind.code,
|
||||
gameId: gameId,
|
||||
ply: ply,
|
||||
).writeTo(out);
|
||||
writeBody(out);
|
||||
return out.toBytes();
|
||||
}
|
||||
|
||||
void writeBody(BytesBuilder out);
|
||||
|
||||
/// Decodes a chess payload, or null when it is not one or is malformed.
|
||||
static ChessPacket? decode(Uint8List payload) {
|
||||
final header = GamePacketHeader.parse(payload);
|
||||
if (header == null || header.app != GameApp.chess) return null;
|
||||
final kind = ChessPacketKind.fromCode(header.kind);
|
||||
if (kind == null) return null;
|
||||
final r = GamePacketReader(payload, GamePacketHeader.length);
|
||||
final id = header.gameId;
|
||||
final ply = header.ply;
|
||||
final ChessPacket? packet = switch (kind) {
|
||||
ChessPacketKind.invite => ChessInvitePacket._read(id, ply, r),
|
||||
ChessPacketKind.accept => ChessAcceptPacket._read(id, ply, r),
|
||||
ChessPacketKind.decline => ChessDeclinePacket._read(id, ply, r),
|
||||
ChessPacketKind.move => ChessMovePacket._read(id, ply, r),
|
||||
ChessPacketKind.resign ||
|
||||
ChessPacketKind.drawOffer ||
|
||||
ChessPacketKind.drawAccept ||
|
||||
ChessPacketKind.cancel ||
|
||||
ChessPacketKind.timeoutClaim => ChessActionPacket._read(kind, id, ply, r),
|
||||
ChessPacketKind.info => ChessInfoPacket._read(id, ply, r),
|
||||
ChessPacketKind.request => ChessRequestPacket._read(id, ply, r),
|
||||
};
|
||||
if (packet == null || r.failed) return null;
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open invite, or a direct challenge when [targetName] is set.
|
||||
class ChessInvitePacket extends ChessPacket {
|
||||
final ChessDeadline deadline;
|
||||
final ChessColourPreference colour;
|
||||
final Uint8List commitment;
|
||||
final String inviterName;
|
||||
final String? targetName;
|
||||
|
||||
const ChessInvitePacket({
|
||||
required super.gameId,
|
||||
required this.deadline,
|
||||
required this.colour,
|
||||
required this.commitment,
|
||||
required this.inviterName,
|
||||
this.targetName,
|
||||
}) : super(ply: 0);
|
||||
|
||||
bool get isDirect => targetName != null;
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.invite;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) {
|
||||
out
|
||||
..addByte(deadline.code)
|
||||
..addByte(colour.code | (isDirect ? 0x04 : 0))
|
||||
..add(commitment);
|
||||
writeShortString(out, inviterName);
|
||||
if (targetName != null) writeShortString(out, targetName!);
|
||||
}
|
||||
|
||||
static ChessInvitePacket? _read(int id, int ply, GamePacketReader r) {
|
||||
final deadline = r.u8();
|
||||
final flags = r.u8();
|
||||
final commitment = r.bytes(HashChain.valueBytes);
|
||||
final name = r.shortString();
|
||||
if (deadline == null || flags == null || commitment == null) return null;
|
||||
if (name == null) return null;
|
||||
String? target;
|
||||
if (flags & 0x04 != 0) {
|
||||
target = r.shortString();
|
||||
if (target == null) return null;
|
||||
}
|
||||
return ChessInvitePacket(
|
||||
gameId: id,
|
||||
deadline: ChessDeadline.fromCode(deadline),
|
||||
colour: ChessColourPreference.fromCode(flags & 0x03),
|
||||
commitment: commitment,
|
||||
inviterName: name,
|
||||
targetName: target,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChessAcceptPacket extends ChessPacket {
|
||||
final Uint8List commitment;
|
||||
final String accepterName;
|
||||
|
||||
const ChessAcceptPacket({
|
||||
required super.gameId,
|
||||
required this.commitment,
|
||||
required this.accepterName,
|
||||
}) : super(ply: 0);
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.accept;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) {
|
||||
out.add(commitment);
|
||||
writeShortString(out, accepterName);
|
||||
}
|
||||
|
||||
static ChessAcceptPacket? _read(int id, int ply, GamePacketReader r) {
|
||||
final commitment = r.bytes(HashChain.valueBytes);
|
||||
final name = r.shortString();
|
||||
if (commitment == null || name == null) return null;
|
||||
return ChessAcceptPacket(
|
||||
gameId: id,
|
||||
commitment: commitment,
|
||||
accepterName: name,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A declined direct challenge. Not authenticated; only the inviter acts on
|
||||
/// it, and only for a challenge addressed to [declinerName].
|
||||
class ChessDeclinePacket extends ChessPacket {
|
||||
final String declinerName;
|
||||
|
||||
const ChessDeclinePacket({required super.gameId, required this.declinerName})
|
||||
: super(ply: 0);
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.decline;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) => writeShortString(out, declinerName);
|
||||
|
||||
static ChessDeclinePacket? _read(int id, int ply, GamePacketReader r) {
|
||||
final name = r.shortString();
|
||||
if (name == null) return null;
|
||||
return ChessDeclinePacket(gameId: id, declinerName: name);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
const ChessMovePacket({
|
||||
required super.gameId,
|
||||
required super.ply,
|
||||
required this.minutes,
|
||||
required this.moveIndex,
|
||||
required this.chainValue,
|
||||
required this.position,
|
||||
});
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.move;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) {
|
||||
writeU16(out, minutes);
|
||||
out
|
||||
..addByte(moveIndex)
|
||||
..add(chainValue)
|
||||
..add(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 (position == null || position.isEmpty) return null;
|
||||
return ChessMovePacket(
|
||||
gameId: id,
|
||||
ply: ply,
|
||||
minutes: minutes,
|
||||
moveIndex: index,
|
||||
chainValue: chain,
|
||||
position: position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resign, draw offer, draw accept, cancel invite or timeout claim: an
|
||||
/// authenticated action with no other data.
|
||||
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);
|
||||
}
|
||||
|
||||
static ChessActionPacket? _read(
|
||||
ChessPacketKind kind,
|
||||
int id,
|
||||
int ply,
|
||||
GamePacketReader r,
|
||||
) {
|
||||
final minutes = r.u16();
|
||||
final chain = r.bytes(HashChain.valueBytes);
|
||||
if (minutes == null || 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.
|
||||
class ChessInfoPacket extends ChessPacket {
|
||||
final int startedAtUnix;
|
||||
final ChessDeadline deadline;
|
||||
final Uint8List whiteCommitment;
|
||||
final Uint8List blackCommitment;
|
||||
final String whiteName;
|
||||
final String blackName;
|
||||
|
||||
const ChessInfoPacket({
|
||||
required super.gameId,
|
||||
required super.ply,
|
||||
required this.startedAtUnix,
|
||||
required this.deadline,
|
||||
required this.whiteCommitment,
|
||||
required this.blackCommitment,
|
||||
required this.whiteName,
|
||||
required this.blackName,
|
||||
});
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.info;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) {
|
||||
writeU32(out, startedAtUnix);
|
||||
out
|
||||
..addByte(deadline.code)
|
||||
..addByte(0) // flags, reserved
|
||||
..add(whiteCommitment)
|
||||
..add(blackCommitment);
|
||||
writeShortString(out, whiteName);
|
||||
writeShortString(out, blackName);
|
||||
}
|
||||
|
||||
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 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;
|
||||
return ChessInfoPacket(
|
||||
gameId: id,
|
||||
ply: ply,
|
||||
startedAtUnix: started,
|
||||
deadline: ChessDeadline.fromCode(deadline),
|
||||
whiteCommitment: white,
|
||||
blackCommitment: black,
|
||||
whiteName: whiteName,
|
||||
blackName: blackName,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the players for the game info and/or the latest move. [ply] is the
|
||||
/// last half-move the requester has.
|
||||
class ChessRequestPacket extends ChessPacket {
|
||||
final bool wantsInfo;
|
||||
final bool wantsLatestMove;
|
||||
|
||||
const ChessRequestPacket({
|
||||
required super.gameId,
|
||||
required super.ply,
|
||||
this.wantsInfo = false,
|
||||
this.wantsLatestMove = false,
|
||||
});
|
||||
|
||||
@override
|
||||
ChessPacketKind get kind => ChessPacketKind.request;
|
||||
|
||||
@override
|
||||
void writeBody(BytesBuilder out) =>
|
||||
out.addByte((wantsInfo ? 1 : 0) | (wantsLatestMove ? 2 : 0));
|
||||
|
||||
static ChessRequestPacket? _read(int id, int ply, GamePacketReader r) {
|
||||
final flags = r.u8();
|
||||
if (flags == null) return null;
|
||||
return ChessRequestPacket(
|
||||
gameId: id,
|
||||
ply: ply,
|
||||
wantsInfo: flags & 1 != 0,
|
||||
wantsLatestMove: flags & 2 != 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// Packs a chess position into at most [maxBytes] bytes and back.
|
||||
///
|
||||
/// Layout:
|
||||
/// * 8 bytes: occupancy bitboard, bit `i` = square `i` (a1 = 0 … h8 = 63),
|
||||
/// byte `i >> 3`, bit `i & 7`.
|
||||
/// * 2 bytes (LE): bit 0 black to move, bits 1–4 castling K Q k q,
|
||||
/// bits 5–8 en-passant file + 1 (0 = none), bits 9–15 halfmove clock
|
||||
/// (capped at 127).
|
||||
/// * One nibble per occupied square in square order, high nibble first:
|
||||
/// bit 3 black, bits 0–2 piece (pawn 0, knight 1, bishop 2, rook 3,
|
||||
/// queen 4, king 5). Padded with a zero nibble to a whole byte.
|
||||
///
|
||||
/// The full-move number is not packed; it follows from the game's ply.
|
||||
abstract final class ChessPositionCodec {
|
||||
static const int maxBytes = 26;
|
||||
static const int _fixedBytes = 10;
|
||||
static const String _pieces = 'pnbrqk';
|
||||
|
||||
/// Packs the first four FEN fields plus the halfmove clock of [fen].
|
||||
/// Throws [FormatException] for a malformed FEN.
|
||||
static Uint8List encodeFen(String fen) {
|
||||
final fields = fen.trim().split(RegExp(r'\s+'));
|
||||
if (fields.length < 4) throw FormatException('Bad FEN', fen);
|
||||
final ranks = fields[0].split('/');
|
||||
if (ranks.length != 8) throw FormatException('Bad FEN board', fen);
|
||||
|
||||
final occupancy = Uint8List(8);
|
||||
final nibbles = <int>[];
|
||||
final squares = List<int?>.filled(64, null);
|
||||
for (var r = 0; r < 8; r++) {
|
||||
final rank = 7 - r; // FEN lists rank 8 first.
|
||||
var file = 0;
|
||||
for (final ch in ranks[r].split('')) {
|
||||
final digit = int.tryParse(ch);
|
||||
if (digit != null) {
|
||||
file += digit;
|
||||
continue;
|
||||
}
|
||||
final type = _pieces.indexOf(ch.toLowerCase());
|
||||
if (type < 0 || file > 7) throw FormatException('Bad piece', fen);
|
||||
final black = ch == ch.toLowerCase();
|
||||
squares[rank * 8 + file] = (black ? 8 : 0) | type;
|
||||
file++;
|
||||
}
|
||||
if (file != 8) throw FormatException('Bad rank', fen);
|
||||
}
|
||||
for (var sq = 0; sq < 64; sq++) {
|
||||
final piece = squares[sq];
|
||||
if (piece == null) continue;
|
||||
occupancy[sq >> 3] |= 1 << (sq & 7);
|
||||
nibbles.add(piece);
|
||||
}
|
||||
if (nibbles.length > 32) throw FormatException('Too many pieces', fen);
|
||||
|
||||
var state = fields[1] == 'b' ? 1 : 0;
|
||||
final castling = fields[2];
|
||||
if (castling.contains('K')) state |= 1 << 1;
|
||||
if (castling.contains('Q')) state |= 1 << 2;
|
||||
if (castling.contains('k')) state |= 1 << 3;
|
||||
if (castling.contains('q')) state |= 1 << 4;
|
||||
final ep = fields[3];
|
||||
if (ep != '-') {
|
||||
final file = ep.codeUnitAt(0) - 'a'.codeUnitAt(0);
|
||||
if (file < 0 || file > 7) throw FormatException('Bad en passant', fen);
|
||||
state |= (file + 1) << 5;
|
||||
}
|
||||
final halfmove = fields.length > 4 ? int.tryParse(fields[4]) ?? 0 : 0;
|
||||
state |= (halfmove.clamp(0, 127)) << 9;
|
||||
|
||||
final out = BytesBuilder()
|
||||
..add(occupancy)
|
||||
..addByte(state & 0xFF)
|
||||
..addByte((state >> 8) & 0xFF);
|
||||
for (var i = 0; i < nibbles.length; i += 2) {
|
||||
final hi = nibbles[i];
|
||||
final lo = i + 1 < nibbles.length ? nibbles[i + 1] : 0;
|
||||
out.addByte((hi << 4) | lo);
|
||||
}
|
||||
return out.toBytes();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
static String? decodeToFen(Uint8List bytes, {required int fullMoveNumber}) {
|
||||
if (bytes.length < _fixedBytes) return null;
|
||||
final squares = <int>[];
|
||||
for (var sq = 0; sq < 64; sq++) {
|
||||
if (bytes[sq >> 3] & (1 << (sq & 7)) != 0) squares.add(sq);
|
||||
}
|
||||
if (squares.length > 32) return null;
|
||||
if (bytes.length != _fixedBytes + (squares.length + 1) ~/ 2) return null;
|
||||
|
||||
final board = List<String?>.filled(64, null);
|
||||
for (var i = 0; i < squares.length; i++) {
|
||||
final byte = bytes[_fixedBytes + (i >> 1)];
|
||||
final nibble = i.isEven ? byte >> 4 : byte & 0x0F;
|
||||
final type = nibble & 0x07;
|
||||
if (type > 5) return null;
|
||||
final letter = _pieces[type];
|
||||
board[squares[i]] = nibble & 0x08 != 0 ? letter : letter.toUpperCase();
|
||||
}
|
||||
|
||||
final rows = <String>[];
|
||||
for (var rank = 7; rank >= 0; rank--) {
|
||||
final row = StringBuffer();
|
||||
var empty = 0;
|
||||
for (var file = 0; file < 8; file++) {
|
||||
final p = board[rank * 8 + file];
|
||||
if (p == null) {
|
||||
empty++;
|
||||
continue;
|
||||
}
|
||||
if (empty > 0) row.write(empty);
|
||||
empty = 0;
|
||||
row.write(p);
|
||||
}
|
||||
if (empty > 0) row.write(empty);
|
||||
rows.add(row.toString());
|
||||
}
|
||||
|
||||
final state = bytes[8] | (bytes[9] << 8);
|
||||
final blackToMove = state & 1 != 0;
|
||||
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');
|
||||
final epFile = (state >> 5) & 0x0F;
|
||||
if (epFile > 8) return null;
|
||||
final ep = epFile == 0
|
||||
? '-'
|
||||
: '${String.fromCharCode('a'.codeUnitAt(0) + epFile - 1)}'
|
||||
'${blackToMove ? 3 : 6}';
|
||||
final halfmove = (state >> 9) & 0x7F;
|
||||
|
||||
return '${rows.join('/')} ${blackToMove ? 'b' : 'w'} '
|
||||
'${castling.isEmpty ? '-' : castling} $ep $halfmove '
|
||||
'${fullMoveNumber < 1 ? 1 : fullMoveNumber}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,843 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../hash_chain.dart';
|
||||
import 'chess_game.dart';
|
||||
import 'chess_link.dart';
|
||||
import 'chess_packets.dart';
|
||||
import 'chess_position_codec.dart';
|
||||
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.
|
||||
class ChessService extends ChangeNotifier {
|
||||
static const Duration inviteLifetime = Duration(hours: 24);
|
||||
static const Duration timeoutGrace = Duration(minutes: 10);
|
||||
static const Duration keepFinished = Duration(days: 7);
|
||||
static const Duration requestAnswerInterval = Duration(minutes: 1);
|
||||
static const int maxStoredGames = 50;
|
||||
|
||||
final ChessLink link;
|
||||
final ChessStore store;
|
||||
final DateTime Function() _clock;
|
||||
final Random _random;
|
||||
final Duration _answerDelayMin;
|
||||
final Duration _answerDelayMax;
|
||||
|
||||
final Map<String, ChessGame> _games = {};
|
||||
final Set<String> _sending = {};
|
||||
final Map<String, Timer> _pendingAnswers = {};
|
||||
StreamSubscription<ChessIncoming>? _sub;
|
||||
Timer? _housekeeping;
|
||||
String _scope = '';
|
||||
String? _viewingKey;
|
||||
bool _disposed = false;
|
||||
|
||||
ChessService({
|
||||
required this.link,
|
||||
ChessStore? store,
|
||||
DateTime Function()? clock,
|
||||
Random? random,
|
||||
Duration answerDelayMin = const Duration(seconds: 2),
|
||||
Duration answerDelayMax = const Duration(seconds: 10),
|
||||
bool startHousekeeping = true,
|
||||
}) : store = store ?? ChessStore(),
|
||||
_clock = clock ?? DateTime.now,
|
||||
_random = random ?? Random.secure(),
|
||||
_answerDelayMin = answerDelayMin,
|
||||
_answerDelayMax = answerDelayMax {
|
||||
_sub = link.incoming.listen(handleIncoming);
|
||||
link.addListener(_onLinkChanged);
|
||||
_loadScope(link.storageScope);
|
||||
if (startHousekeeping) {
|
||||
_housekeeping = Timer.periodic(
|
||||
const Duration(minutes: 1),
|
||||
(_) => housekeeping(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
int get _now => _clock().millisecondsSinceEpoch;
|
||||
|
||||
// ---- queries ---------------------------------------------------------------
|
||||
|
||||
/// Games on [channelId], newest activity first.
|
||||
List<ChessGame> gamesForChannel(String channelId) =>
|
||||
_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;
|
||||
|
||||
ChessGame? game(String channelId, int gameId) =>
|
||||
_games[ChessGame.gameKey(channelId, gameId)];
|
||||
|
||||
bool isSending(ChessGame game) => _sending.contains(game.key);
|
||||
|
||||
bool get canSend => link.canSend;
|
||||
|
||||
String get selfName => link.selfName;
|
||||
|
||||
/// When the side to move runs out of time, or null without a deadline.
|
||||
DateTime? deadlineAt(ChessGame game) {
|
||||
final d = game.deadline.duration;
|
||||
if (d == null || game.status != ChessGameStatus.active) return null;
|
||||
return DateTime.fromMillisecondsSinceEpoch(game.lastMoveAtMs).add(d);
|
||||
}
|
||||
|
||||
/// True when we may claim a win because the opponent let the deadline
|
||||
/// (plus grace) pass.
|
||||
bool canClaimTimeout(ChessGame game) {
|
||||
if (!game.isPlayer || game.isMyTurn) return false;
|
||||
if (game.status != ChessGameStatus.active) return false;
|
||||
final at = deadlineAt(game);
|
||||
return at != null && _clock().isAfter(at.add(timeoutGrace));
|
||||
}
|
||||
|
||||
/// The screen showing [game] (no notifications for it), or null.
|
||||
set viewing(ChessGame? game) => _viewingKey = game?.key;
|
||||
|
||||
// ---- our actions -----------------------------------------------------------
|
||||
|
||||
/// Posts an open invite, or a direct challenge to [targetName].
|
||||
Future<ChessGame?> createInvite({
|
||||
required String channelId,
|
||||
ChessDeadline deadline = ChessDeadline.defaultValue,
|
||||
ChessColourPreference colour = ChessColourPreference.random,
|
||||
String? targetName,
|
||||
}) async {
|
||||
final chain = HashChain.generate(_random);
|
||||
final gameId = _newGameId(channelId);
|
||||
final packet = ChessInvitePacket(
|
||||
gameId: gameId,
|
||||
deadline: deadline,
|
||||
colour: colour,
|
||||
commitment: chain.commitment,
|
||||
inviterName: link.selfName,
|
||||
targetName: targetName,
|
||||
);
|
||||
final game = ChessGame(
|
||||
channelId: channelId,
|
||||
gameId: gameId,
|
||||
status: ChessGameStatus.invite,
|
||||
deadline: deadline,
|
||||
colourPreference: colour,
|
||||
inviter: ChessPlayer(name: link.selfName, commitment: chain.commitment),
|
||||
targetName: targetName,
|
||||
mySeedHex: bytesToHex(chain.seed),
|
||||
iAmInviter: true,
|
||||
createdAtMs: _now,
|
||||
);
|
||||
if (!await _send(game, packet)) return null;
|
||||
_games[game.key] = game;
|
||||
_changed();
|
||||
return game;
|
||||
}
|
||||
|
||||
Future<bool> 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;
|
||||
game
|
||||
..mySeedHex = bytesToHex(chain.seed)
|
||||
..myNextChainIndex = 1
|
||||
..status = ChessGameStatus.starting
|
||||
..lastActivityMs = _now;
|
||||
_changed();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Re-sends our accept while waiting for the inviter's confirmation.
|
||||
Future<bool> resendAccept(ChessGame game) async {
|
||||
if (game.status != ChessGameStatus.starting) return false;
|
||||
final chain = game.myChain;
|
||||
if (chain == null) return false;
|
||||
return _send(
|
||||
game,
|
||||
ChessAcceptPacket(
|
||||
gameId: game.gameId,
|
||||
commitment: chain.commitment,
|
||||
accepterName: link.selfName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> decline(ChessGame game) async {
|
||||
if (game.status != ChessGameStatus.invite || game.iAmInviter) return false;
|
||||
final ok = await _send(
|
||||
game,
|
||||
ChessDeclinePacket(gameId: game.gameId, declinerName: link.selfName),
|
||||
);
|
||||
if (ok) {
|
||||
game.finish(ChessEndReason.declined);
|
||||
_touch(game);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
Future<bool> cancelInvite(ChessGame game) =>
|
||||
_sendAction(game, ChessPacketKind.cancel, (g, _) {
|
||||
g.finish(ChessEndReason.cancelled);
|
||||
}, allowedStatus: ChessGameStatus.invite);
|
||||
|
||||
/// Plays [uci] (e.g. `e2e4`, `e7e8q`).
|
||||
Future<bool> makeMove(ChessGame game, String uci) async {
|
||||
if (!game.isMyTurn || isSending(game)) 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);
|
||||
final packet = ChessMovePacket(
|
||||
gameId: game.gameId,
|
||||
ply: probe.ply & 0xFF,
|
||||
minutes: game.minutesSinceStart(_now),
|
||||
moveIndex: index,
|
||||
chainValue: value,
|
||||
position: probe.packedPosition(),
|
||||
);
|
||||
if (!await _send(game, packet)) {
|
||||
game.myNextChainIndex--;
|
||||
return false;
|
||||
}
|
||||
game.applyUci(uci);
|
||||
game.playerOf(game.mySide!)?.verifyAndAdvance(value);
|
||||
game
|
||||
..lastMovePacket = packet.encode()
|
||||
..lastMoveAtMs = _now;
|
||||
_touch(game);
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<bool> resign(ChessGame game) =>
|
||||
_sendAction(game, ChessPacketKind.resign, (g, side) {
|
||||
g.finish(ChessEndReason.resignation, winner: side.other);
|
||||
});
|
||||
|
||||
Future<bool> offerDraw(ChessGame game) =>
|
||||
_sendAction(game, ChessPacketKind.drawOffer, (g, side) {
|
||||
g.drawOfferedBy = side;
|
||||
});
|
||||
|
||||
Future<bool> acceptDraw(ChessGame game) {
|
||||
if (game.drawOfferedBy == null || game.drawOfferedBy == game.mySide) {
|
||||
return Future.value(false);
|
||||
}
|
||||
return _sendAction(game, ChessPacketKind.drawAccept, (g, _) {
|
||||
g.finish(ChessEndReason.drawAgreed);
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> claimTimeout(ChessGame game) {
|
||||
if (!canClaimTimeout(game)) return Future.value(false);
|
||||
return _sendAction(game, ChessPacketKind.timeoutClaim, (g, side) {
|
||||
g.finish(ChessEndReason.timeout, winner: side);
|
||||
});
|
||||
}
|
||||
|
||||
/// Asks the players for whatever we are missing: the game info when we
|
||||
/// cannot verify the players, the latest move otherwise.
|
||||
Future<bool> requestUpdate(ChessGame game) {
|
||||
if (game.status == ChessGameStatus.starting) return resendAccept(game);
|
||||
return _send(
|
||||
game,
|
||||
ChessRequestPacket(
|
||||
gameId: game.gameId,
|
||||
ply: game.ply & 0xFF,
|
||||
wantsInfo: !game.hasPlayers,
|
||||
wantsLatestMove: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Forgets a finished game or an invite we only watched.
|
||||
void remove(ChessGame game) {
|
||||
if (_games.remove(game.key) != null) _changed();
|
||||
}
|
||||
|
||||
Future<bool> _sendAction(
|
||||
ChessGame game,
|
||||
ChessPacketKind kind,
|
||||
void Function(ChessGame game, ChessSide side) apply, {
|
||||
ChessGameStatus allowedStatus = ChessGameStatus.active,
|
||||
}) async {
|
||||
if (game.status != allowedStatus || isSending(game)) 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,
|
||||
);
|
||||
if (!await _send(game, packet)) {
|
||||
game.myNextChainIndex--;
|
||||
return false;
|
||||
}
|
||||
if (side != null) {
|
||||
game.playerOf(side)?.verifyAndAdvance(value);
|
||||
apply(game, side);
|
||||
} else {
|
||||
game.inviter?.verifyAndAdvance(value);
|
||||
apply(game, ChessSide.white);
|
||||
}
|
||||
_touch(game);
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<bool> _send(ChessGame game, ChessPacket packet) async {
|
||||
if (!link.canSend) return false;
|
||||
_sending.add(game.key);
|
||||
notifyListeners();
|
||||
try {
|
||||
return await link.send(game.channelId, packet.encode());
|
||||
} finally {
|
||||
_sending.remove(game.key);
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
int _newGameId(String channelId) {
|
||||
while (true) {
|
||||
final id = _random.nextInt(0x10000);
|
||||
if (!_games.containsKey(ChessGame.gameKey(channelId, id))) return id;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- incoming --------------------------------------------------------------
|
||||
|
||||
@visibleForTesting
|
||||
void handleIncoming(ChessIncoming incoming) {
|
||||
final packet = ChessPacket.decode(incoming.payload);
|
||||
if (packet == null) return;
|
||||
final channelId = incoming.channelId;
|
||||
final existing = game(channelId, packet.gameId);
|
||||
final changed = switch (packet) {
|
||||
ChessInvitePacket p => _onInvite(channelId, existing, p),
|
||||
ChessAcceptPacket p => _onAccept(existing, p),
|
||||
ChessDeclinePacket p => _onDecline(existing, p),
|
||||
ChessMovePacket p => _onMove(channelId, existing, p, incoming.payload),
|
||||
ChessActionPacket p => _onAction(existing, p),
|
||||
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();
|
||||
}
|
||||
|
||||
bool _onInvite(String channelId, ChessGame? existing, ChessInvitePacket p) {
|
||||
if (existing != null) return false;
|
||||
final game = ChessGame(
|
||||
channelId: channelId,
|
||||
gameId: p.gameId,
|
||||
status: ChessGameStatus.invite,
|
||||
deadline: p.deadline,
|
||||
colourPreference: p.colour,
|
||||
inviter: ChessPlayer(name: p.inviterName, commitment: p.commitment),
|
||||
targetName: p.targetName,
|
||||
createdAtMs: _now,
|
||||
);
|
||||
_games[game.key] = game;
|
||||
if (_isMe(p.targetName)) {
|
||||
_notify(game, link.l10n.chess_notifyChallenge(p.inviterName));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (game.status != ChessGameStatus.invite) return false;
|
||||
final target = game.targetName;
|
||||
if (target != null && !_sameName(target, p.accepterName)) return false;
|
||||
final inviter = game.inviter;
|
||||
if (inviter == null) return false;
|
||||
|
||||
if (game.iAmInviter) {
|
||||
final inviterWhite = _inviterIsWhite(
|
||||
game.colourPreference,
|
||||
inviter.commitment,
|
||||
p.commitment,
|
||||
);
|
||||
final accepter = ChessPlayer(
|
||||
name: p.accepterName,
|
||||
commitment: p.commitment,
|
||||
);
|
||||
_start(
|
||||
game,
|
||||
white: inviterWhite ? inviter : accepter,
|
||||
black: inviterWhite ? accepter : inviter,
|
||||
mySide: inviterWhite ? ChessSide.white : ChessSide.black,
|
||||
);
|
||||
// Confirm, so the accepter and spectators know whose accept won.
|
||||
_scheduleAnswer(game, info: true, latestMove: false, immediate: true);
|
||||
_notify(
|
||||
game,
|
||||
inviterWhite
|
||||
? link.l10n.chess_notifyAcceptedYourMove(p.accepterName)
|
||||
: link.l10n.chess_notifyAccepted(p.accepterName),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
// Spectators wait for the inviter's confirmation (a game info packet).
|
||||
game.lastActivityMs = _now;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _onDecline(ChessGame? game, ChessDeclinePacket p) {
|
||||
if (game == null || 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));
|
||||
}
|
||||
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.
|
||||
}
|
||||
final white = ChessPlayer(name: p.whiteName, commitment: p.whiteCommitment);
|
||||
final black = ChessPlayer(name: p.blackName, commitment: p.blackCommitment);
|
||||
|
||||
if (game == null) {
|
||||
final created = ChessGame(
|
||||
channelId: channelId,
|
||||
gameId: p.gameId,
|
||||
status: ChessGameStatus.active,
|
||||
deadline: p.deadline,
|
||||
white: white,
|
||||
black: black,
|
||||
createdAtMs: _now,
|
||||
startedAtMs: p.startedAtUnix * 1000,
|
||||
hasPosition: p.ply == 0,
|
||||
ply: p.ply,
|
||||
sanMoves: List<String?>.filled(p.ply, null, growable: true),
|
||||
);
|
||||
_games[created.key] = created;
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if (side == null) {
|
||||
// Someone else's accept won. Keep watching the game.
|
||||
game.mySeedHex = null;
|
||||
_start(game, white: white, black: black, mySide: null);
|
||||
_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;
|
||||
game
|
||||
..white = white
|
||||
..black = black
|
||||
..startedAtMs ??= p.startedAtUnix * 1000
|
||||
..lastActivityMs = _now;
|
||||
return true;
|
||||
case ChessGameStatus.finished:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _start(
|
||||
ChessGame game, {
|
||||
required ChessPlayer white,
|
||||
required ChessPlayer black,
|
||||
required ChessSide? mySide,
|
||||
}) {
|
||||
game
|
||||
..white = white
|
||||
..black = black
|
||||
..mySide = mySide
|
||||
..status = ChessGameStatus.active
|
||||
..startedAtMs = _now
|
||||
..lastMoveAtMs = _now
|
||||
..lastActivityMs = _now;
|
||||
}
|
||||
|
||||
bool _onMove(
|
||||
String channelId,
|
||||
ChessGame? game,
|
||||
ChessMovePacket p,
|
||||
Uint8List raw,
|
||||
) {
|
||||
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,
|
||||
);
|
||||
if (fen == null || !isValidFen(fen)) return false;
|
||||
final created = ChessGame(
|
||||
channelId: channelId,
|
||||
gameId: p.gameId,
|
||||
status: ChessGameStatus.active,
|
||||
deadline: ChessDeadline.none,
|
||||
createdAtMs: _now,
|
||||
)..adoptPosition(fen, fullPly);
|
||||
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;
|
||||
}
|
||||
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.
|
||||
|
||||
final player = game.playerOf(mover);
|
||||
if (player != null && !player.owns(p.chainValue)) return false;
|
||||
|
||||
final fen = ChessPositionCodec.decodeToFen(
|
||||
p.position,
|
||||
fullMoveNumber: fullPly ~/ 2 + 1,
|
||||
);
|
||||
if (fen == null) return false;
|
||||
|
||||
var applied = false;
|
||||
if (fullPly == game.ply + 1 && game.hasPosition) {
|
||||
final legal = game.legalUci();
|
||||
if (p.moveIndex < legal.length) {
|
||||
final probe = ChessGame.fromJson(game.toJson())!;
|
||||
if (probe.applyUci(legal[p.moveIndex]) &&
|
||||
bytesEqual(probe.packedPosition(), p.position)) {
|
||||
game.applyUci(legal[p.moveIndex]);
|
||||
applied = true;
|
||||
}
|
||||
}
|
||||
if (!applied && game.isPlayer) return false; // Does not match our board.
|
||||
} else if (game.isPlayer && game.hasPosition) {
|
||||
return false; // Players cannot skip moves.
|
||||
}
|
||||
if (!applied) {
|
||||
if (!isValidFen(fen)) return false;
|
||||
game.adoptPosition(fen, fullPly);
|
||||
}
|
||||
player?.verifyAndAdvance(p.chainValue);
|
||||
game
|
||||
..lastMovePacket = raw
|
||||
..lastMoveAtMs = _now
|
||||
..lastActivityMs = _now;
|
||||
|
||||
if (game.isPlayer) {
|
||||
final opponent = game.nameOf(mover) ?? '';
|
||||
final san = game.sanMoves.isEmpty ? null : game.sanMoves.last;
|
||||
if (game.status == ChessGameStatus.finished) {
|
||||
_notify(game, link.l10n.chess_notifyGameOver(opponent));
|
||||
} else if (game.isMyTurn) {
|
||||
_notify(game, link.l10n.chess_notifyYourMove(opponent, san ?? ''));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
if (!inviter.verifyAndAdvance(p.chainValue)) return false;
|
||||
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 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:
|
||||
game.drawOfferedBy = side;
|
||||
if (game.isPlayer) {
|
||||
_notify(game, link.l10n.chess_notifyDrawOffered(name));
|
||||
}
|
||||
case ChessPacketKind.drawAccept:
|
||||
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;
|
||||
game.finish(ChessEndReason.timeout, winner: side);
|
||||
if (game.isPlayer) _notify(game, link.l10n.chess_notifyTimeout(name));
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
game.lastActivityMs = _now;
|
||||
return true;
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Answers a request after a random delay, unless someone else answers
|
||||
/// first. At most one answer per game per [requestAnswerInterval].
|
||||
void _scheduleAnswer(
|
||||
ChessGame game, {
|
||||
required bool info,
|
||||
required bool latestMove,
|
||||
bool immediate = false,
|
||||
}) {
|
||||
if (!info && !latestMove) return;
|
||||
if (_pendingAnswers.containsKey(game.key)) return;
|
||||
final last = game.lastAnsweredRequestAtMs;
|
||||
if (!immediate &&
|
||||
last != null &&
|
||||
_now - last < requestAnswerInterval.inMilliseconds) {
|
||||
return;
|
||||
}
|
||||
final spread = _answerDelayMax - _answerDelayMin;
|
||||
final delay = immediate
|
||||
? Duration.zero
|
||||
: _answerDelayMin +
|
||||
Duration(
|
||||
milliseconds: spread.inMilliseconds <= 0
|
||||
? 0
|
||||
: _random.nextInt(spread.inMilliseconds),
|
||||
);
|
||||
_pendingAnswers[game.key] = Timer(delay, () async {
|
||||
_pendingAnswers.remove(game.key);
|
||||
// Confirmations are not answers to a request; they don't count.
|
||||
if (!immediate) game.lastAnsweredRequestAtMs = _now;
|
||||
if (info) await _sendInfo(game);
|
||||
final move = game.lastMovePacket;
|
||||
if (latestMove && move != null && link.canSend) {
|
||||
await link.send(game.channelId, move);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _sendInfo(ChessGame game) async {
|
||||
final white = game.white;
|
||||
final black = game.black;
|
||||
if (white == null || black == null) return;
|
||||
await _send(
|
||||
game,
|
||||
ChessInfoPacket(
|
||||
gameId: game.gameId,
|
||||
ply: game.ply & 0xFF,
|
||||
startedAtUnix: (game.startedAtMs ?? game.createdAtMs) ~/ 1000,
|
||||
deadline: game.deadline,
|
||||
whiteCommitment: white.commitment,
|
||||
blackCommitment: black.commitment,
|
||||
whiteName: white.name,
|
||||
blackName: black.name,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 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(
|
||||
ChessColourPreference pref,
|
||||
Uint8List inviter,
|
||||
Uint8List accepter,
|
||||
) {
|
||||
switch (pref) {
|
||||
case ChessColourPreference.white:
|
||||
return true;
|
||||
case ChessColourPreference.black:
|
||||
return false;
|
||||
case ChessColourPreference.random:
|
||||
return sha256.convert([...inviter, ...accepter]).bytes[0] & 1 == 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isMe(String? name) =>
|
||||
name != null &&
|
||||
link.selfName.isNotEmpty &&
|
||||
_sameName(name, link.selfName);
|
||||
|
||||
static bool _sameName(String a, String b) =>
|
||||
a.trim().toLowerCase() == b.trim().toLowerCase();
|
||||
|
||||
void _notify(ChessGame game, String text) {
|
||||
if (game.key == _viewingKey) return;
|
||||
link.notify(game.channelId, text);
|
||||
}
|
||||
|
||||
void _touch(ChessGame game) {
|
||||
game.lastActivityMs = _now;
|
||||
_changed();
|
||||
}
|
||||
|
||||
void _changed() {
|
||||
if (_disposed) return;
|
||||
notifyListeners();
|
||||
unawaited(store.save(_scope, _games.values.toList()));
|
||||
}
|
||||
|
||||
/// Expires stale invites and prunes old games. Runs every minute.
|
||||
@visibleForTesting
|
||||
void housekeeping() {
|
||||
final now = _now;
|
||||
var changed = false;
|
||||
for (final g in _games.values) {
|
||||
if ((g.status == ChessGameStatus.invite ||
|
||||
g.status == ChessGameStatus.starting) &&
|
||||
now - g.createdAtMs > inviteLifetime.inMilliseconds) {
|
||||
g.finish(ChessEndReason.expired);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
final stale = _games.values
|
||||
.where(
|
||||
(g) =>
|
||||
(!g.isOpen || !g.isPlayer) &&
|
||||
now - g.lastActivityMs > keepFinished.inMilliseconds,
|
||||
)
|
||||
.map((g) => g.key)
|
||||
.toList();
|
||||
for (final key in stale) {
|
||||
_games.remove(key);
|
||||
changed = true;
|
||||
}
|
||||
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;
|
||||
if (ao != bo) return ao - bo;
|
||||
return a.lastActivityMs.compareTo(b.lastActivityMs);
|
||||
});
|
||||
for (final g in byAge.take(_games.length - maxStoredGames)) {
|
||||
_games.remove(g.key);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
_changed();
|
||||
} else if (_games.values.any((g) => g.status == ChessGameStatus.active)) {
|
||||
notifyListeners(); // Deadline countdowns.
|
||||
}
|
||||
}
|
||||
|
||||
void _onLinkChanged() {
|
||||
final scope = link.storageScope;
|
||||
if (scope != _scope) {
|
||||
_loadScope(scope);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _loadScope(String scope) {
|
||||
_scope = scope;
|
||||
_games
|
||||
..clear()
|
||||
..addEntries(store.load(scope).map((g) => MapEntry(g.key, g)));
|
||||
for (final t in _pendingAnswers.values) {
|
||||
t.cancel();
|
||||
}
|
||||
_pendingAnswers.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_sub?.cancel();
|
||||
_housekeeping?.cancel();
|
||||
for (final t in _pendingAnswers.values) {
|
||||
t.cancel();
|
||||
}
|
||||
link.removeListener(_onLinkChanged);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../../storage/prefs_manager.dart';
|
||||
import 'chess_game.dart';
|
||||
|
||||
/// Per-radio list of chess games in preferences, keyed by the first 10 hex
|
||||
/// chars of the radio's public key.
|
||||
class ChessStore {
|
||||
static const String _keyPrefix = 'chess_games_';
|
||||
|
||||
Future<void> _pending = Future.value();
|
||||
|
||||
static String keyFor(String scope) => '$_keyPrefix$scope';
|
||||
|
||||
/// Games saved for [scope]; records that fail to decode are skipped.
|
||||
List<ChessGame> load(String scope) {
|
||||
if (scope.isEmpty) return [];
|
||||
try {
|
||||
final raw = PrefsManager.instance.getString(keyFor(scope));
|
||||
if (raw == null || raw.isEmpty) return [];
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) return [];
|
||||
return decoded.map(ChessGame.fromJson).whereType<ChessGame>().toList();
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves [games] for [scope]. Writes are serialized.
|
||||
Future<void> save(String scope, List<ChessGame> games) {
|
||||
if (scope.isEmpty) return Future.value();
|
||||
final json = jsonEncode(games.map((g) => g.toJson()).toList());
|
||||
return _pending = _pending.then((_) async {
|
||||
try {
|
||||
await PrefsManager.instance.setString(keyFor(scope), json);
|
||||
} catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> flush() => _pending;
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import 'package:chess_vectors_flutter/chess_vectors_flutter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../l10n/l10n.dart';
|
||||
import '../../../widgets/mesh_nav_tile.dart';
|
||||
import '../../../widgets/mesh_ui.dart';
|
||||
|
||||
/// Board square colours. The board is content, not chrome, so it keeps the
|
||||
/// same classic colours in every theme; both have strong contrast with the
|
||||
/// white and black pieces.
|
||||
abstract final class ChessBoardPalette {
|
||||
static const Color light = Color(0xFFEEEED2);
|
||||
static const Color dark = Color(0xFF769656);
|
||||
static const Color lastMove = Color(0x99F6E05E);
|
||||
static const Color check = Color(0xCCE53935);
|
||||
static const Color hint = Color(0x8C1B1B1B);
|
||||
}
|
||||
|
||||
/// A chess piece drawn from vectors. [piece] is a FEN letter (`K`, `q`, …).
|
||||
Widget chessPieceWidget(String piece, double size) {
|
||||
return switch (piece) {
|
||||
'P' => WhitePawn(size: size),
|
||||
'N' => WhiteKnight(size: size),
|
||||
'B' => WhiteBishop(size: size),
|
||||
'R' => WhiteRook(size: size),
|
||||
'Q' => WhiteQueen(size: size),
|
||||
'K' => WhiteKing(size: size),
|
||||
'p' => BlackPawn(size: size),
|
||||
'n' => BlackKnight(size: size),
|
||||
'b' => BlackBishop(size: size),
|
||||
'r' => BlackRook(size: size),
|
||||
'q' => BlackQueen(size: size),
|
||||
'k' => BlackKing(size: size),
|
||||
_ => SizedBox(width: size, height: size),
|
||||
};
|
||||
}
|
||||
|
||||
/// Pieces by square (`e4` → `P`) from the board field of [fen].
|
||||
Map<String, String> piecesFromFen(String fen) {
|
||||
final out = <String, String>{};
|
||||
final rows = fen.split(' ').first.split('/');
|
||||
for (var r = 0; r < rows.length && r < 8; r++) {
|
||||
final rank = 8 - r;
|
||||
var file = 0;
|
||||
for (final ch in rows[r].split('')) {
|
||||
final n = int.tryParse(ch);
|
||||
if (n != null) {
|
||||
file += n;
|
||||
continue;
|
||||
}
|
||||
if (file < 8) {
|
||||
out['${String.fromCharCode(97 + file)}$rank'] = ch;
|
||||
}
|
||||
file++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// An 8×8 board. Tap one of your pieces, then a highlighted square, to
|
||||
/// move. [legalMoves] (UCI) enables input; pass an empty list for a
|
||||
/// read-only board.
|
||||
class ChessBoardView extends StatefulWidget {
|
||||
final String fen;
|
||||
final bool flipped;
|
||||
final String? lastMoveUci;
|
||||
final bool inCheck;
|
||||
final List<String> legalMoves;
|
||||
final ValueChanged<String>? onMove;
|
||||
|
||||
const ChessBoardView({
|
||||
super.key,
|
||||
required this.fen,
|
||||
this.flipped = false,
|
||||
this.lastMoveUci,
|
||||
this.inCheck = false,
|
||||
this.legalMoves = const [],
|
||||
this.onMove,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ChessBoardView> createState() => _ChessBoardViewState();
|
||||
}
|
||||
|
||||
class _ChessBoardViewState extends State<ChessBoardView> {
|
||||
String? _selected;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChessBoardView old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (old.fen != widget.fen) _selected = null;
|
||||
}
|
||||
|
||||
bool get _interactive =>
|
||||
widget.onMove != null && widget.legalMoves.isNotEmpty;
|
||||
|
||||
Iterable<String> _movesFrom(String square) =>
|
||||
widget.legalMoves.where((m) => m.startsWith(square));
|
||||
|
||||
Future<void> _onTap(String square) async {
|
||||
if (!_interactive) return;
|
||||
final selected = _selected;
|
||||
if (selected != null) {
|
||||
final moves = _movesFrom(
|
||||
selected,
|
||||
).where((m) => m.substring(2, 4) == square).toList();
|
||||
if (moves.isNotEmpty) {
|
||||
setState(() => _selected = null);
|
||||
var uci = moves.first;
|
||||
if (moves.length > 1) {
|
||||
final promotion = await _pickPromotion(moves);
|
||||
if (promotion == null) return;
|
||||
uci = promotion;
|
||||
}
|
||||
widget.onMove?.call(uci);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setState(() {
|
||||
_selected = _movesFrom(square).isNotEmpty && selected != square
|
||||
? square
|
||||
: null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<String?> _pickPromotion(List<String> moves) {
|
||||
final l10n = context.l10n;
|
||||
final labels = {
|
||||
'q': l10n.chess_pieceQueen,
|
||||
'r': l10n.chess_pieceRook,
|
||||
'b': l10n.chess_pieceBishop,
|
||||
'n': l10n.chess_pieceKnight,
|
||||
};
|
||||
return showMeshSheet<String>(
|
||||
context,
|
||||
builder: (sheetContext) => SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
BottomSheetHeader(title: l10n.chess_promoteTitle),
|
||||
for (final letter in const ['q', 'r', 'b', 'n'])
|
||||
for (final m in moves.where((m) => m.endsWith(letter)))
|
||||
MeshSheetOption(
|
||||
label: labels[letter]!,
|
||||
selected: false,
|
||||
onTap: () => Navigator.pop(sheetContext, m),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final pieces = piecesFromFen(widget.fen);
|
||||
final last = widget.lastMoveUci;
|
||||
final lastSquares = last == null || last.length < 4
|
||||
? const <String>{}
|
||||
: {last.substring(0, 2), last.substring(2, 4)};
|
||||
final targets = _selected == null
|
||||
? const <String>{}
|
||||
: _movesFrom(_selected!).map((m) => m.substring(2, 4)).toSet();
|
||||
final whiteToMove = widget.fen.split(' ').elementAtOrNull(1) != 'b';
|
||||
final checkedKing = widget.inCheck ? (whiteToMove ? 'K' : 'k') : null;
|
||||
|
||||
return AspectRatio(
|
||||
aspectRatio: 1,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final cell = constraints.maxWidth / 8;
|
||||
return Column(
|
||||
children: [
|
||||
for (var row = 0; row < 8; row++)
|
||||
Row(
|
||||
children: [
|
||||
for (var col = 0; col < 8; col++)
|
||||
_square(
|
||||
context,
|
||||
scheme: scheme,
|
||||
cell: cell,
|
||||
row: row,
|
||||
col: col,
|
||||
pieces: pieces,
|
||||
lastSquares: lastSquares,
|
||||
targets: targets,
|
||||
checkedKing: checkedKing,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _square(
|
||||
BuildContext context, {
|
||||
required ColorScheme scheme,
|
||||
required double cell,
|
||||
required int row,
|
||||
required int col,
|
||||
required Map<String, String> pieces,
|
||||
required Set<String> lastSquares,
|
||||
required Set<String> targets,
|
||||
required String? checkedKing,
|
||||
}) {
|
||||
final file = widget.flipped ? 7 - col : col;
|
||||
final rank = widget.flipped ? row + 1 : 8 - row;
|
||||
final square = '${String.fromCharCode(97 + file)}$rank';
|
||||
final isLight = (file + rank).isOdd;
|
||||
final piece = pieces[square];
|
||||
final isTarget = targets.contains(square);
|
||||
final isSelected = _selected == square;
|
||||
final coordStyle = TextStyle(
|
||||
fontSize: (cell * 0.24).clamp(12.0, 14.0),
|
||||
fontWeight: FontWeight.w700,
|
||||
color: isLight ? ChessBoardPalette.dark : ChessBoardPalette.light,
|
||||
);
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => _onTap(square),
|
||||
child: Semantics(
|
||||
label: piece == null ? square : '$square $piece',
|
||||
button: isTarget || (_interactive && piece != null),
|
||||
selected: isSelected,
|
||||
child: SizedBox(
|
||||
width: cell,
|
||||
height: cell,
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: ColoredBox(
|
||||
color: isLight
|
||||
? ChessBoardPalette.light
|
||||
: ChessBoardPalette.dark,
|
||||
),
|
||||
),
|
||||
if (lastSquares.contains(square))
|
||||
const Positioned.fill(
|
||||
child: ColoredBox(color: ChessBoardPalette.lastMove),
|
||||
),
|
||||
if (piece != null && piece == checkedKing)
|
||||
Positioned.fill(
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: RadialGradient(
|
||||
colors: [
|
||||
ChessBoardPalette.check,
|
||||
ChessBoardPalette.check.withValues(alpha: 0),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isSelected)
|
||||
Positioned.fill(
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: scheme.primary, width: 3),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (col == 0)
|
||||
Positioned(
|
||||
left: 2,
|
||||
top: 1,
|
||||
child: Text('$rank', style: coordStyle),
|
||||
),
|
||||
if (row == 7)
|
||||
Positioned(
|
||||
right: 2,
|
||||
bottom: 0,
|
||||
child: Text(
|
||||
String.fromCharCode(97 + file),
|
||||
style: coordStyle,
|
||||
),
|
||||
),
|
||||
if (piece != null)
|
||||
Center(child: chessPieceWidget(piece, cell * 0.92)),
|
||||
if (isTarget)
|
||||
Center(
|
||||
child: piece == null
|
||||
? Container(
|
||||
width: cell * 0.3,
|
||||
height: cell * 0.3,
|
||||
decoration: const BoxDecoration(
|
||||
color: ChessBoardPalette.hint,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
)
|
||||
: Container(
|
||||
width: cell * 0.92,
|
||||
height: cell * 0.92,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: ChessBoardPalette.hint,
|
||||
width: cell * 0.08,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../../helpers/snack_bar_builder.dart';
|
||||
import '../../../l10n/l10n.dart';
|
||||
import '../../../theme/mesh_theme.dart';
|
||||
import '../../../utils/radio_guard.dart';
|
||||
import '../../../widgets/mesh_nav_tile.dart';
|
||||
import '../../../widgets/mesh_ui.dart';
|
||||
import '../chess_game.dart';
|
||||
import '../chess_service.dart';
|
||||
import 'chess_board.dart';
|
||||
import 'chess_text.dart';
|
||||
|
||||
/// A chess game, for players and spectators alike.
|
||||
class ChessGameScreen extends StatefulWidget {
|
||||
final String channelId;
|
||||
final int gameId;
|
||||
|
||||
const ChessGameScreen({
|
||||
super.key,
|
||||
required this.channelId,
|
||||
required this.gameId,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ChessGameScreen> createState() => _ChessGameScreenState();
|
||||
}
|
||||
|
||||
class _ChessGameScreenState extends State<ChessGameScreen> {
|
||||
ChessService? _service;
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_service ??= context.read<ChessService>();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_service?.viewing = null;
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _run(Future<bool> Function() action) async {
|
||||
if (!ensureRadioConnected(context)) return;
|
||||
final ok = await action();
|
||||
if (!ok && mounted) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.chess_sendFailed),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _confirmResign(ChessService service, ChessGame game) async {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final yes = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.chess_resignConfirmTitle),
|
||||
content: Text(l10n.chess_resignConfirmBody),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: scheme.error,
|
||||
foregroundColor: scheme.onError,
|
||||
),
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.chess_actionResign),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (yes == true && mounted) await _run(() => service.resign(game));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final service = context.watch<ChessService>();
|
||||
final game = service.game(widget.channelId, widget.gameId);
|
||||
if (game == null) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(l10n.chess_sheetTitle), centerTitle: true),
|
||||
body: Center(child: Text(l10n.chess_gameGone)),
|
||||
);
|
||||
}
|
||||
service.viewing = game;
|
||||
final readOnly = context.radioReadOnly;
|
||||
final busy = service.isSending(game);
|
||||
final canAct = !readOnly && service.canSend && !busy;
|
||||
final flipped = game.mySide == ChessSide.black;
|
||||
final myTurn = game.isMyTurn && canAct;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: Text(
|
||||
l10n.chessPlayers(game),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
bottom: busy
|
||||
? const PreferredSize(
|
||||
preferredSize: Size.fromHeight(3),
|
||||
child: LinearProgressIndicator(minHeight: 3),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
body: SafeArea(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final boardSize = constraints.maxWidth.clamp(0.0, 560.0) - 16;
|
||||
return ListView(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
children: [
|
||||
_PlayerStrip(
|
||||
game: game,
|
||||
side: flipped ? ChessSide.white : ChessSide.black,
|
||||
),
|
||||
Center(
|
||||
child: SizedBox(
|
||||
width: boardSize,
|
||||
child: game.hasPosition
|
||||
? ChessBoardView(
|
||||
fen: game.fen,
|
||||
flipped: flipped,
|
||||
lastMoveUci: game.lastMoveUci,
|
||||
inCheck: game.board.in_check,
|
||||
legalMoves: myTurn ? game.legalUci() : const [],
|
||||
onMove: myTurn
|
||||
? (uci) =>
|
||||
_run(() => service.makeMove(game, uci))
|
||||
: null,
|
||||
)
|
||||
: AspectRatio(
|
||||
aspectRatio: 1,
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
l10n.chess_statusUnknownPosition,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
_PlayerStrip(
|
||||
game: game,
|
||||
side: flipped ? ChessSide.black : ChessSide.white,
|
||||
),
|
||||
_StatusCard(game: game, service: service),
|
||||
_Actions(
|
||||
game: game,
|
||||
service: service,
|
||||
canAct: canAct,
|
||||
onRun: _run,
|
||||
onResign: () => _confirmResign(service, game),
|
||||
),
|
||||
SectionHeader(l10n.chess_movesTitle),
|
||||
_MoveList(game: game),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PlayerStrip extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
final ChessSide side;
|
||||
|
||||
const _PlayerStrip({required this.game, required this.side});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = context.l10n;
|
||||
final name = game.nameOf(side) ?? l10n.chess_unknownPlayer;
|
||||
final toMove =
|
||||
game.status == ChessGameStatus.active &&
|
||||
game.hasPosition &&
|
||||
game.sideToMove == side;
|
||||
final isMe = game.mySide == side;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
side == ChessSide.white ? Icons.circle_outlined : Icons.circle,
|
||||
size: 20,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
isMe ? l10n.chess_playerYou(name) : name,
|
||||
style: meshTileTitleStyle(theme),
|
||||
),
|
||||
),
|
||||
if (toMove)
|
||||
StatusChip(
|
||||
label: l10n.chess_toMoveChip,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whose move it is, time left, draw offers, result.
|
||||
class _StatusCard extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
final ChessService service;
|
||||
|
||||
const _StatusCard({required this.game, required this.service});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = context.l10n;
|
||||
final lines = <String>[];
|
||||
switch (game.status) {
|
||||
case ChessGameStatus.invite:
|
||||
case ChessGameStatus.starting:
|
||||
lines.add(l10n.chess_rowStarting);
|
||||
case ChessGameStatus.finished:
|
||||
lines.add(l10n.chessResult(game));
|
||||
case ChessGameStatus.active:
|
||||
if (!game.hasPosition) {
|
||||
lines.add(l10n.chess_statusUnknownPosition);
|
||||
} else if (game.isMyTurn) {
|
||||
lines.add(l10n.chess_statusYourMove);
|
||||
} else {
|
||||
final name = game.nameOf(game.sideToMove) ?? l10n.chess_unknownPlayer;
|
||||
lines.add(
|
||||
game.isPlayer
|
||||
? l10n.chess_statusWaiting(name)
|
||||
: l10n.chess_statusToMove(name),
|
||||
);
|
||||
}
|
||||
final at = service.deadlineAt(game);
|
||||
if (at != null && game.hasPosition) {
|
||||
final left = at.difference(DateTime.now());
|
||||
lines.add(
|
||||
left.isNegative
|
||||
? l10n.chess_statusOverdue
|
||||
: l10n.chess_statusTimeLeft(l10n.chessDuration(left)),
|
||||
);
|
||||
}
|
||||
final offeredBy = game.drawOfferedBy;
|
||||
if (offeredBy != null) {
|
||||
lines.add(
|
||||
l10n.chess_statusDrawOffered(
|
||||
game.nameOf(offeredBy) ?? l10n.chess_unknownPlayer,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!game.hasPlayers) lines.add(l10n.chess_statusUnverified);
|
||||
}
|
||||
return MeshCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
lines.first,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
for (final line in lines.skip(1)) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
line,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Actions extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
final ChessService service;
|
||||
final bool canAct;
|
||||
final Future<void> Function(Future<bool> Function()) onRun;
|
||||
final VoidCallback onResign;
|
||||
|
||||
const _Actions({
|
||||
required this.game,
|
||||
required this.service,
|
||||
required this.canAct,
|
||||
required this.onRun,
|
||||
required this.onResign,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final buttons = <Widget>[];
|
||||
final active = game.status == ChessGameStatus.active;
|
||||
if (active && game.isPlayer) {
|
||||
final offeredBy = game.drawOfferedBy;
|
||||
if (offeredBy != null && offeredBy != game.mySide) {
|
||||
buttons.add(
|
||||
FilledButton(
|
||||
onPressed: canAct
|
||||
? () => onRun(() => service.acceptDraw(game))
|
||||
: null,
|
||||
child: Text(l10n.chess_actionAcceptDraw),
|
||||
),
|
||||
);
|
||||
} else if (offeredBy == null) {
|
||||
buttons.add(
|
||||
OutlinedButton(
|
||||
onPressed: canAct
|
||||
? () => onRun(() => service.offerDraw(game))
|
||||
: null,
|
||||
child: Text(l10n.chess_actionOfferDraw),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (service.canClaimTimeout(game)) {
|
||||
buttons.add(
|
||||
FilledButton(
|
||||
onPressed: canAct
|
||||
? () => onRun(() => service.claimTimeout(game))
|
||||
: null,
|
||||
child: Text(l10n.chess_actionClaimTimeout),
|
||||
),
|
||||
);
|
||||
}
|
||||
buttons.add(
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(foregroundColor: scheme.error),
|
||||
onPressed: canAct ? onResign : null,
|
||||
child: Text(l10n.chess_actionResign),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (game.isOpen && (!game.isMyTurn || !game.hasPlayers)) {
|
||||
buttons.add(
|
||||
Tooltip(
|
||||
message: l10n.chess_actionNudgeTooltip,
|
||||
child: OutlinedButton.icon(
|
||||
icon: const Icon(Icons.refresh, size: 20),
|
||||
onPressed: canAct
|
||||
? () => onRun(() => service.requestUpdate(game))
|
||||
: null,
|
||||
label: Text(l10n.chess_actionNudge),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (buttons.isEmpty) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Wrap(spacing: 8, runSpacing: 8, children: buttons),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves as numbered pairs; runs of moves we never heard collapse into one
|
||||
/// "missed" entry.
|
||||
class _MoveList extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
|
||||
const _MoveList({required this.game});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = context.l10n;
|
||||
if (game.sanMoves.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
l10n.chess_noMovesYet,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final entries = <String>[];
|
||||
var i = 0;
|
||||
final moves = game.sanMoves;
|
||||
while (i < moves.length) {
|
||||
if (moves[i] == null) {
|
||||
while (i < moves.length && moves[i] == null) {
|
||||
i++;
|
||||
}
|
||||
entries.add(l10n.chess_movesMissed);
|
||||
continue;
|
||||
}
|
||||
final number = i ~/ 2 + 1;
|
||||
if (i.isEven) {
|
||||
final black = i + 1 < moves.length ? moves[i + 1] : null;
|
||||
entries.add(
|
||||
black == null
|
||||
? '$number. ${moves[i]}'
|
||||
: '$number. ${moves[i]} $black',
|
||||
);
|
||||
i += black == null ? 1 : 2;
|
||||
} else {
|
||||
entries.add('$number… ${moves[i]}');
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
for (final e in entries) Text(e, style: MeshTheme.mono(fontSize: 14)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
import 'package:chess_vectors_flutter/chess_vectors_flutter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../../helpers/snack_bar_builder.dart';
|
||||
import '../../../l10n/l10n.dart';
|
||||
import '../../../models/channel.dart';
|
||||
import '../../../utils/radio_guard.dart';
|
||||
import '../../../widgets/empty_state.dart';
|
||||
import '../../../widgets/mesh_nav_tile.dart';
|
||||
import '../../../widgets/mesh_ui.dart';
|
||||
import '../chess_game.dart';
|
||||
import '../chess_service.dart';
|
||||
import 'chess_game_screen.dart';
|
||||
import 'chess_new_game_sheet.dart';
|
||||
import 'chess_text.dart';
|
||||
|
||||
/// Label of the channel menu entry: "Chess games", with the number of open
|
||||
/// games and invites when there are any.
|
||||
String chessMenuLabel(BuildContext context, Channel channel) {
|
||||
final id = channel.storageId;
|
||||
var count = 0;
|
||||
try {
|
||||
if (id != null) {
|
||||
count = context.read<ChessService>().openCountForChannel(id);
|
||||
}
|
||||
} on ProviderNotFoundException {
|
||||
// Hosts without chess (some tests) just show the plain label.
|
||||
}
|
||||
return count == 0
|
||||
? context.l10n.chess_menuGames
|
||||
: context.l10n.chess_menuGamesCount(count);
|
||||
}
|
||||
|
||||
/// Games on [channel]: yours, open invites, games to watch, and buttons to
|
||||
/// start a new one.
|
||||
Future<void> showChessGamesSheet(BuildContext context, Channel channel) async {
|
||||
final channelId = channel.storageId;
|
||||
if (channelId == null) return;
|
||||
final action = await showMeshSheet<_NewGameAction>(
|
||||
context,
|
||||
builder: (sheetContext) => DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.7,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.95,
|
||||
builder: (_, controller) => _ChessGamesSheetBody(
|
||||
channel: channel,
|
||||
channelId: channelId,
|
||||
controller: controller,
|
||||
hostContext: context,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (action == null || !context.mounted) return;
|
||||
// Close-then-open: the new-game sheet replaces this one.
|
||||
await showChessNewGameSheet(
|
||||
context,
|
||||
channel: channel,
|
||||
direct: action == _NewGameAction.challenge,
|
||||
);
|
||||
}
|
||||
|
||||
enum _NewGameAction { challenge, openInvite }
|
||||
|
||||
class _ChessGamesSheetBody extends StatelessWidget {
|
||||
final Channel channel;
|
||||
final String channelId;
|
||||
final ScrollController controller;
|
||||
final BuildContext hostContext;
|
||||
|
||||
const _ChessGamesSheetBody({
|
||||
required this.channel,
|
||||
required this.channelId,
|
||||
required this.controller,
|
||||
required this.hostContext,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final service = context.watch<ChessService>();
|
||||
final readOnly = context.radioReadOnly;
|
||||
final games = service.gamesForChannel(channelId);
|
||||
final mine = games
|
||||
.where(
|
||||
(g) =>
|
||||
g.isOpen &&
|
||||
(g.isPlayer ||
|
||||
g.iAmInviter ||
|
||||
g.status == ChessGameStatus.starting),
|
||||
)
|
||||
.toList();
|
||||
final invites = games
|
||||
.where(
|
||||
(g) =>
|
||||
g.status == ChessGameStatus.invite &&
|
||||
!g.iAmInviter &&
|
||||
(g.targetName == null ||
|
||||
_sameName(g.targetName!, service.selfName)),
|
||||
)
|
||||
.toList();
|
||||
final live = games
|
||||
.where(
|
||||
(g) =>
|
||||
g.isOpen &&
|
||||
!mine.contains(g) &&
|
||||
!invites.contains(g) &&
|
||||
g.status == ChessGameStatus.active,
|
||||
)
|
||||
.toList();
|
||||
final finished = games.where((g) => !g.isOpen).take(10).toList();
|
||||
final canStart = !readOnly && service.canSend;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
BottomSheetHeader(title: l10n.chess_sheetTitle, subtitle: channel.name),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: controller,
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
children: [
|
||||
if (!readOnly && !service.canSend)
|
||||
MeshCard(child: Text(l10n.settings_requiresFirmware('v1.15'))),
|
||||
SectionHeader(l10n.chess_sectionNewGame),
|
||||
_ActionCard(
|
||||
icon: Icons.person_add_alt_1_outlined,
|
||||
title: l10n.chess_newChallenge,
|
||||
subtitle: l10n.chess_newChallengeSubtitle,
|
||||
onTap: canStart
|
||||
? () => Navigator.pop(context, _NewGameAction.challenge)
|
||||
: null,
|
||||
),
|
||||
_ActionCard(
|
||||
icon: Icons.campaign_outlined,
|
||||
title: l10n.chess_newOpenInvite,
|
||||
subtitle: l10n.chess_newOpenInviteSubtitle,
|
||||
onTap: canStart
|
||||
? () => Navigator.pop(context, _NewGameAction.openInvite)
|
||||
: null,
|
||||
),
|
||||
if (games.isEmpty)
|
||||
EmptyState(
|
||||
icon: Icons.sports_esports_outlined,
|
||||
title: l10n.chess_emptyTitle,
|
||||
subtitle: l10n.chess_emptySubtitle,
|
||||
),
|
||||
if (mine.isNotEmpty) ...[
|
||||
SectionHeader(l10n.chess_sectionYourGames),
|
||||
for (final g in mine) _GameCard(game: g, host: hostContext),
|
||||
],
|
||||
if (invites.isNotEmpty) ...[
|
||||
SectionHeader(l10n.chess_sectionInvites),
|
||||
for (final g in invites)
|
||||
_InviteCard(game: g, readOnly: readOnly, host: hostContext),
|
||||
],
|
||||
if (live.isNotEmpty) ...[
|
||||
SectionHeader(l10n.chess_sectionLive),
|
||||
for (final g in live) _GameCard(game: g, host: hostContext),
|
||||
],
|
||||
if (finished.isNotEmpty) ...[
|
||||
SectionHeader(l10n.chess_sectionFinished),
|
||||
for (final g in finished) _GameCard(game: g, host: hostContext),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _sameName(String a, String b) =>
|
||||
a.trim().toLowerCase() == b.trim().toLowerCase();
|
||||
|
||||
class _ActionCard extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
const _ActionCard({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final enabled = onTap != null;
|
||||
return Opacity(
|
||||
opacity: enabled ? 1 : 0.5,
|
||||
child: MeshCard(
|
||||
onTap: onTap,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 24, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: meshTileTitleStyle(theme)),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
subtitle,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One game: players, and whose move it is or how it ended.
|
||||
class _GameCard extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
final BuildContext host;
|
||||
|
||||
const _GameCard({required this.game, required this.host});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = context.l10n;
|
||||
final service = context.read<ChessService>();
|
||||
final String title;
|
||||
final String subtitle;
|
||||
switch (game.status) {
|
||||
case ChessGameStatus.invite:
|
||||
title = game.targetName == null
|
||||
? l10n.chess_rowYourOpenInvite
|
||||
: l10n.chess_rowYourChallenge(game.targetName!);
|
||||
subtitle = l10n.chessDeadlineLabel(game.deadline);
|
||||
case ChessGameStatus.starting:
|
||||
title = l10n.chess_rowInviteFrom(game.inviter?.name ?? '');
|
||||
subtitle = l10n.chess_rowStarting;
|
||||
case ChessGameStatus.active:
|
||||
title = l10n.chessPlayers(game);
|
||||
final toMove = game.nameOf(game.sideToMove) ?? l10n.chess_unknownPlayer;
|
||||
final turn = game.isMyTurn
|
||||
? l10n.chess_statusYourMove
|
||||
: l10n.chess_statusToMove(toMove);
|
||||
subtitle = l10n.chess_rowMoveTurn((game.ply ~/ 2) + 1, turn);
|
||||
case ChessGameStatus.finished:
|
||||
title = l10n.chessPlayers(game);
|
||||
subtitle = l10n.chessResult(game);
|
||||
}
|
||||
return MeshCard(
|
||||
onTap: game.status == ChessGameStatus.invite && game.iAmInviter
|
||||
? () => _confirmCancel(context, service)
|
||||
: () {
|
||||
Navigator.pop(context);
|
||||
Navigator.push(
|
||||
host,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ChessGameScreen(
|
||||
channelId: game.channelId,
|
||||
gameId: game.gameId,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Row(
|
||||
children: [
|
||||
_PieceIcon(highlight: game.isMyTurn),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: meshTileTitleStyle(theme)),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
subtitle,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: game.isMyTurn
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
fontWeight: game.isMyTurn ? FontWeight.w600 : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!game.isOpen)
|
||||
IconButton(
|
||||
tooltip: l10n.chess_remove,
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => service.remove(game),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmCancel(
|
||||
BuildContext context,
|
||||
ChessService service,
|
||||
) async {
|
||||
final l10n = context.l10n;
|
||||
final cancel = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.chess_cancelInviteTitle),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.chess_cancelInvite),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (cancel != true || !context.mounted) return;
|
||||
if (!ensureRadioConnected(context)) return;
|
||||
final ok = await service.cancelInvite(game);
|
||||
if (!ok && context.mounted) {
|
||||
showDismissibleSnackBar(context, content: Text(l10n.chess_sendFailed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Someone else's invite with Accept (and Decline for a challenge to us).
|
||||
class _InviteCard extends StatelessWidget {
|
||||
final ChessGame game;
|
||||
final bool readOnly;
|
||||
final BuildContext host;
|
||||
|
||||
const _InviteCard({
|
||||
required this.game,
|
||||
required this.readOnly,
|
||||
required this.host,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = context.l10n;
|
||||
final service = context.watch<ChessService>();
|
||||
final inviter = game.inviter?.name ?? l10n.chess_unknownPlayer;
|
||||
final busy = service.isSending(game);
|
||||
final canAct = !readOnly && service.canSend && !busy;
|
||||
return MeshCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const _PieceIcon(highlight: false),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
game.targetName == null
|
||||
? l10n.chess_rowOpenInvite(inviter)
|
||||
: l10n.chess_rowChallengedYou(inviter),
|
||||
style: meshTileTitleStyle(theme),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
l10n.chess_rowInviteDetails(
|
||||
l10n.chessDeadlineLabel(game.deadline),
|
||||
),
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
alignment: WrapAlignment.end,
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
if (game.targetName != null)
|
||||
OutlinedButton(
|
||||
onPressed: canAct
|
||||
? () => _run(context, service.decline)
|
||||
: null,
|
||||
child: Text(l10n.chess_decline),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: canAct ? () => _run(context, service.accept) : null,
|
||||
child: Text(l10n.chess_accept),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _run(
|
||||
BuildContext context,
|
||||
Future<bool> Function(ChessGame) action,
|
||||
) async {
|
||||
if (!ensureRadioConnected(context)) return;
|
||||
final ok = await action(game);
|
||||
if (!ok && context.mounted) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.chess_sendFailed),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _PieceIcon extends StatelessWidget {
|
||||
final bool highlight;
|
||||
|
||||
const _PieceIcon({required this.highlight});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: highlight
|
||||
? scheme.primaryContainer
|
||||
: scheme.surfaceContainerHigh,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: WhiteKnight(size: 30),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../../connector/meshcore_connector.dart';
|
||||
import '../../../helpers/snack_bar_builder.dart';
|
||||
import '../../../l10n/l10n.dart';
|
||||
import '../../../models/channel.dart';
|
||||
import '../../../utils/radio_guard.dart';
|
||||
import '../../../widgets/mesh_nav_tile.dart';
|
||||
import '../../../widgets/mesh_ui.dart';
|
||||
import '../chess_packets.dart';
|
||||
import '../chess_service.dart';
|
||||
import 'chess_text.dart';
|
||||
|
||||
/// Names recently heard on [channel], newest first, without our own.
|
||||
List<String> recentChannelSenders(
|
||||
MeshCoreConnector connector,
|
||||
Channel channel, {
|
||||
int limit = 30,
|
||||
}) {
|
||||
final self = (connector.selfName ?? '').trim().toLowerCase();
|
||||
final seen = <String>{};
|
||||
final out = <String>[];
|
||||
final messages = connector.getChannelMessages(channel);
|
||||
for (final m in messages.reversed) {
|
||||
if (m.isOutgoing) continue;
|
||||
final name = m.senderName.trim();
|
||||
final key = name.toLowerCase();
|
||||
if (name.isEmpty || key == self || !seen.add(key)) continue;
|
||||
out.add(name);
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Picks the opponent (for a [direct] challenge), time per move and colour,
|
||||
/// then sends the invite.
|
||||
Future<void> showChessNewGameSheet(
|
||||
BuildContext context, {
|
||||
required Channel channel,
|
||||
required bool direct,
|
||||
}) async {
|
||||
final channelId = channel.storageId;
|
||||
if (channelId == null) return;
|
||||
final senders = direct
|
||||
? recentChannelSenders(context.read<MeshCoreConnector>(), channel)
|
||||
: const <String>[];
|
||||
final service = context.read<ChessService>();
|
||||
final l10n = context.l10n;
|
||||
|
||||
final result = await showMeshSheet<_NewGameChoice>(
|
||||
context,
|
||||
builder: (sheetContext) => DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.8,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.95,
|
||||
builder: (_, controller) => _NewGameBody(
|
||||
direct: direct,
|
||||
senders: senders,
|
||||
controller: controller,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (result == null || !context.mounted) return;
|
||||
if (!ensureRadioConnected(context)) return;
|
||||
final game = await service.createInvite(
|
||||
channelId: channelId,
|
||||
deadline: result.deadline,
|
||||
colour: result.colour,
|
||||
targetName: result.target,
|
||||
);
|
||||
if (!context.mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(
|
||||
game == null
|
||||
? l10n.chess_sendFailed
|
||||
: direct
|
||||
? l10n.chess_challengeSent(result.target ?? '')
|
||||
: l10n.chess_inviteSent,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _NewGameChoice {
|
||||
final String? target;
|
||||
final ChessDeadline deadline;
|
||||
final ChessColourPreference colour;
|
||||
|
||||
const _NewGameChoice(this.target, this.deadline, this.colour);
|
||||
}
|
||||
|
||||
class _NewGameBody extends StatefulWidget {
|
||||
final bool direct;
|
||||
final List<String> senders;
|
||||
final ScrollController controller;
|
||||
|
||||
const _NewGameBody({
|
||||
required this.direct,
|
||||
required this.senders,
|
||||
required this.controller,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_NewGameBody> createState() => _NewGameBodyState();
|
||||
}
|
||||
|
||||
class _NewGameBodyState extends State<_NewGameBody> {
|
||||
String? _target;
|
||||
ChessDeadline _deadline = ChessDeadline.defaultValue;
|
||||
ChessColourPreference _colour = ChessColourPreference.random;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final ready = !widget.direct || _target != null;
|
||||
return Column(
|
||||
children: [
|
||||
BottomSheetHeader(
|
||||
title: widget.direct
|
||||
? l10n.chess_newChallenge
|
||||
: l10n.chess_newOpenInvite,
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: widget.controller,
|
||||
children: [
|
||||
if (widget.direct) ...[
|
||||
SectionHeader(l10n.chess_pickOpponent),
|
||||
if (widget.senders.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(l10n.chess_noRecentSenders),
|
||||
),
|
||||
for (final name in widget.senders)
|
||||
MeshSheetOption(
|
||||
label: name,
|
||||
selected: _target == name,
|
||||
onTap: () => setState(() => _target = name),
|
||||
),
|
||||
],
|
||||
SectionHeader(l10n.chess_deadlineLabel),
|
||||
for (final d in ChessDeadline.values)
|
||||
MeshSheetOption(
|
||||
label: l10n.chessDeadlineLabel(d),
|
||||
selected: _deadline == d,
|
||||
onTap: () => setState(() => _deadline = d),
|
||||
),
|
||||
SectionHeader(l10n.chess_colourLabel),
|
||||
for (final c in ChessColourPreference.values)
|
||||
MeshSheetOption(
|
||||
label: l10n.chessColourLabel(c),
|
||||
selected: _colour == c,
|
||||
onTap: () => setState(() => _colour = c),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton(
|
||||
onPressed: ready
|
||||
? () => Navigator.pop(
|
||||
context,
|
||||
_NewGameChoice(_target, _deadline, _colour),
|
||||
)
|
||||
: null,
|
||||
child: Text(
|
||||
widget.direct
|
||||
? l10n.chess_sendChallenge
|
||||
: l10n.chess_postInvite,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
import '../chess_game.dart';
|
||||
import '../chess_packets.dart';
|
||||
|
||||
/// Localized labels shared by the chess sheet and screen.
|
||||
extension ChessText on AppLocalizations {
|
||||
String chessDeadlineLabel(ChessDeadline d) => switch (d) {
|
||||
ChessDeadline.none => chess_deadlineNone,
|
||||
ChessDeadline.min15 => chess_deadline15m,
|
||||
ChessDeadline.hour1 => chess_deadline1h,
|
||||
ChessDeadline.hours6 => chess_deadline6h,
|
||||
ChessDeadline.day1 => chess_deadline1d,
|
||||
ChessDeadline.days3 => chess_deadline3d,
|
||||
};
|
||||
|
||||
String chessColourLabel(ChessColourPreference c) => switch (c) {
|
||||
ChessColourPreference.random => chess_colourRandom,
|
||||
ChessColourPreference.white => chess_colourWhite,
|
||||
ChessColourPreference.black => chess_colourBlack,
|
||||
};
|
||||
|
||||
String chessEndReason(ChessEndReason r) => switch (r) {
|
||||
ChessEndReason.checkmate => chess_endCheckmate,
|
||||
ChessEndReason.resignation => chess_endResignation,
|
||||
ChessEndReason.timeout => chess_endTimeout,
|
||||
ChessEndReason.drawAgreed => chess_endDrawAgreed,
|
||||
ChessEndReason.stalemate => chess_endStalemate,
|
||||
ChessEndReason.insufficientMaterial => chess_endInsufficient,
|
||||
ChessEndReason.fiftyMoves => chess_endFiftyMoves,
|
||||
ChessEndReason.repetition => chess_endRepetition,
|
||||
ChessEndReason.cancelled => chess_endCancelled,
|
||||
ChessEndReason.declined => chess_endDeclined,
|
||||
ChessEndReason.expired => chess_endExpired,
|
||||
ChessEndReason.taken => chess_endTaken,
|
||||
};
|
||||
|
||||
/// "Alice vs Bob", with placeholders for unknown players.
|
||||
String chessPlayers(ChessGame game) => chess_vs(
|
||||
game.nameOf(ChessSide.white) ?? chess_unknownPlayer,
|
||||
game.nameOf(ChessSide.black) ?? chess_unknownPlayer,
|
||||
);
|
||||
|
||||
/// Result line of a finished game: "Bob won · Checkmate" or "Draw · …".
|
||||
String chessResult(ChessGame game) {
|
||||
final reason = game.endReason;
|
||||
final reasonText = reason == null ? '' : chessEndReason(reason);
|
||||
final winner = game.winner;
|
||||
final noGame = {
|
||||
ChessEndReason.cancelled,
|
||||
ChessEndReason.declined,
|
||||
ChessEndReason.expired,
|
||||
ChessEndReason.taken,
|
||||
}.contains(reason);
|
||||
if (noGame) return reasonText;
|
||||
final head = winner == null
|
||||
? chess_resultDraw
|
||||
: chess_resultWon(game.nameOf(winner) ?? chess_unknownPlayer);
|
||||
return reasonText.isEmpty ? head : chess_resultWithReason(head, reasonText);
|
||||
}
|
||||
|
||||
/// Compact remaining time: "43 min", "5 h 10 min", "2 d 3 h".
|
||||
String chessDuration(Duration d) {
|
||||
if (d.inDays >= 1) return chess_timeDays(d.inDays, d.inHours % 24);
|
||||
if (d.inHours >= 1) return chess_timeHours(d.inHours, d.inMinutes % 60);
|
||||
return chess_timeMinutes(d.inMinutes < 1 ? 1 : d.inMinutes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// GRP_DATA data type registered to MeshCore Open in the firmware's
|
||||
/// `docs/number_allocations.md`. Everything inside it is owned by this app;
|
||||
/// the first payload byte's high nibble says which game (or other app
|
||||
/// feature) the packet belongs to.
|
||||
const int meshcoreOpenDataType = 0x0100;
|
||||
|
||||
/// Largest GRP_DATA payload a companion can deliver to us: the 172-byte
|
||||
/// frame minus the 9-byte RESP_CODE_CHANNEL_DATA_RECV header.
|
||||
const int maxGamePayloadBytes = 163;
|
||||
|
||||
/// Size of the encrypted body on air for a payload of [payloadBytes]: the
|
||||
/// firmware prepends data type (2) and length (1), then pads to the 16-byte
|
||||
/// AES block.
|
||||
int encryptedGamePayloadSize(int payloadBytes) =>
|
||||
((payloadBytes + 3 + 15) ~/ 16) * 16;
|
||||
|
||||
/// App identifiers carried in the high nibble of a packet's first byte.
|
||||
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]`.
|
||||
class GamePacketHeader {
|
||||
static const int length = 4;
|
||||
|
||||
final int app;
|
||||
final int kind;
|
||||
final int gameId;
|
||||
final int ply;
|
||||
|
||||
const GamePacketHeader({
|
||||
required this.app,
|
||||
required this.kind,
|
||||
required this.gameId,
|
||||
required this.ply,
|
||||
});
|
||||
|
||||
void writeTo(BytesBuilder out) {
|
||||
out
|
||||
..addByte(((app & 0x0F) << 4) | (kind & 0x0F))
|
||||
..addByte(gameId & 0xFF)
|
||||
..addByte((gameId >> 8) & 0xFF)
|
||||
..addByte(ply & 0xFF);
|
||||
}
|
||||
|
||||
static GamePacketHeader? parse(Uint8List bytes) {
|
||||
if (bytes.length < length) return null;
|
||||
return GamePacketHeader(
|
||||
app: bytes[0] >> 4,
|
||||
kind: bytes[0] & 0x0F,
|
||||
gameId: bytes[1] | (bytes[2] << 8),
|
||||
ply: bytes[3],
|
||||
);
|
||||
}
|
||||
|
||||
/// The app nibble of [payload], or null when it is too short.
|
||||
static int? appOf(Uint8List payload) =>
|
||||
payload.isEmpty ? null : payload[0] >> 4;
|
||||
}
|
||||
|
||||
/// Sequential reader over a packet body. Every read returns null (and stays
|
||||
/// failed) once the data runs out, so decoders can bail out with one check.
|
||||
class GamePacketReader {
|
||||
final Uint8List _bytes;
|
||||
int _offset;
|
||||
bool _failed = false;
|
||||
|
||||
GamePacketReader(this._bytes, [this._offset = 0]);
|
||||
|
||||
bool get failed => _failed;
|
||||
int get remaining => _failed ? 0 : _bytes.length - _offset;
|
||||
bool get atEnd => remaining == 0;
|
||||
|
||||
int? u8() {
|
||||
if (_failed || _offset + 1 > _bytes.length) return _fail();
|
||||
return _bytes[_offset++];
|
||||
}
|
||||
|
||||
int? u16() {
|
||||
if (_failed || _offset + 2 > _bytes.length) return _fail();
|
||||
final v = _bytes[_offset] | (_bytes[_offset + 1] << 8);
|
||||
_offset += 2;
|
||||
return v;
|
||||
}
|
||||
|
||||
int? u32() {
|
||||
if (_failed || _offset + 4 > _bytes.length) return _fail();
|
||||
final v = ByteData.sublistView(
|
||||
_bytes,
|
||||
_offset,
|
||||
_offset + 4,
|
||||
).getUint32(0, Endian.little);
|
||||
_offset += 4;
|
||||
return v;
|
||||
}
|
||||
|
||||
Uint8List? bytes(int count) {
|
||||
if (_failed || count < 0 || _offset + count > _bytes.length) {
|
||||
return _fail();
|
||||
}
|
||||
final v = Uint8List.fromList(_bytes.sublist(_offset, _offset + count));
|
||||
_offset += count;
|
||||
return v;
|
||||
}
|
||||
|
||||
Uint8List? rest() => bytes(remaining);
|
||||
|
||||
/// A length-prefixed UTF-8 string (see [writeShortString]).
|
||||
String? shortString() {
|
||||
final len = u8();
|
||||
if (len == null) return null;
|
||||
final raw = bytes(len);
|
||||
if (raw == null) return null;
|
||||
return utf8.decode(raw, allowMalformed: true);
|
||||
}
|
||||
|
||||
Null _fail() {
|
||||
_failed = true;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest name, in UTF-8 bytes, a game packet carries.
|
||||
const int maxGameNameBytes = 31;
|
||||
|
||||
/// Writes [value] as a 1-byte length plus UTF-8, truncated on a character
|
||||
/// boundary to [maxGameNameBytes].
|
||||
void writeShortString(BytesBuilder out, String value) {
|
||||
final encoded = truncateUtf8(value, maxGameNameBytes);
|
||||
out
|
||||
..addByte(encoded.length)
|
||||
..add(encoded);
|
||||
}
|
||||
|
||||
/// UTF-8 bytes of [value], cut to at most [maxBytes] without splitting a
|
||||
/// character.
|
||||
Uint8List truncateUtf8(String value, int maxBytes) {
|
||||
final out = BytesBuilder();
|
||||
for (final rune in value.runes) {
|
||||
final encoded = utf8.encode(String.fromCharCode(rune));
|
||||
if (out.length + encoded.length > maxBytes) break;
|
||||
out.add(encoded);
|
||||
}
|
||||
return out.toBytes();
|
||||
}
|
||||
|
||||
void writeU16(BytesBuilder out, int value) {
|
||||
out
|
||||
..addByte(value & 0xFF)
|
||||
..addByte((value >> 8) & 0xFF);
|
||||
}
|
||||
|
||||
void writeU32(BytesBuilder out, int value) {
|
||||
final b = ByteData(4)..setUint32(0, value & 0xFFFFFFFF, Endian.little);
|
||||
out.add(b.buffer.asUint8List());
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// A one-way hash chain used to authenticate a player's actions without
|
||||
/// 64-byte signatures.
|
||||
///
|
||||
/// `v[length] = seed` and `v[i] = H(v[i + 1])`, where H is SHA-256 cut to
|
||||
/// [valueBytes]. The player publishes `v[0]` (the commitment) when joining a
|
||||
/// game and reveals `v[1]`, `v[2]`, … with each later action. Anyone holding
|
||||
/// an earlier value can check a new one by hashing it forward, but only the
|
||||
/// seed holder can produce the next one.
|
||||
class HashChain {
|
||||
static const int length = 512;
|
||||
static const int valueBytes = 16;
|
||||
|
||||
final Uint8List seed;
|
||||
|
||||
HashChain(this.seed) : assert(seed.length == valueBytes);
|
||||
|
||||
factory HashChain.generate([Random? random]) {
|
||||
final rng = random ?? Random.secure();
|
||||
return HashChain(
|
||||
Uint8List.fromList(List.generate(valueBytes, (_) => rng.nextInt(256))),
|
||||
);
|
||||
}
|
||||
|
||||
/// `v[index]`, for `0 <= index <= length`.
|
||||
Uint8List valueAt(int index) {
|
||||
RangeError.checkValueInInterval(index, 0, length, 'index');
|
||||
var v = seed;
|
||||
for (var i = length; i > index; i--) {
|
||||
v = hashChainStep(v);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
Uint8List get commitment => valueAt(0);
|
||||
}
|
||||
|
||||
/// One step towards the commitment: SHA-256 cut to [HashChain.valueBytes].
|
||||
Uint8List hashChainStep(Uint8List value) =>
|
||||
Uint8List.fromList(sha256.convert(value).bytes.sublist(0, 16));
|
||||
|
||||
/// How many chain steps [candidate] lies beyond [lastVerified]: 0 when it is
|
||||
/// the same value (a duplicate), a positive count when hashing it forward
|
||||
/// that many times reaches [lastVerified], or null when it is not on the
|
||||
/// chain within [maxSteps] (forged, or older than [lastVerified]).
|
||||
int? hashChainDistance(
|
||||
Uint8List candidate,
|
||||
Uint8List lastVerified, {
|
||||
int maxSteps = HashChain.length,
|
||||
}) {
|
||||
if (candidate.length != HashChain.valueBytes) return null;
|
||||
if (bytesEqual(candidate, lastVerified)) return 0;
|
||||
var v = candidate;
|
||||
for (var steps = 1; steps <= maxSteps; steps++) {
|
||||
v = hashChainStep(v);
|
||||
if (bytesEqual(v, lastVerified)) return steps;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool bytesEqual(List<int> a, List<int> b) {
|
||||
if (a.length != b.length) return false;
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
if (a[i] != b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user