Merge pull request #199 from thecodingmachine/connectioninscene

Code cleanup and removing exception in favor of console error
This commit is contained in:
David Négrier 2020-06-22 18:46:44 +02:00 committed by GitHub
commit 52df539314
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 113 deletions

View File

@ -1,4 +1,3 @@
import {gameManager, GameManager} from "./Phaser/Game/GameManager";
import Axios from "axios"; import Axios from "axios";
import {API_URL} from "./Enum/EnvironmentVariable"; import {API_URL} from "./Enum/EnvironmentVariable";
import {MessageUI} from "./Logger/MessageUI"; import {MessageUI} from "./Logger/MessageUI";
@ -14,7 +13,6 @@ import {SignalData} from "simple-peer";
enum EventMessage{ enum EventMessage{
WEBRTC_SIGNAL = "webrtc-signal", WEBRTC_SIGNAL = "webrtc-signal",
WEBRTC_START = "webrtc-start", WEBRTC_START = "webrtc-start",
WEBRTC_JOIN_ROOM = "webrtc-join-room",
JOIN_ROOM = "join-room", // bi-directional JOIN_ROOM = "join-room", // bi-directional
USER_POSITION = "user-position", // bi-directional USER_POSITION = "user-position", // bi-directional
USER_MOVED = "user-moved", // From server to client USER_MOVED = "user-moved", // From server to client
@ -26,22 +24,6 @@ enum EventMessage{
SET_PLAYER_DETAILS = "set-player-details", // Send the name and character to the server (on connect), receive back the id. SET_PLAYER_DETAILS = "set-player-details", // Send the name and character to the server (on connect), receive back the id.
CONNECT_ERROR = "connect_error", CONNECT_ERROR = "connect_error",
RECONNECT = "reconnect",
RECONNECTING = "reconnecting",
RECONNECT_ERROR = "reconnect_error",
RECONNECT_FAILED = "reconnect_failed"
}
class Message {
userId: string;
name: string;
character: string;
constructor(userId : string, name: string, character: string) {
this.userId = userId;
this.name = name;
this.character = character;
}
} }
export interface PointInterface { export interface PointInterface {
@ -71,15 +53,6 @@ export interface MessageUserMovedInterface {
position: PointInterface; position: PointInterface;
} }
class MessageUserPosition extends Message implements MessageUserPositionInterface{
position: PointInterface;
constructor(userId : string, point : Point, name: string, character: string) {
super(userId, name, character);
this.position = point;
}
}
export interface MessageUserJoined { export interface MessageUserJoined {
userId: string; userId: string;
name: string; name: string;
@ -87,11 +60,6 @@ export interface MessageUserJoined {
position: PointInterface position: PointInterface
} }
export interface ListMessageUserPositionInterface {
roomId: string;
listUsersPosition: Array<MessageUserPosition>;
}
export interface PositionInterface { export interface PositionInterface {
x: number, x: number,
y: number y: number
@ -124,26 +92,14 @@ export interface StartMapInterface {
} }
export class Connection implements Connection { export class Connection implements Connection {
socket: Socket; private readonly socket: Socket;
token: string|null = null; private userId: string|null = null;
name: string|null = null; // TODO: drop "name" storage here
character: string|null = null;
userId: string|null = null;
GameManager: GameManager; private constructor(token: string) {
lastPositionShared: PointInterface|null = null;
lastRoom: string|null = null;
private constructor(GameManager: GameManager, name: string, character: string, token: string) {
this.GameManager = GameManager;
this.name = name;
this.character = character;
this.token = token;
this.socket = SocketIo(`${API_URL}`, { this.socket = SocketIo(`${API_URL}`, {
query: { query: {
token: this.token token: token
}, },
reconnection: false // Reconnection is handled by the application itself reconnection: false // Reconnection is handled by the application itself
}); });
@ -158,7 +114,7 @@ export class Connection implements Connection {
.then((res) => { .then((res) => {
return new Promise<Connection>((resolve, reject) => { return new Promise<Connection>((resolve, reject) => {
const connection = new Connection(gameManager, name, characterSelected, res.data.token); const connection = new Connection(res.data.token);
connection.onConnectError((error: object) => { connection.onConnectError((error: object) => {
console.log('An error occurred while connecting to socket server. Retrying'); console.log('An error occurred while connecting to socket server. Retrying');
@ -166,8 +122,8 @@ export class Connection implements Connection {
}); });
connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, { connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, {
name: connection.name, name: name,
character: connection.character character: characterSelected
} as SetPlayerDetailsMessage, (id: string) => { } as SetPlayerDetailsMessage, (id: string) => {
connection.userId = id; connection.userId = id;
}); });
@ -183,38 +139,28 @@ export class Connection implements Connection {
.catch((error) => reject(error)); .catch((error) => reject(error));
}, 4000 + Math.floor(Math.random() * 2000) ); }, 4000 + Math.floor(Math.random() * 2000) );
}); });
//console.error(err);
//throw err;
}); });
} }
public closeConnection(): void { public closeConnection(): void {
this.socket?.close(); this.socket?.close();
this.lastPositionShared = null;
this.lastRoom = null;
} }
joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): Promise<MessageUserPositionInterface[]> { public joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): Promise<MessageUserPositionInterface[]> {
const point = new Point(startX, startY, direction, moving);
this.lastPositionShared = point;
const promise = new Promise<MessageUserPositionInterface[]>((resolve, reject) => { const promise = new Promise<MessageUserPositionInterface[]>((resolve, reject) => {
this.socket.emit(EventMessage.JOIN_ROOM, { roomId, position: {x: startX, y: startY, direction, moving }}, (userPositions: MessageUserPositionInterface[]) => { this.socket.emit(EventMessage.JOIN_ROOM, { roomId, position: {x: startX, y: startY, direction, moving }}, (userPositions: MessageUserPositionInterface[]) => {
//this.GameManager.initUsersPosition(userPositions);
resolve(userPositions); resolve(userPositions);
}); });
}) })
this.lastRoom = roomId;
return promise; return promise;
} }
sharePosition(x : number, y : number, direction : string, moving: boolean) : void{ public sharePosition(x : number, y : number, direction : string, moving: boolean) : void{
if(!this.socket){ if(!this.socket){
return; return;
} }
const point = new Point(x, y, direction, moving); const point = new Point(x, y, direction, moving);
this.lastPositionShared = point;
this.socket.emit(EventMessage.USER_POSITION, point); this.socket.emit(EventMessage.USER_POSITION, point);
} }
@ -242,7 +188,7 @@ export class Connection implements Connection {
this.socket.on(EventMessage.CONNECT_ERROR, callback) this.socket.on(EventMessage.CONNECT_ERROR, callback)
} }
sendWebrtcSignal(signal: unknown, roomId: string, userId? : string|null, receiverId? : string) { public sendWebrtcSignal(signal: unknown, roomId: string, userId? : string|null, receiverId? : string) {
return this.socket.emit(EventMessage.WEBRTC_SIGNAL, { return this.socket.emit(EventMessage.WEBRTC_SIGNAL, {
userId: userId ? userId : this.userId, userId: userId ? userId : this.userId,
receiverId: receiverId ? receiverId : this.userId, receiverId: receiverId ? receiverId : this.userId,
@ -251,19 +197,15 @@ export class Connection implements Connection {
}); });
} }
receiveWebrtcStart(callback: (message: WebRtcStartMessageInterface) => void) { public receiveWebrtcStart(callback: (message: WebRtcStartMessageInterface) => void) {
this.socket.on(EventMessage.WEBRTC_START, callback); this.socket.on(EventMessage.WEBRTC_START, callback);
} }
receiveWebrtcSignal(callback: (message: WebRtcSignalMessageInterface) => void) { public receiveWebrtcSignal(callback: (message: WebRtcSignalMessageInterface) => void) {
return this.socket.on(EventMessage.WEBRTC_SIGNAL, callback); return this.socket.on(EventMessage.WEBRTC_SIGNAL, callback);
} }
public onServerDisconnected(callback: (reason: string) => void): void { public onServerDisconnected(callback: (reason: string) => void): void {
/*this.socket.on(EventMessage.CONNECT_ERROR, (error: object) => {
callback(error);
});*/
this.socket.on('disconnect', (reason: string) => { this.socket.on('disconnect', (reason: string) => {
if (reason === 'io client disconnect') { if (reason === 'io client disconnect') {
// The client asks for disconnect, let's not trigger any event. // The client asks for disconnect, let's not trigger any event.
@ -272,30 +214,10 @@ export class Connection implements Connection {
callback(reason); callback(reason);
}); });
/*this.socket.on(EventMessage.CONNECT_ERROR, (error: object) => {
this.GameManager.switchToDisconnectedScene();
});*/
/*this.socket.on(EventMessage.RECONNECTING, () => {
console.log('Trying to reconnect');
});
this.socket.on(EventMessage.RECONNECT_ERROR, () => {
console.log('Error while trying to reconnect.');
});
this.socket.on(EventMessage.RECONNECT_FAILED, () => {
console.error('Reconnection failed. Giving up.');
});
this.socket.on(EventMessage.RECONNECT, () => {
console.log('Reconnect event triggered');
this.connectSocketServer();
if (this.lastPositionShared === null) {
throw new Error('No last position shared found while reconnecting');
} }
this.GameManager.reconnectToGameScene(this.lastPositionShared);
});*/ public getUserId(): string|null {
return this.userId;
} }
disconnectMessage(callback: (message: WebRtcDisconnectMessageInterface) => void): void { disconnectMessage(callback: (message: WebRtcDisconnectMessageInterface) => void): void {

View File

@ -1,19 +1,7 @@
import {GameScene} from "./GameScene"; import {GameScene} from "./GameScene";
import { import {
Connection, StartMapInterface
GroupCreatedUpdatedMessageInterface,
ListMessageUserPositionInterface,
MessageUserJoined,
MessageUserMovedInterface,
MessageUserPositionInterface,
Point,
PointInterface, StartMapInterface
} from "../../Connection"; } from "../../Connection";
import {SimplePeer} from "../../WebRtc/SimplePeer";
import {AddPlayerInterface} from "./AddPlayerInterface";
import {ReconnectingScene, ReconnectingSceneName} from "../Reconnecting/ReconnectingScene";
import ScenePlugin = Phaser.Scenes.ScenePlugin;
import {Scene} from "phaser";
import Axios from "axios"; import Axios from "axios";
import {API_URL} from "../../Enum/EnvironmentVariable"; import {API_URL} from "../../Enum/EnvironmentVariable";
@ -24,11 +12,6 @@ export interface HasMovedEvent {
y: number; y: number;
} }
export interface MapObject {
key: string,
url: string
}
export class GameManager { export class GameManager {
private playerName: string; private playerName: string;
private characterUserSelected: string; private characterUserSelected: string;

View File

@ -647,7 +647,7 @@ export class GameScene extends Phaser.Scene {
* Put all the players on the map on map load. * Put all the players on the map on map load.
*/ */
private doInitUsersPosition(usersPosition: MessageUserPositionInterface[]): void { private doInitUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
const currentPlayerId = this.connection.userId; const currentPlayerId = this.connection.getUserId();
// clean map // clean map
this.MapPlayersByKey.forEach((player: RemotePlayer) => { this.MapPlayersByKey.forEach((player: RemotePlayer) => {
@ -740,7 +740,9 @@ export class GameScene extends Phaser.Scene {
private doUpdatePlayerPosition(message: MessageUserMovedInterface): void { private doUpdatePlayerPosition(message: MessageUserMovedInterface): void {
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId); const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
if (player === undefined) { if (player === undefined) {
throw new Error('Cannot find player with ID "' + message.userId +'"'); //throw new Error('Cannot find player with ID "' + message.userId +'"');
console.error('Cannot update position of player with ID "' + message.userId +'": player not found');
return;
} }
// We do not update the player position directly (because it is sent only every 200ms). // We do not update the player position directly (because it is sent only every 200ms).