mchess-client/lib/chess_bloc/chess_bloc.dart

99 lines
2.4 KiB
Dart

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<ChessEvent, ChessBoardState> {
static final ChessBloc _instance = ChessBloc._internal();
ChessBloc._internal() : super(ChessBoardState.init()) {
on<PieceMoved>(moveHandler);
on<PreCheckMove>(preCheckHandler);
}
factory ChessBloc.getInstance() {
return ChessBloc();
}
factory ChessBloc() {
return _instance;
}
FutureOr<void> moveHandler(
PieceMoved event,
Emitter<ChessBoardState> emit,
) {
Map<ChessCoordinate, ChessPiece> 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<bool> preCheckHandler(
PreCheckMove event,
Emitter<ChessBoardState> 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<ChessCoordinate, ChessPiece> position;
ChessBoardState._(this.flipped, this.turnColor, this.position);
factory ChessBoardState(
bool flipped,
ChessColor turnColor,
Map<ChessCoordinate, ChessPiece> position,
) {
return ChessBoardState._(flipped, turnColor, position);
}
factory ChessBoardState.init() {
bool flipped = false;
ChessColor turnColor = ChessColor.white;
Map<ChessCoordinate, ChessPiece> 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);
}
}