98 lines
2.4 KiB
Dart
98 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[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<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);
|
|
if (col == 1 && row == 4) {
|
|
position[ChessCoordinate(col, row)] =
|
|
ChessPiece(ChessPieceName.blackKing, ChessColor.black);
|
|
}
|
|
}
|
|
}
|
|
|
|
return ChessBoardState._(flipped, turnColor, position);
|
|
}
|
|
}
|