Many many changes.

This commit is contained in:
Marco 2022-12-18 01:04:08 +01:00
parent c04407ae67
commit 2ad028f8a7
8 changed files with 160 additions and 121 deletions

View File

@ -1,19 +1,16 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_events.dart'; import 'package:mchess/chess_bloc/chess_events.dart';
import 'package:mchess/chessapp/chess_utils.dart'; import 'package:mchess/chessapp/chess_utils.dart';
import 'package:mchess/connection/ws_connection.dart';
import 'dart:developer'; import 'dart:developer';
int message_index = 0;
class ChessBloc extends Bloc<ChessEvent, ChessBoardState> { class ChessBloc extends Bloc<ChessEvent, ChessBoardState> {
static final ChessBloc _instance = ChessBloc._internal(); static final ChessBloc _instance = ChessBloc._internal();
late ChessColor? myColor;
ChessBloc._internal() : super(ChessBoardState.init()) { ChessBloc._internal() : super(ChessBoardState.init()) {
on<InitBoard>(initBoard);
on<ColorDetermined>(flipBoard);
on<PieceMoved>(moveHandler); on<PieceMoved>(moveHandler);
on<BoardFlippedEvent>(flipBoard);
} }
factory ChessBloc.getInstance() { factory ChessBloc.getInstance() {
@ -24,52 +21,52 @@ class ChessBloc extends Bloc<ChessEvent, ChessBoardState> {
return _instance; return _instance;
} }
FutureOr<void> moveHandler(PieceMoved event, Emitter<ChessBoardState> emit) { void initBoard(InitBoard event, Emitter<ChessBoardState> emit) {
emit(ChessBoardState.init());
}
void flipBoard(ColorDetermined event, Emitter<ChessBoardState> emit) {
emit(ChessBoardState(event.myColor, state.newTurnColor, state.position));
}
void moveHandler(PieceMoved event, Emitter<ChessBoardState> emit) {
Map<ChessCoordinate, ChessPiece> newPosition = state.position; Map<ChessCoordinate, ChessPiece> newPosition = state.position;
newPosition[event.endSquare] = state.position[event.startSquare]!; newPosition[event.endSquare] = state.position[event.startSquare]!;
newPosition[event.startSquare] = const ChessPiece.none(); newPosition[event.startSquare] = const ChessPiece.none();
var newTurnColor = state.newTurnColor == ChessColor.white
? ChessColor.black
: ChessColor.white;
log('emitting new state with position $newPosition'); log('emitting new state with position $newPosition');
emit(ChessBoardState( emit(
state.flipped, ChessBoardState(
ChessColor.black, state.bottomColor,
newTurnColor,
newPosition, newPosition,
)); ),
} );
bool preCheckHandler(
PreCheckMove event,
) {
ServerConnection.getInstance().send(
'${message_index++} pc ${event.move.startSquare.toString()} ${event.move.endSquare.toString()}');
log('Pretending to check a move before you drop a piece');
return true;
}
void flipBoard(BoardFlippedEvent event, Emitter<ChessBoardState> emit) {
emit(ChessBoardState(!state.flipped, state.turnColor, state.position));
} }
} }
class ChessBoardState { class ChessBoardState {
late bool flipped; late ChessColor bottomColor;
final ChessColor turnColor; final ChessColor newTurnColor;
final Map<ChessCoordinate, ChessPiece> position; final Map<ChessCoordinate, ChessPiece> position;
ChessBoardState._(this.flipped, this.turnColor, this.position); ChessBoardState._(this.bottomColor, this.newTurnColor, this.position);
factory ChessBoardState( factory ChessBoardState(
bool flipped, ChessColor bottomColor,
ChessColor turnColor, ChessColor turnColor,
Map<ChessCoordinate, ChessPiece> position, Map<ChessCoordinate, ChessPiece> position,
) { ) {
return ChessBoardState._(flipped, turnColor, position); return ChessBoardState._(bottomColor, turnColor, position);
} }
factory ChessBoardState.init() { factory ChessBoardState.init() {
bool flipped = false; ChessColor bottomColor = ChessColor.white;
ChessColor turnColor = ChessColor.white; ChessColor turnColor = ChessColor.white;
Map<ChessCoordinate, ChessPiece> position = {}; Map<ChessCoordinate, ChessPiece> position = {};
@ -114,6 +111,6 @@ class ChessBoardState {
position[ChessCoordinate(8, 1)] = position[ChessCoordinate(8, 1)] =
ChessPiece(ChessPieceName.whiteRook, ChessColor.black); ChessPiece(ChessPieceName.whiteRook, ChessColor.black);
return ChessBoardState._(flipped, turnColor, position); return ChessBoardState._(bottomColor, turnColor, position);
} }
} }

View File

@ -9,10 +9,12 @@ class PieceMoved extends ChessEvent {
PieceMoved({required this.startSquare, required this.endSquare}); PieceMoved({required this.startSquare, required this.endSquare});
} }
class PreCheckMove extends ChessEvent { class InitBoard extends ChessEvent {
final ChessMove move; InitBoard();
PreCheckMove({required this.move});
} }
class BoardFlippedEvent extends ChessEvent {} class ColorDetermined extends ChessEvent {
final ChessColor myColor;
ColorDetermined({required this.myColor});
}

View File

@ -1,13 +1,14 @@
import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_bloc.dart'; import 'package:mchess/chess_bloc/chess_bloc.dart';
import 'package:mchess/connection/ws_connection.dart';
import 'package:mchess/chessapp/chess_board.dart'; import 'package:mchess/chessapp/chess_board.dart';
import 'package:mchess/chessapp/turn_indicator_widget.dart';
import 'package:mchess/connection_cubit/connection_cubit.dart'; import 'package:mchess/connection_cubit/connection_cubit.dart';
import '../connection/ws_connection.dart';
import '../utils/widgets/server_log_widget.dart';
class ChessApp extends StatelessWidget { class ChessApp extends StatelessWidget {
const ChessApp({super.key}); const ChessApp({super.key});
@ -15,6 +16,8 @@ class ChessApp extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider( return BlocProvider(
create: (_) => ConnectionCubit.getInstance(), create: (_) => ConnectionCubit.getInstance(),
child: BlocProvider(
create: (_) => ChessBloc.getInstance(),
child: MaterialApp( child: MaterialApp(
title: 'mChess', title: 'mChess',
home: Scaffold( home: Scaffold(
@ -33,12 +36,19 @@ class ChessApp extends StatelessWidget {
child: Center( child: Center(
child: FittedBox( child: FittedBox(
fit: BoxFit.contain, fit: BoxFit.contain,
child: Column( child: Row(
children: [ children: [
StreamBuilder(
stream: ServerConnection.getInstance().broadcast,
builder: (context, snapshot) {
return ServerLogWidget(
snapshot.data ?? "<snapshot empty>",
textColor: Colors.white,
);
},
),
Container( Container(
margin: const EdgeInsets.all(20), margin: const EdgeInsets.all(20),
child: BlocProvider(
create: (_) => ChessBloc.getInstance(),
child: BlocBuilder<ChessBloc, ChessBoardState>( child: BlocBuilder<ChessBloc, ChessBoardState>(
builder: (context, state) { builder: (context, state) {
return ChessBoard( return ChessBoard(
@ -47,23 +57,10 @@ class ChessApp extends StatelessWidget {
}, },
), ),
), ),
), const TurnIndicator(),
BlocBuilder<ConnectionCubit, ConnectionCubitState>(
builder: (context, state) {
return StreamBuilder(
stream: ServerConnection.getInstance().broadcast,
builder: (context, snapshot) {
return Text(
style: const TextStyle(color: Colors.white),
snapshot.data.toString());
},
);
},
)
], ],
), ),
), )),
),
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: () { onPressed: () {
@ -73,6 +70,7 @@ class ChessApp extends StatelessWidget {
), ),
), ),
), ),
),
); );
} }
} }

View File

@ -34,7 +34,9 @@ class ChessBoard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
log("ChessBoard's build()"); log("ChessBoard's build()");
return Column(children: _buildBoard(bState.flipped));
return Column(
children: _buildBoard(bState.bottomColor == ChessColor.black));
} }
Row _buildChessRow(int rowNo, bool flipped) { Row _buildChessRow(int rowNo, bool flipped) {

View File

@ -1,5 +1,3 @@
import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@ -9,6 +7,8 @@ import 'package:mchess/chess_bloc/chess_bloc.dart';
import '../connection/ws_connection.dart'; import '../connection/ws_connection.dart';
import 'chess_utils.dart'; import 'chess_utils.dart';
int message_index = 0;
class ChessSquare extends StatelessWidget { class ChessSquare extends StatelessWidget {
final ChessCoordinate coordinate; final ChessCoordinate coordinate;
final ChessPiece? containedPiece; final ChessPiece? containedPiece;
@ -85,13 +85,6 @@ class ChessSquare extends StatelessWidget {
), ),
); );
}, },
// onWillAccept: (move) {
// move!.endSquare = coordinate;
// final legalMove =
// context.read<ChessBloc>().preCheckHandler(PreCheckMove(move: move));
// log('onWillAccept returns $legalMove');
// return legalMove;
// },
onAccept: (move) { onAccept: (move) {
move.endSquare = coordinate; move.endSquare = coordinate;

View File

@ -0,0 +1,19 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_bloc.dart';
import 'chess_utils.dart';
class TurnIndicator extends StatelessWidget {
const TurnIndicator({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<ChessBloc, ChessBoardState>(
builder: (context, state) => Text(
state.newTurnColor == ChessColor.white ? "white" : "black",
style: const TextStyle(color: Colors.white),
),
);
}
}

View File

@ -6,7 +6,7 @@ import 'package:mchess/chessapp/chess_utils.dart';
import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:web_socket_channel/web_socket_channel.dart';
class ServerConnection { class ServerConnection {
late WebSocketChannel _channel; late WebSocketChannel channel;
late bool wasConnected = false; late bool wasConnected = false;
late int counter = 0; late int counter = 0;
late Stream broadcast; late Stream broadcast;
@ -27,45 +27,44 @@ class ServerConnection {
} }
void send(String message) { void send(String message) {
_channel.sink.add(message); channel.sink.add(message);
counter++; counter++;
} }
void connect() { void connect() {
if (wasConnected) _channel.sink.close(); if (wasConnected) channel.sink.close();
_channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8080')); channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8080'));
wasConnected = true; wasConnected = true;
broadcast = _channel.stream.asBroadcastStream(); broadcast = channel.stream.asBroadcastStream();
broadcast.listen((data) { broadcast.listen((data) {
log("Data received:"); log("Data received:");
log(data); log(data);
var receivedString = data.toString(); var receivedString = data.toString();
var splitString = receivedString.split(' ');
if (receivedString == "fb") { if (splitString[0] == "cl") {
ChessBloc.getInstance().add(BoardFlippedEvent()); ChessColor onBottom =
splitString[1] == "white" ? ChessColor.white : ChessColor.black;
ChessBloc.getInstance().add(ColorDetermined(myColor: onBottom));
return; return;
} }
var moveStringList = receivedString.split(' '); if (splitString[0] == "bd") {
if (moveStringList[1] == ('mv')) { if (splitString[1] == "init") ChessBloc.getInstance().add(InitBoard());
var startSquare = ChessCoordinate.fromString(moveStringList[2]); }
var endSquare = ChessCoordinate.fromString(moveStringList[3]);
log('Move received : ${moveStringList[2]}:${moveStringList[3]}'); if (splitString[1] == ('mv')) {
var startSquare = ChessCoordinate.fromString(splitString[2]);
var endSquare = ChessCoordinate.fromString(splitString[3]);
log('Move received : ${splitString[2]}:${splitString[3]}');
ChessBloc.getInstance() ChessBloc.getInstance()
.add(PieceMoved(startSquare: startSquare, endSquare: endSquare)); .add(PieceMoved(startSquare: startSquare, endSquare: endSquare));
} }
}); });
sendPassword();
}
void sendPassword() {
send(
'pw NC4EjHvRcsltY3ibWuYDH9OXbKgDXppfnHNCi1K4jktMspoeZjBnOPExxCpDms7zmxijoKCSaSlZ1fWclfWr7Q32DJnv2k87Z5uM');
} }
} }

View File

@ -0,0 +1,29 @@
import 'package:flutter/widgets.dart';
class ServerLogWidget extends StatefulWidget {
final Color textColor;
final String addString;
const ServerLogWidget(this.addString, {required this.textColor, super.key});
@override
State<StatefulWidget> createState() => ServerLogWidgetState();
}
class ServerLogWidgetState extends State<ServerLogWidget> {
List<String> log = [];
ServerLogWidgetState();
@override
Widget build(BuildContext context) {
log.add(widget.addString);
return Column(
children: [
for (int i = 0; i < log.length; i++)
Text(style: TextStyle(color: widget.textColor, fontSize: 20), log[i])
],
);
}
}