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[ChessCoordinate(5, 5)] = ChessPiece(ChessPieceName.blackBishop, ChessColor.black); ChessPiece? piece = state.position[ChessCoordinate.copyFrom(event.startSquare)]; newPosition[event.endSquare] = piece!; newPosition[event.startSquare] = const ChessPiece.none(); 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); } } return ChessBoardState._(flipped, turnColor, position); } }