Add chess games over channel data

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

No files matched your search

+314
View File
@@ -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,
),
),
),
),
],
),
),
),
);
}
}
+437
View File
@@ -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)),
],
),
);
}
}
+447
View File
@@ -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,
),
),
),
),
],
);
}
}
+67
View File
@@ -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);
}
}