More changes. Memory error when accessing state.position in ChessBloc.

This commit is contained in:
Marco 2022-11-13 02:42:10 +01:00
parent 94b7c227c9
commit b3a7418c5f
4 changed files with 83 additions and 29 deletions

View File

@ -1,6 +1,8 @@
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';
@ -10,6 +12,7 @@ class ChessBloc extends Bloc<ChessEvent, ChessBoardState> {
ChessBloc._internal() : super(ChessBoardState.init()) {
on<PieceMoved>(moveHandler);
on<PreCheckMove>(preCheckHandler);
}
factory ChessBloc.getInstance() {
@ -24,17 +27,42 @@ class ChessBloc extends Bloc<ChessEvent, ChessBoardState> {
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,
state.flipped,
ChessColor.black,
state.position,
newPosition,
));
}
FutureOr<bool> preCheckHandler(
PreCheckMove event,
Emitter<ChessBoardState> emit,
) {
return false;
}
}
abstract class ChessEvent {}
class PieceMoved extends 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 {}
@ -43,10 +71,28 @@ class ChessBoardState {
final ChessColor turnColor;
final Map<ChessCoordinate, ChessPiece> position;
ChessBoardState(this.flipped, this.turnColor, this.position);
ChessBoardState._(this.flipped, this.turnColor, this.position);
ChessBoardState.init()
: flipped = false,
turnColor = ChessColor.white,
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);
}
}

2