import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:mchess/chess_bloc/chess_bloc.dart'; import 'chess_square.dart'; import '../utils/chess_utils.dart'; class ChessBoard extends StatelessWidget { final ChessBoardState bState; final List squares; const ChessBoard._({required this.bState, required this.squares}); factory ChessBoard({required ChessBoardState bState}) { List squares = List.empty(growable: true); for (int i = 0; i < 64; i++) { var column = (i % 8) + 1; var row = (i ~/ 8) + 1; final piece = bState.position[ChessCoordinate(column, row)]; squares.add( ChessSquare( ChessCoordinate(column, row), piece, ), ); } return ChessBoard._(bState: bState, squares: squares); } @override Widget build(BuildContext context) { log("ChessBoard's build()"); return Container( decoration: const BoxDecoration( boxShadow: [BoxShadow(color: Colors.black, offset: Offset(10, 10))]), child: _buildBoard(bState.bottomColor == ChessColor.black), ); } 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) ], ); } } Column _buildBoard(bool flipped) { List chessBoard = []; 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 Column(children: [...chessBoard]); } ChessSquare getSquareAtCoordinate(ChessCoordinate coord) { /* Calculate index in squares[] from column and row */ int index = (coord.row - 1) * 8 + (coord.column - 1); log("getSquareAtCoordinates: index calculated to $index"); return squares.elementAt(index); } }