mchess-client/lib/chess_bloc/chess_bloc.dart

77 lines
2.1 KiB
Dart
Raw Normal View History

2022-11-13 00:03:09 +00:00
import 'dart:async';
2022-11-13 00:03:09 +00:00
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_events.dart';
2022-11-13 00:03:09 +00:00
import 'package:mchess/chessapp/chess_utils.dart';
import 'package:mchess/connection/ws_connection.dart';
2022-11-13 00:03:09 +00:00
class ChessBloc extends Bloc<ChessEvent, ChessBoardState> {
static final ChessBloc _instance = ChessBloc._internal();
ChessBloc._internal() : super(ChessBoardState.init()) {
on<PieceMoved>(moveHandler);
}
factory ChessBloc.getInstance() {
return ChessBloc();
}
factory ChessBloc() {
return _instance;
}
FutureOr<void> moveHandler(PieceMoved event, Emitter<ChessBoardState> emit) {
Map<ChessCoordinate, ChessPiece> newPosition = {};
ServerConnection.getInstance().send(
'from: ${event.startSquare.toString()} to: ${event.endSquare.toString()}');
2022-11-13 02:24:42 +00:00
newPosition[event.endSquare] = state.position[event.startSquare]!;
newPosition[event.startSquare] = const ChessPiece.none();
2022-11-13 02:24:42 +00:00
print('emitting new state with position $newPosition');
2022-11-13 00:03:09 +00:00
emit(ChessBoardState(
state.flipped,
2022-11-13 00:03:09 +00:00
ChessColor.black,
newPosition,
2022-11-13 00:03:09 +00:00
));
}
bool preCheckHandler(
PreCheckMove event,
) {
ServerConnection.getInstance().send(
'from: ${event.move.startSquare.toString()} to: ${event.move.endSquare.toString()}');
2022-11-13 02:42:30 +00:00
print('Pretending to check a move before you drop a piece');
return true;
}
2022-11-13 00:03:09 +00:00
}
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 = {};
2022-11-13 00:03:09 +00:00
2022-11-13 02:42:30 +00:00
position[ChessCoordinate(1, 1)] =
ChessPiece(ChessPieceName.blackKing, ChessColor.black);
return ChessBoardState._(flipped, turnColor, position);
}
2022-11-13 00:03:09 +00:00
}