2022-11-12 21:55:45 +00:00
|
|
|
import 'package:flutter/material.dart';
|
2022-11-13 00:03:47 +00:00
|
|
|
import 'package:mchess/chess_bloc/chess_bloc.dart';
|
2022-11-12 21:55:45 +00:00
|
|
|
|
|
|
|
import 'chess_square.dart';
|
|
|
|
import 'chess_utils.dart';
|
|
|
|
|
2022-11-13 00:03:47 +00:00
|
|
|
class ChessBoard extends StatelessWidget {
|
|
|
|
final ChessBoardState bState;
|
|
|
|
final List<ChessSquare> squares;
|
2022-11-12 21:55:45 +00:00
|
|
|
|
2022-11-13 01:42:10 +00:00
|
|
|
const ChessBoard._({required this.bState, required this.squares});
|
2022-11-12 21:55:45 +00:00
|
|
|
|
2022-11-13 00:03:47 +00:00
|
|
|
factory ChessBoard({required ChessBoardState bState}) {
|
|
|
|
List<ChessSquare> squares = List.empty(growable: true);
|
2022-11-12 21:55:45 +00:00
|
|
|
for (int i = 0; i < 64; i++) {
|
|
|
|
var column = (i % 8) + 1;
|
|
|
|
var row = (i ~/ 8) + 1;
|
|
|
|
|
2022-11-13 02:24:42 +00:00
|
|
|
final piece = bState.position[ChessCoordinate(column, row)];
|
|
|
|
|
2022-11-12 21:55:45 +00:00
|
|
|
squares.add(
|
|
|
|
ChessSquare(
|
2022-11-13 12:09:36 +00:00
|
|
|
ChessCoordinate(column, row),
|
|
|
|
piece,
|
2022-11-12 21:55:45 +00:00
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-11-13 00:03:47 +00:00
|
|
|
return ChessBoard._(bState: bState, squares: squares);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Widget build(BuildContext context) {
|
2022-11-13 02:42:30 +00:00
|
|
|
print("ChessBoard's build()");
|
|
|
|
return Column(children: _buildBoard(bState.flipped));
|
2022-11-12 21:55:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Row _buildChessRow(int rowNo, bool flipped) {
|
|
|
|
if (!flipped) {
|
|
|
|
return Row(
|
|
|
|
children: [
|
|
|
|
for (int i = 8 * rowNo - 8; i < 8 * rowNo; i++) squares.elementAt(i)
|
|
|
|
],
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
return Row(
|
|
|
|
children: [
|
|
|
|
for (int i = 8 * rowNo - 1; i >= 8 * rowNo - 8; i--)
|
|
|
|
squares.elementAt(i)
|
|
|
|
],
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
List<Row> _buildBoard(bool flipped) {
|
|
|
|
List<Row> chessBoard = <Row>[];
|
|
|
|
|
|
|
|
if (!flipped) {
|
|
|
|
for (int row = 8; row > 0; row--) {
|
|
|
|
chessBoard.add(_buildChessRow(row, flipped));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
for (int row = 1; row <= 8; row++) {
|
|
|
|
chessBoard.add(_buildChessRow(row, flipped));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return chessBoard;
|
|
|
|
}
|
|
|
|
|
|
|
|
ChessSquare getSquareAtCoordinate(ChessCoordinate coord) {
|
|
|
|
/* Calculate index in squares[] from column and row */
|
|
|
|
int index = (coord.row - 1) * 8 + (coord.column - 1);
|
|
|
|
|
|
|
|
print("getSquareAtCoordinates: index calculated to $index");
|
|
|
|
|
|
|
|
return squares.elementAt(index);
|
|
|
|
}
|
|
|
|
}
|