import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mchess/chessapp/chess_board.dart'; import 'package:mchess/chessapp/chess_utils.dart'; import 'package:mchess/chessapp/chess_square.dart'; class ChessBloc extends Bloc { static final ChessBloc _instance = ChessBloc._internal(); ChessBloc._internal() : super(ChessBoardState.init()) { on(moveHandler); on(preCheckHandler); } factory ChessBloc.getInstance() { return ChessBloc(); } factory ChessBloc() { return _instance; } FutureOr moveHandler( PieceMoved event, Emitter emit, ) { Map newPosition = {}; newPosition[event.endSquare] = state.position[event.startSquare]!; newPosition[event.startSquare] = const ChessPiece.none(); print('emitting new state with position $newPosition'); emit(ChessBoardState( state.flipped, ChessColor.black, newPosition, )); } FutureOr preCheckHandler( PreCheckMove event, Emitter emit, ) { return false; } } abstract class ChessEvent {} class PieceMoved extends ChessEvent { final ChessCoordinate startSquare; final ChessCoordinate endSquare; PieceMoved({required this.startSquare, required this.endSquare}); } class PreCheckMove extends ChessEvent {} class BoardFlippedEvent extends ChessEvent {} class ChessBoardState { final bool flipped; final ChessColor turnColor; final Map position; ChessBoardState._(this.flipped, this.turnColor, this.position); factory ChessBoardState( bool flipped, ChessColor turnColor, Map position, ) { return ChessBoardState._(flipped, turnColor, position); } factory ChessBoardState.init() { bool flipped = false; ChessColor turnColor = ChessColor.white; Map position = {}; for (int row = 1; row <= 8; row++) { for (int col = 1; col <= 8; col++) { position[ChessCoordinate(row, col)] = ChessPiece(ChessPieceName.none, ChessColor.white); if (col == 1 && row == 4) { position[ChessCoordinate(col, row)] = ChessPiece(ChessPieceName.blackKing, ChessColor.black); } } } return ChessBoardState._(flipped, turnColor, position); } }