mchess-client/lib/utils/widgets/move_history_widget.dart

90 lines
2.3 KiB
Dart
Raw Permalink Normal View History

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_bloc.dart';
import 'package:mchess/chess_bloc/chess_position.dart';
import 'package:mchess/utils/chess_utils.dart';
class MoveHistory extends StatefulWidget {
const MoveHistory({super.key});
@override
State<MoveHistory> createState() => _MoveHistoryState();
}
class _MoveHistoryState extends State<MoveHistory> {
2023-08-25 10:11:23 +00:00
ChessMoveHistory allMoves = [];
List<HistoryEntry> entries = [];
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
2023-08-25 10:11:23 +00:00
return BlocBuilder<ChessBloc, ChessBoardState>(builder: (context, state) {
//We do not use the state, we just use the ChessBloc as a trigger
var positionManager = ChessPositionManager.getInstance();
if (positionManager.lastMove == null) return Container();
var pieceMoved = positionManager.getPieceAt(positionManager.lastMove!.to);
var pieceChar = pieceCharacter[ChessPieceAssetKey(
//we take the opposite color because we use dark theme. White pieces appear black and vice versa.
pieceClass: pieceMoved!.pieceClass,
color: pieceMoved.color.getOpposite())];
if (pieceMoved.color == ChessColor.white) {
var entry = HistoryEntry();
entry.setWhite(
pieceChar!, positionManager.lastMove!.to.toAlphabetical());
entries.add(entry);
} else {
var entry = entries.last;
entry.setBlack(
pieceChar!, positionManager.lastMove!.to.toAlphabetical());
}
return ListView.builder(
itemCount: entries.length,
itemBuilder: (context, index) {
return Text(
entries[index].toString(),
style: const TextStyle(fontSize: 20),
);
},
);
});
}
}
class HistoryEntry {
String? wChar;
String? wTo;
String? bChar;
String? bTo;
HistoryEntry();
void setWhite(String char, to) {
wChar = char;
wTo = to;
}
void setBlack(String char, to) {
bChar = char;
bTo = to;
}
@override
String toString() {
String entry = "";
if (wChar != null) {
entry = "$entry$wChar$wTo";
}
if (bChar != null) {
entry = "$entry\t\t$bChar$bTo";
}
return entry;
}
}