Marco
8f4cd2266f
This is another step to allow reconnecting after connection loss or browser closing. When the game is left with the X button on the bottom right, we will close the websocket connection, to let the server know, that we are gone. The server still has issues that prevent this from working flawlessly. Remove unused import
95 lines
2.4 KiB
Dart
95 lines
2.4 KiB
Dart
import 'package:mchess/api/move.dart';
|
|
|
|
enum MessageType {
|
|
boardState,
|
|
move,
|
|
invalidMove,
|
|
colorDetermined;
|
|
|
|
String toJson() => name;
|
|
static MessageType fromJson(String json) => values.byName(json);
|
|
}
|
|
|
|
enum ApiColor {
|
|
black,
|
|
white;
|
|
|
|
String toJson() => name;
|
|
static ApiColor fromJson(String json) => values.byName(json);
|
|
}
|
|
|
|
class ApiWebsocketMessage {
|
|
final MessageType type;
|
|
final ApiMove? move;
|
|
final ApiColor? turnColor;
|
|
final ApiColor? playerColor;
|
|
final String? reason;
|
|
final String? position;
|
|
final ApiCoordinate? squareInCheck;
|
|
|
|
ApiWebsocketMessage({
|
|
required this.type,
|
|
required this.move,
|
|
required this.turnColor,
|
|
required this.playerColor,
|
|
required this.reason,
|
|
required this.position,
|
|
required this.squareInCheck,
|
|
});
|
|
|
|
factory ApiWebsocketMessage.fromJson(Map<String, dynamic> json) {
|
|
final type = MessageType.fromJson(json['messageType']);
|
|
ApiWebsocketMessage ret;
|
|
switch (type) {
|
|
case MessageType.boardState:
|
|
ret = ApiWebsocketMessage(
|
|
type: type,
|
|
move: null,
|
|
turnColor: ApiColor.fromJson(json['turnColor']),
|
|
reason: null,
|
|
position: json['position'],
|
|
squareInCheck: null,
|
|
playerColor: ApiColor.fromJson(json['playerColor']),
|
|
);
|
|
case MessageType.colorDetermined:
|
|
ret = ApiWebsocketMessage(
|
|
type: type,
|
|
move: null,
|
|
turnColor: null,
|
|
reason: null,
|
|
position: null,
|
|
squareInCheck: null,
|
|
playerColor: ApiColor.fromJson(json['playerColor']),
|
|
);
|
|
break;
|
|
case MessageType.move:
|
|
ret = ApiWebsocketMessage(
|
|
type: type,
|
|
move: ApiMove.fromJson(json['move']),
|
|
turnColor: null,
|
|
reason: null,
|
|
position: json['position'],
|
|
squareInCheck: json['squareInCheck'],
|
|
playerColor: null);
|
|
break;
|
|
case MessageType.invalidMove:
|
|
ret = ApiWebsocketMessage(
|
|
type: type,
|
|
move: ApiMove.fromJson(json['move']),
|
|
turnColor: null,
|
|
reason: json['reason'],
|
|
position: null,
|
|
squareInCheck: json['squareInCheck'],
|
|
playerColor: null,
|
|
);
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
Map<String, dynamic> toJson() => {
|
|
'messageType': type,
|
|
'move': move,
|
|
'color': turnColor,
|
|
};
|
|
}
|