From ba947ae5e4753547d3a19eea061d3aa1164b303b Mon Sep 17 00:00:00 2001 From: Marco Date: Mon, 25 Dec 2023 17:50:58 +0100 Subject: [PATCH] Fix routing and move handling --- lib/api/websocket_message.dart | 2 +- lib/chess/chess_app.dart | 2 +- lib/chess/chess_square_outer_dragtarget.dart | 4 +- lib/chess_bloc/chess_bloc.dart | 7 +- lib/chess_bloc/chess_position.dart | 9 ++ lib/connection/ws_connection.dart | 22 +---- lib/pages/chess_game.dart | 6 +- lib/pages/host_game.dart | 4 +- lib/pages/lobby_selector.dart | 6 +- lib/pages/prepare_random_game.dart | 91 -------------------- lib/utils/chess_router.dart | 7 -- 11 files changed, 24 insertions(+), 136 deletions(-) delete mode 100644 lib/pages/prepare_random_game.dart diff --git a/lib/api/websocket_message.dart b/lib/api/websocket_message.dart index 79df52d..67cb0b8 100644 --- a/lib/api/websocket_message.dart +++ b/lib/api/websocket_message.dart @@ -44,7 +44,7 @@ class ApiWebsocketMessage { case MessageType.boardState: ret = ApiWebsocketMessage( type: type, - move: null, + move: ApiMove.fromJson(json['move']), turnColor: ApiColor.fromJson(json['turnColor']), reason: null, position: json['position'], diff --git a/lib/chess/chess_app.dart b/lib/chess/chess_app.dart index e491605..18e2595 100644 --- a/lib/chess/chess_app.dart +++ b/lib/chess/chess_app.dart @@ -27,7 +27,7 @@ class ChessApp extends StatelessWidget { useMaterial3: true, ), routerConfig: ChessAppRouter.getInstance().router, - title: 'mChess', + title: 'mChess 0.1339', ), ); } diff --git a/lib/chess/chess_square_outer_dragtarget.dart b/lib/chess/chess_square_outer_dragtarget.dart index cc02099..7155144 100644 --- a/lib/chess/chess_square_outer_dragtarget.dart +++ b/lib/chess/chess_square_outer_dragtarget.dart @@ -10,9 +10,7 @@ class ChessSquareOuterDragTarget extends StatelessWidget { final ChessPiece containedPiece; const ChessSquareOuterDragTarget( - {super.key, - required this.coordinate, - required this.containedPiece}); + {super.key, required this.coordinate, required this.containedPiece}); @override Widget build(BuildContext context) { diff --git a/lib/chess_bloc/chess_bloc.dart b/lib/chess_bloc/chess_bloc.dart index f419412..2f76146 100644 --- a/lib/chess_bloc/chess_bloc.dart +++ b/lib/chess_bloc/chess_bloc.dart @@ -67,12 +67,9 @@ class ChessBloc extends Bloc { void moveAndPositionHandler( ReceivedBoardState event, Emitter emit) { - turnColor = state.newTurnColor == ChessColor.white - ? ChessColor.black - : ChessColor.white; - ChessMove? move; - if (event.startSquare != null && event.endSquare != null) { + if (event.startSquare != ChessCoordinate.none() && + event.endSquare != ChessCoordinate.none()) { move = ChessMove(from: event.startSquare!, to: event.endSquare!); ChessPositionManager.getInstance() .recordMove(event.startSquare, event.endSquare, event.position); diff --git a/lib/chess_bloc/chess_position.dart b/lib/chess_bloc/chess_position.dart index 6449930..f01753e 100644 --- a/lib/chess_bloc/chess_position.dart +++ b/lib/chess_bloc/chess_position.dart @@ -95,6 +95,15 @@ class ChessPositionManager { return _instance; } + static ChessPosition _getDebugPostion() { + ChessPosition pos = {}; + + pos[ChessCoordinate(7, 7)] = + ChessPiece(ChessPieceClass.pawn, ChessColor.white); + + return pos; + } + static ChessPosition _getStartingPosition() { ChessPosition pos = {}; diff --git a/lib/connection/ws_connection.dart b/lib/connection/ws_connection.dart index 8b03211..16114ff 100644 --- a/lib/connection/ws_connection.dart +++ b/lib/connection/ws_connection.dart @@ -68,7 +68,7 @@ class ServerConnection { } void handleIncomingData(dynamic data) { - log("Data received:"); + log('${DateTime.now()}: Data received:'); log(data); var apiMessage = ApiWebsocketMessage.fromJson(jsonDecode(data)); @@ -82,7 +82,7 @@ class ServerConnection { break; case MessageType.move: - handleIncomingMoveMessage(apiMessage); + log('ERROR: move message received'); break; case MessageType.invalidMove: @@ -119,24 +119,6 @@ class ServerConnection { myColor: ChessColor.fromApiColor(apiMessage.playerColor!))); } - void handleIncomingMoveMessage(ApiWebsocketMessage apiMessage) { - if (apiMessage.position != null) { - var move = ChessMove.fromApiMove(apiMessage.move!); - ChessBloc.getInstance().add( - ReceivedBoardState( - startSquare: move.from, - endSquare: move.to, - position: ChessPositionManager.getInstance() - .fromPGNString(apiMessage.position!), - squareInCheck: ChessCoordinate.fromApiCoordinate( - apiMessage.squareInCheck ?? const ApiCoordinate(col: 0, row: 0)), - ), - ); - } else { - log('Error: no position received'); - } - } - void handleInvalidMoveMessage(ApiWebsocketMessage apiMessage) { log("invalid move message received, with move: ${apiMessage.move.toString()}"); ChessBloc.getInstance().add( diff --git a/lib/pages/chess_game.dart b/lib/pages/chess_game.dart index 55971d6..7fb7d92 100644 --- a/lib/pages/chess_game.dart +++ b/lib/pages/chess_game.dart @@ -37,9 +37,9 @@ class _ChessGameState extends State { child: Container( margin: const EdgeInsets.all(10), child: BlocListener( - listener: (context, state) { + listener: (listenerContext, state) { if (state.showPromotionDialog) { - promotionDialogBuilder(context, state.colorMoved); + promotionDialogBuilder(listenerContext, state.colorMoved); } }, child: BlocBuilder( @@ -55,7 +55,7 @@ class _ChessGameState extends State { floatingActionButton: FloatingActionButton( onPressed: () { ServerConnection.getInstance().disconnectExistingConnection(); - context.push('/'); + GoRouter.of(context).goNamed('lobbySelector'); }, child: const Icon(Icons.cancel), ), diff --git a/lib/pages/host_game.dart b/lib/pages/host_game.dart index be2f302..c8076d7 100644 --- a/lib/pages/host_game.dart +++ b/lib/pages/host_game.dart @@ -70,7 +70,7 @@ class _HostGameWidgetState extends State { listener: (context, state) { // We wait for our opponent to connect if (state.opponentConnected) { - context.push('/game', extra: chessGameArgs); + context.goNamed('game', extra: chessGameArgs); } }, child: Column( @@ -98,7 +98,7 @@ class _HostGameWidgetState extends State { floatingActionButton: FloatingActionButton( child: const Icon(Icons.cancel), onPressed: () { - context.push('/'); + context.pop(); }, ), ); diff --git a/lib/pages/lobby_selector.dart b/lib/pages/lobby_selector.dart index dbedeb6..1afa481 100644 --- a/lib/pages/lobby_selector.dart +++ b/lib/pages/lobby_selector.dart @@ -74,7 +74,7 @@ class _LobbySelectorState extends State { TextButton( child: const Text('Host'), onPressed: () { - context.push('/host'); + context.push('/host'); //replaces joinOrHostDialog }, ), TextButton( @@ -137,7 +137,7 @@ class _LobbySelectorState extends State { ); if (!chessGameArgs.isValid()) { - context.push('/'); + context.goNamed('lobbySelector'); const snackBar = SnackBar( backgroundColor: Colors.amberAccent, content: Text("Game information is corrupted"), @@ -146,7 +146,7 @@ class _LobbySelectorState extends State { ScaffoldMessenger.of(context).showSnackBar(snackBar); } - context.push('/game', extra: chessGameArgs); + context.pushReplacement('/game', extra: chessGameArgs); } Future joinPrivateGame() async { diff --git a/lib/pages/prepare_random_game.dart b/lib/pages/prepare_random_game.dart deleted file mode 100644 index 454e197..0000000 --- a/lib/pages/prepare_random_game.dart +++ /dev/null @@ -1,91 +0,0 @@ -import 'dart:developer'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:go_router/go_router.dart'; -import 'package:http/http.dart'; -import 'package:mchess/api/register.dart'; -import 'package:mchess/pages/chess_game.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; - -class PrepareRandomGameWidget extends StatefulWidget { - const PrepareRandomGameWidget({super.key}); - - @override - State createState() => - _PrepareRandomGameWidgetState(); -} - -class _PrepareRandomGameWidgetState extends State { - late Future randomGameResponse; - - @override - void initState() { - randomGameResponse = registerForRandomGame(); - goToGameWhenResponseIsHere(randomGameResponse as Future); - super.initState(); - } - - void goToGameWhenResponseIsHere(Future resp) { - resp.then((value) { - if (value == null) return; - context.push( - '/game', - extra: ChessGameArguments( - lobbyID: value.lobbyID!, - playerID: value.playerID!, - passphrase: value.passphrase), - ); - }); - } - - @override - Widget build(BuildContext context) { - return const Scaffold( - body: Center( - child: SizedBox( - height: 100, - width: 100, - child: CircularProgressIndicator(), - ), - ), - ); - } - - Future registerForRandomGame() async { - String addr; - Response response; - - if (kDebugMode) { - addr = 'http://localhost:8080/api/random'; - } else { - addr = 'https://chess.sw-gross.de:9999/api/random'; - } - - try { - response = await http - .get(Uri.parse(addr), headers: {"Accept": "application/json"}); - } catch (e) { - if (!context.mounted) return null; - - const snackBar = SnackBar( - backgroundColor: Colors.amberAccent, - content: Text("mChess server is not responding. Try again or give up"), - ); - Future.delayed(const Duration(seconds: 2), () { - ScaffoldMessenger.of(context).clearSnackBars(); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - context.pop(); - }); - - return null; - } - - if (response.statusCode == 200) { - log(response.body); - return PlayerInfo.fromJson(jsonDecode(response.body)); - } - return null; - } -} diff --git a/lib/utils/chess_router.dart b/lib/utils/chess_router.dart index f483ebc..35892b0 100644 --- a/lib/utils/chess_router.dart +++ b/lib/utils/chess_router.dart @@ -2,7 +2,6 @@ import 'package:go_router/go_router.dart'; import 'package:mchess/pages/chess_game.dart'; import 'package:mchess/pages/lobby_selector.dart'; import 'package:mchess/pages/host_game.dart'; -import 'package:mchess/pages/prepare_random_game.dart'; class ChessAppRouter { static final ChessAppRouter _instance = ChessAppRouter._internal(); @@ -22,12 +21,6 @@ class ChessAppRouter { return const LobbySelector(); }, ), - GoRoute( - path: '/prepareRandom', - name: 'prepareRandom', - builder: (context, state) { - return const PrepareRandomGameWidget(); - }), GoRoute( path: '/host', name: 'host',