Merge pull request #201 from thecodingmachine/develop
Putting refactoring of connection in production
This commit is contained in:
commit
6e46f37146
@ -7,7 +7,8 @@
|
|||||||
},
|
},
|
||||||
"extends": [
|
"extends": [
|
||||||
"eslint:recommended",
|
"eslint:recommended",
|
||||||
"plugin:@typescript-eslint/eslint-recommended"
|
"plugin:@typescript-eslint/eslint-recommended",
|
||||||
|
"plugin:@typescript-eslint/recommended-requiring-type-checking"
|
||||||
],
|
],
|
||||||
"globals": {
|
"globals": {
|
||||||
"Atomics": "readonly",
|
"Atomics": "readonly",
|
||||||
@ -16,12 +17,14 @@
|
|||||||
"parser": "@typescript-eslint/parser",
|
"parser": "@typescript-eslint/parser",
|
||||||
"parserOptions": {
|
"parserOptions": {
|
||||||
"ecmaVersion": 2018,
|
"ecmaVersion": 2018,
|
||||||
"sourceType": "module"
|
"sourceType": "module",
|
||||||
|
"project": "./tsconfig.json"
|
||||||
},
|
},
|
||||||
"plugins": [
|
"plugins": [
|
||||||
"@typescript-eslint"
|
"@typescript-eslint"
|
||||||
],
|
],
|
||||||
"rules": {
|
"rules": {
|
||||||
"no-unused-vars": "off"
|
"no-unused-vars": "off",
|
||||||
|
"@typescript-eslint/no-explicit-any": "error"
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -22,6 +22,7 @@
|
|||||||
"@types/simple-peer": "^9.6.0",
|
"@types/simple-peer": "^9.6.0",
|
||||||
"@types/socket.io-client": "^1.4.32",
|
"@types/socket.io-client": "^1.4.32",
|
||||||
"phaser": "^3.22.0",
|
"phaser": "^3.22.0",
|
||||||
|
"queue-typescript": "^1.0.1",
|
||||||
"simple-peer": "^9.6.2",
|
"simple-peer": "^9.6.2",
|
||||||
"socket.io-client": "^2.3.0"
|
"socket.io-client": "^2.3.0"
|
||||||
},
|
},
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import {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";
|
||||||
@ -8,12 +7,12 @@ const SocketIo = require('socket.io-client');
|
|||||||
import Socket = SocketIOClient.Socket;
|
import Socket = SocketIOClient.Socket;
|
||||||
import {PlayerAnimationNames} from "./Phaser/Player/Animation";
|
import {PlayerAnimationNames} from "./Phaser/Player/Animation";
|
||||||
import {UserSimplePeer} from "./WebRtc/SimplePeer";
|
import {UserSimplePeer} from "./WebRtc/SimplePeer";
|
||||||
|
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
|
||||||
@ -25,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 {
|
||||||
@ -70,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;
|
||||||
@ -86,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
|
||||||
@ -110,182 +79,117 @@ export interface WebRtcDisconnectMessageInterface {
|
|||||||
userId: string
|
userId: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ConnectionInterface {
|
export interface WebRtcSignalMessageInterface {
|
||||||
socket: Socket|null;
|
userId: string,
|
||||||
token: string|null;
|
receiverId: string,
|
||||||
name: string|null;
|
roomId: string,
|
||||||
userId: string|null;
|
signal: SignalData
|
||||||
|
|
||||||
createConnection(name: string, characterSelected: string): Promise<any>;
|
|
||||||
|
|
||||||
loadStartMap(): Promise<any>;
|
|
||||||
|
|
||||||
joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): void;
|
|
||||||
|
|
||||||
sharePosition(x: number, y: number, direction: string, moving: boolean): void;
|
|
||||||
|
|
||||||
/*webrtc*/
|
|
||||||
sendWebrtcSignal(signal: any, roomId: string, userId?: string|null, receiverId?: string): void;
|
|
||||||
|
|
||||||
receiveWebrtcSignal(callBack: Function): void;
|
|
||||||
|
|
||||||
receiveWebrtcStart(callBack: (message: WebRtcStartMessageInterface) => void): void;
|
|
||||||
|
|
||||||
disconnectMessage(callBack: (message: WebRtcDisconnectMessageInterface) => void): void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Connection implements ConnectionInterface {
|
export interface StartMapInterface {
|
||||||
socket: Socket|null = null;
|
mapUrlStart: string,
|
||||||
token: string|null = null;
|
startInstance: string
|
||||||
name: string|null = null; // TODO: drop "name" storage here
|
|
||||||
character: string|null = null;
|
|
||||||
userId: string|null = null;
|
|
||||||
|
|
||||||
GameManager: GameManager;
|
|
||||||
|
|
||||||
lastPositionShared: PointInterface|null = null;
|
|
||||||
lastRoom: string|null = null;
|
|
||||||
|
|
||||||
constructor(GameManager: GameManager) {
|
|
||||||
this.GameManager = GameManager;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createConnection(name: string, characterSelected: string): Promise<ConnectionInterface> {
|
export class Connection implements Connection {
|
||||||
this.name = name;
|
private readonly socket: Socket;
|
||||||
this.character = characterSelected;
|
private userId: string|null = null;
|
||||||
return Axios.post(`${API_URL}/login`, {name: name})
|
|
||||||
.then((res) => {
|
private constructor(token: string) {
|
||||||
this.token = res.data.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
|
||||||
});
|
});
|
||||||
|
|
||||||
//listen event
|
this.socket.on(EventMessage.MESSAGE_ERROR, (message: string) => {
|
||||||
this.disconnectServer();
|
console.error(EventMessage.MESSAGE_ERROR, message);
|
||||||
this.errorMessage();
|
})
|
||||||
this.groupUpdatedOrCreated();
|
}
|
||||||
this.groupDeleted();
|
|
||||||
this.onUserJoins();
|
|
||||||
this.onUserMoved();
|
|
||||||
this.onUserLeft();
|
|
||||||
|
|
||||||
return this.connectSocketServer();
|
public static createConnection(name: string, characterSelected: string): Promise<Connection> {
|
||||||
|
return Axios.post(`${API_URL}/login`, {name: name})
|
||||||
|
.then((res) => {
|
||||||
|
|
||||||
|
return new Promise<Connection>((resolve, reject) => {
|
||||||
|
const connection = new Connection(res.data.token);
|
||||||
|
|
||||||
|
connection.onConnectError((error: object) => {
|
||||||
|
console.log('An error occurred while connecting to socket server. Retrying');
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, {
|
||||||
|
name: name,
|
||||||
|
character: characterSelected
|
||||||
|
} as SetPlayerDetailsMessage, (id: string) => {
|
||||||
|
connection.userId = id;
|
||||||
|
});
|
||||||
|
|
||||||
|
resolve(connection);
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error(err);
|
// Let's retry in 4-6 seconds
|
||||||
throw err;
|
return new Promise<Connection>((resolve, reject) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
Connection.createConnection(name, characterSelected).then((connection) => resolve(connection))
|
||||||
|
.catch((error) => reject(error));
|
||||||
|
}, 4000 + Math.floor(Math.random() * 2000) );
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private getSocket(): Socket {
|
public closeConnection(): void {
|
||||||
if (this.socket === null) {
|
this.socket?.close();
|
||||||
throw new Error('Socket not initialized while using Connection')
|
|
||||||
}
|
|
||||||
return this.socket;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
public joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): Promise<MessageUserPositionInterface[]> {
|
||||||
* @param character
|
const promise = new Promise<MessageUserPositionInterface[]>((resolve, reject) => {
|
||||||
*/
|
this.socket.emit(EventMessage.JOIN_ROOM, { roomId, position: {x: startX, y: startY, direction, moving }}, (userPositions: MessageUserPositionInterface[]) => {
|
||||||
connectSocketServer(): Promise<ConnectionInterface>{
|
resolve(userPositions);
|
||||||
return new Promise<ConnectionInterface>((resolve, reject) => {
|
|
||||||
this.getSocket().emit(EventMessage.SET_PLAYER_DETAILS, {
|
|
||||||
name: this.name,
|
|
||||||
character: this.character
|
|
||||||
} as SetPlayerDetailsMessage, (id: string) => {
|
|
||||||
this.userId = id;
|
|
||||||
});
|
|
||||||
|
|
||||||
//if try to reconnect with last position
|
|
||||||
/*if(this.lastRoom) {
|
|
||||||
//join the room
|
|
||||||
this.joinARoom(this.lastRoom,
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.x : 0,
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.y : 0,
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.direction : PlayerAnimationNames.WalkDown,
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.moving : false);
|
|
||||||
}*/
|
|
||||||
|
|
||||||
/*if(this.lastPositionShared) {
|
|
||||||
|
|
||||||
//share your first position
|
|
||||||
this.sharePosition(
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.x : 0,
|
|
||||||
this.lastPositionShared ? this.lastPositionShared.y : 0,
|
|
||||||
this.lastPositionShared.direction,
|
|
||||||
this.lastPositionShared.moving
|
|
||||||
);
|
|
||||||
}*/
|
|
||||||
|
|
||||||
resolve(this);
|
|
||||||
});
|
});
|
||||||
|
})
|
||||||
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO add middleware with access token to secure api
|
public sharePosition(x : number, y : number, direction : string, moving: boolean) : void{
|
||||||
loadStartMap() : Promise<any> {
|
|
||||||
return Axios.get(`${API_URL}/start-map`)
|
|
||||||
.then((res) => {
|
|
||||||
return res.data;
|
|
||||||
}).catch((err) => {
|
|
||||||
console.error(err);
|
|
||||||
throw err;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): void {
|
|
||||||
let point = new Point(startX, startY, direction, moving);
|
|
||||||
this.lastPositionShared = point;
|
|
||||||
this.getSocket().emit(EventMessage.JOIN_ROOM, { roomId, position: {x: startX, y: startY, direction, moving }}, (userPositions: MessageUserPositionInterface[]) => {
|
|
||||||
this.GameManager.initUsersPosition(userPositions);
|
|
||||||
});
|
|
||||||
this.lastRoom = roomId;
|
|
||||||
}
|
|
||||||
|
|
||||||
sharePosition(x : number, y : number, direction : string, moving: boolean) : void{
|
|
||||||
if(!this.socket){
|
if(!this.socket){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let 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.getSocket().emit(EventMessage.USER_POSITION, point);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private onUserJoins(): void {
|
public onUserJoins(callback: (message: MessageUserJoined) => void): void {
|
||||||
this.getSocket().on(EventMessage.JOIN_ROOM, (message: MessageUserJoined) => {
|
this.socket.on(EventMessage.JOIN_ROOM, callback);
|
||||||
this.GameManager.onUserJoins(message);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private onUserMoved(): void {
|
public onUserMoved(callback: (message: MessageUserMovedInterface) => void): void {
|
||||||
this.getSocket().on(EventMessage.USER_MOVED, (message: MessageUserMovedInterface) => {
|
this.socket.on(EventMessage.USER_MOVED, callback);
|
||||||
this.GameManager.onUserMoved(message);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private onUserLeft(): void {
|
public onUserLeft(callback: (userId: string) => void): void {
|
||||||
this.getSocket().on(EventMessage.USER_LEFT, (userId: string) => {
|
this.socket.on(EventMessage.USER_LEFT, callback);
|
||||||
this.GameManager.onUserLeft(userId);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private groupUpdatedOrCreated(): void {
|
public onGroupUpdatedOrCreated(callback: (groupCreateUpdateMessage: GroupCreatedUpdatedMessageInterface) => void): void {
|
||||||
this.getSocket().on(EventMessage.GROUP_CREATE_UPDATE, (groupCreateUpdateMessage: GroupCreatedUpdatedMessageInterface) => {
|
this.socket.on(EventMessage.GROUP_CREATE_UPDATE, callback);
|
||||||
//console.log('Group ', groupCreateUpdateMessage.groupId, " position :", groupCreateUpdateMessage.position.x, groupCreateUpdateMessage.position.y)
|
|
||||||
this.GameManager.shareGroupPosition(groupCreateUpdateMessage);
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private groupDeleted(): void {
|
public onGroupDeleted(callback: (groupId: string) => void): void {
|
||||||
this.getSocket().on(EventMessage.GROUP_DELETE, (groupId: string) => {
|
this.socket.on(EventMessage.GROUP_DELETE, callback)
|
||||||
this.GameManager.deleteGroup(groupId);
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sendWebrtcSignal(signal: any, roomId: string, userId? : string|null, receiverId? : string) {
|
public onConnectError(callback: (error: object) => void): void {
|
||||||
return this.getSocket().emit(EventMessage.WEBRTC_SIGNAL, {
|
this.socket.on(EventMessage.CONNECT_ERROR, callback)
|
||||||
|
}
|
||||||
|
|
||||||
|
public sendWebrtcSignal(signal: unknown, roomId: string, userId? : string|null, receiverId? : string) {
|
||||||
|
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,
|
||||||
roomId: roomId,
|
roomId: roomId,
|
||||||
@ -293,48 +197,30 @@ export class Connection implements ConnectionInterface {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
receiveWebrtcStart(callback: (message: WebRtcStartMessageInterface) => void) {
|
public receiveWebrtcStart(callback: (message: WebRtcStartMessageInterface) => void) {
|
||||||
this.getSocket().on(EventMessage.WEBRTC_START, callback);
|
this.socket.on(EventMessage.WEBRTC_START, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
receiveWebrtcSignal(callback: Function) {
|
public receiveWebrtcSignal(callback: (message: WebRtcSignalMessageInterface) => void) {
|
||||||
return this.getSocket().on(EventMessage.WEBRTC_SIGNAL, callback);
|
return this.socket.on(EventMessage.WEBRTC_SIGNAL, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
private errorMessage(): void {
|
public onServerDisconnected(callback: (reason: string) => void): void {
|
||||||
this.getSocket().on(EventMessage.MESSAGE_ERROR, (message: string) => {
|
this.socket.on('disconnect', (reason: string) => {
|
||||||
console.error(EventMessage.MESSAGE_ERROR, message);
|
if (reason === 'io client disconnect') {
|
||||||
})
|
// The client asks for disconnect, let's not trigger any event.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
callback(reason);
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private disconnectServer(): void {
|
public getUserId(): string|null {
|
||||||
this.getSocket().on(EventMessage.CONNECT_ERROR, () => {
|
return this.userId;
|
||||||
this.GameManager.switchToDisconnectedScene();
|
|
||||||
});
|
|
||||||
|
|
||||||
this.getSocket().on(EventMessage.RECONNECTING, () => {
|
|
||||||
console.log('Trying to reconnect');
|
|
||||||
});
|
|
||||||
|
|
||||||
this.getSocket().on(EventMessage.RECONNECT_ERROR, () => {
|
|
||||||
console.log('Error while trying to reconnect.');
|
|
||||||
});
|
|
||||||
|
|
||||||
this.getSocket().on(EventMessage.RECONNECT_FAILED, () => {
|
|
||||||
console.error('Reconnection failed. Giving up.');
|
|
||||||
});
|
|
||||||
|
|
||||||
this.getSocket().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);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
disconnectMessage(callback: (message: WebRtcDisconnectMessageInterface) => void): void {
|
disconnectMessage(callback: (message: WebRtcDisconnectMessageInterface) => void): void {
|
||||||
this.getSocket().on(EventMessage.WEBRTC_DISCONNECT, callback);
|
this.socket.on(EventMessage.WEBRTC_DISCONNECT, callback);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,8 @@
|
|||||||
declare let window:any;
|
declare let window:WindowWithCypressAsserter;
|
||||||
|
|
||||||
|
interface WindowWithCypressAsserter extends Window {
|
||||||
|
cypressAsserter: CypressAsserter;
|
||||||
|
}
|
||||||
|
|
||||||
//this class is used to communicate with cypress, our e2e testing client
|
//this class is used to communicate with cypress, our e2e testing client
|
||||||
//Since cypress cannot manipulate canvas, we notified it with console logs
|
//Since cypress cannot manipulate canvas, we notified it with console logs
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
const DEBUG_MODE: boolean = process.env.DEBUG_MODE as any === true;
|
const DEBUG_MODE: boolean = process.env.DEBUG_MODE == "true";
|
||||||
const API_URL = process.env.API_URL || "http://api.workadventure.localhost";
|
const API_URL = process.env.API_URL || "http://api.workadventure.localhost";
|
||||||
const RESOLUTION = 3;
|
const RESOLUTION = 3;
|
||||||
const ZOOM_LEVEL = 1/*3/4*/;
|
const ZOOM_LEVEL = 1/*3/4*/;
|
||||||
|
@ -2,7 +2,7 @@ export class MessageUI {
|
|||||||
|
|
||||||
static warningMessage(text: string){
|
static warningMessage(text: string){
|
||||||
this.removeMessage();
|
this.removeMessage();
|
||||||
let body = document.getElementById("body");
|
const body = document.getElementById("body");
|
||||||
body?.insertAdjacentHTML('afterbegin', `
|
body?.insertAdjacentHTML('afterbegin', `
|
||||||
<div id="message-reconnect" class="message-info warning">
|
<div id="message-reconnect" class="message-info warning">
|
||||||
${text}
|
${text}
|
||||||
@ -12,13 +12,13 @@ export class MessageUI {
|
|||||||
|
|
||||||
static removeMessage(id : string|null = null) {
|
static removeMessage(id : string|null = null) {
|
||||||
if(!id){
|
if(!id){
|
||||||
let messages = document.getElementsByClassName("message-info");
|
const messages = document.getElementsByClassName("message-info");
|
||||||
for (let i = 0; i < messages.length; i++){
|
for (let i = 0; i < messages.length; i++){
|
||||||
messages.item(i)?.remove();
|
messages.item(i)?.remove();
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let previousElement = document.getElementById(id);
|
const previousElement = document.getElementById(id);
|
||||||
if (!previousElement) {
|
if (!previousElement) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -10,9 +10,9 @@ export class TextInput extends Phaser.GameObjects.BitmapText {
|
|||||||
this.underLine = this.scene.add.text(x, y+1, '_______', { fontFamily: 'Arial', fontSize: "32px", color: '#ffffff'})
|
this.underLine = this.scene.add.text(x, y+1, '_______', { fontFamily: 'Arial', fontSize: "32px", color: '#ffffff'})
|
||||||
|
|
||||||
|
|
||||||
let keySpace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
|
const keySpace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
|
||||||
let keyBackspace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.BACKSPACE);
|
const keyBackspace = this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.BACKSPACE);
|
||||||
this.scene.input.keyboard.on('keydown', (event: any) => {
|
this.scene.input.keyboard.on('keydown', (event: KeyboardEvent) => {
|
||||||
if (event.keyCode === 8 && this.text.length > 0) {
|
if (event.keyCode === 8 && this.text.length > 0) {
|
||||||
this.deleteLetter();
|
this.deleteLetter();
|
||||||
} else if ((event.keyCode === 32 || (event.keyCode >= 48 && event.keyCode <= 90)) && this.text.length < maxLength) {
|
} else if ((event.keyCode === 32 || (event.keyCode >= 48 && event.keyCode <= 90)) && this.text.length < maxLength) {
|
||||||
|
@ -2,7 +2,12 @@ import {PlayerAnimationNames} from "../Player/Animation";
|
|||||||
import {SpeechBubble} from "./SpeechBubble";
|
import {SpeechBubble} from "./SpeechBubble";
|
||||||
import BitmapText = Phaser.GameObjects.BitmapText;
|
import BitmapText = Phaser.GameObjects.BitmapText;
|
||||||
|
|
||||||
export const PLAYER_RESOURCES: Array<any> = [
|
export interface PlayerResourceDescriptionInterface {
|
||||||
|
name: string,
|
||||||
|
img: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PLAYER_RESOURCES: Array<PlayerResourceDescriptionInterface> = [
|
||||||
{name: "male1", img: "resources/characters/pipoya/Male 01-1.png" /*, x: 32, y: 32*/},
|
{name: "male1", img: "resources/characters/pipoya/Male 01-1.png" /*, x: 32, y: 32*/},
|
||||||
{name: "male2", img: "resources/characters/pipoya/Male 02-2.png"/*, x: 64, y: 32*/},
|
{name: "male2", img: "resources/characters/pipoya/Male 02-2.png"/*, x: 64, y: 32*/},
|
||||||
{name: "male3", img: "resources/characters/pipoya/Male 03-4.png"/*, x: 96, y: 32*/},
|
{name: "male3", img: "resources/characters/pipoya/Male 03-4.png"/*, x: 96, y: 32*/},
|
||||||
|
@ -13,10 +13,10 @@ export class SpeechBubble {
|
|||||||
*/
|
*/
|
||||||
constructor(scene: Scene, player: Character, text: string = "") {
|
constructor(scene: Scene, player: Character, text: string = "") {
|
||||||
|
|
||||||
let bubbleHeight = 50;
|
const bubbleHeight = 50;
|
||||||
let bubblePadding = 10;
|
const bubblePadding = 10;
|
||||||
let bubbleWidth = bubblePadding * 2 + text.length * 10;
|
const bubbleWidth = bubblePadding * 2 + text.length * 10;
|
||||||
let arrowHeight = bubbleHeight / 4;
|
const arrowHeight = bubbleHeight / 4;
|
||||||
|
|
||||||
this.bubble = scene.add.graphics({ x: player.x + 16, y: player.y - 80 });
|
this.bubble = scene.add.graphics({ x: player.x + 16, y: player.y - 80 });
|
||||||
|
|
||||||
@ -35,12 +35,12 @@ export class SpeechBubble {
|
|||||||
this.bubble.fillRoundedRect(0, 0, bubbleWidth, bubbleHeight, 16);
|
this.bubble.fillRoundedRect(0, 0, bubbleWidth, bubbleHeight, 16);
|
||||||
|
|
||||||
// Calculate arrow coordinates
|
// Calculate arrow coordinates
|
||||||
let point1X = Math.floor(bubbleWidth / 7);
|
const point1X = Math.floor(bubbleWidth / 7);
|
||||||
let point1Y = bubbleHeight;
|
const point1Y = bubbleHeight;
|
||||||
let point2X = Math.floor((bubbleWidth / 7) * 2);
|
const point2X = Math.floor((bubbleWidth / 7) * 2);
|
||||||
let point2Y = bubbleHeight;
|
const point2Y = bubbleHeight;
|
||||||
let point3X = Math.floor(bubbleWidth / 7);
|
const point3X = Math.floor(bubbleWidth / 7);
|
||||||
let point3Y = Math.floor(bubbleHeight + arrowHeight);
|
const point3Y = Math.floor(bubbleHeight + arrowHeight);
|
||||||
|
|
||||||
// bubble arrow shadow
|
// bubble arrow shadow
|
||||||
this.bubble.lineStyle(4, 0x222222, 0.5);
|
this.bubble.lineStyle(4, 0x222222, 0.5);
|
||||||
@ -54,7 +54,7 @@ export class SpeechBubble {
|
|||||||
|
|
||||||
this.content = scene.add.text(0, 0, text, { fontFamily: 'Arial', fontSize: 20, color: '#000000', align: 'center', wordWrap: { width: bubbleWidth - (bubblePadding * 2) } });
|
this.content = scene.add.text(0, 0, text, { fontFamily: 'Arial', fontSize: 20, color: '#000000', align: 'center', wordWrap: { width: bubbleWidth - (bubblePadding * 2) } });
|
||||||
|
|
||||||
let bounds = this.content.getBounds();
|
const bounds = this.content.getBounds();
|
||||||
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
|
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,10 +68,10 @@ export class SpeechBubble {
|
|||||||
this.bubble.setPosition((x + 16), (y - 80));
|
this.bubble.setPosition((x + 16), (y - 80));
|
||||||
}
|
}
|
||||||
if (this.content) {
|
if (this.content) {
|
||||||
let bubbleHeight = 50;
|
const bubbleHeight = 50;
|
||||||
let bubblePadding = 10;
|
const bubblePadding = 10;
|
||||||
let bubbleWidth = bubblePadding * 2 + this.content.text.length * 10;
|
const bubbleWidth = bubblePadding * 2 + this.content.text.length * 10;
|
||||||
let bounds = this.content.getBounds();
|
const bounds = this.content.getBounds();
|
||||||
//this.content.setPosition(x, y);
|
//this.content.setPosition(x, y);
|
||||||
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
|
this.content.setPosition(this.bubble.x + (bubbleWidth / 2) - (bounds.width / 2), this.bubble.y + (bubbleHeight / 2) - (bounds.height / 2));
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,9 @@
|
|||||||
import {GameScene} from "./GameScene";
|
import {GameScene} from "./GameScene";
|
||||||
import {
|
import {
|
||||||
Connection,
|
StartMapInterface
|
||||||
GroupCreatedUpdatedMessageInterface,
|
|
||||||
ListMessageUserPositionInterface,
|
|
||||||
MessageUserJoined,
|
|
||||||
MessageUserMovedInterface,
|
|
||||||
MessageUserPositionInterface,
|
|
||||||
Point,
|
|
||||||
PointInterface
|
|
||||||
} from "../../Connection";
|
} from "../../Connection";
|
||||||
import {SimplePeer} from "../../WebRtc/SimplePeer";
|
import Axios from "axios";
|
||||||
import {AddPlayerInterface} from "./AddPlayerInterface";
|
import {API_URL} from "../../Enum/EnvironmentVariable";
|
||||||
import {ReconnectingScene, ReconnectingSceneName} from "../Reconnecting/ReconnectingScene";
|
|
||||||
import ScenePlugin = Phaser.Scenes.ScenePlugin;
|
|
||||||
import {Scene} from "phaser";
|
|
||||||
|
|
||||||
/*export enum StatusGameManagerEnum {
|
|
||||||
IN_PROGRESS = 1,
|
|
||||||
CURRENT_USER_CREATED = 2
|
|
||||||
}*/
|
|
||||||
|
|
||||||
export interface HasMovedEvent {
|
export interface HasMovedEvent {
|
||||||
direction: string;
|
direction: string;
|
||||||
@ -27,200 +12,43 @@ export interface HasMovedEvent {
|
|||||||
y: number;
|
y: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MapObject {
|
|
||||||
key: string,
|
|
||||||
url: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GameManager {
|
export class GameManager {
|
||||||
//status: number;
|
|
||||||
private ConnectionInstance: Connection;
|
|
||||||
private currentGameScene: GameScene|null = null;
|
|
||||||
private playerName: string;
|
private playerName: string;
|
||||||
SimplePeer : SimplePeer;
|
|
||||||
private characterUserSelected: string;
|
private characterUserSelected: string;
|
||||||
|
|
||||||
constructor() {
|
public storePlayerDetails(name: string, characterUserSelected : string): void {
|
||||||
//this.status = StatusGameManagerEnum.IN_PROGRESS;
|
|
||||||
}
|
|
||||||
|
|
||||||
connect(name: string, characterUserSelected : string) {
|
|
||||||
this.playerName = name;
|
this.playerName = name;
|
||||||
this.characterUserSelected = characterUserSelected;
|
this.characterUserSelected = characterUserSelected;
|
||||||
this.ConnectionInstance = new Connection(this);
|
}
|
||||||
return this.ConnectionInstance.createConnection(name, characterUserSelected).then((data : any) => {
|
|
||||||
this.SimplePeer = new SimplePeer(this.ConnectionInstance);
|
loadStartMap() : Promise<StartMapInterface> {
|
||||||
return data;
|
return Axios.get(`${API_URL}/start-map`)
|
||||||
|
.then((res) => {
|
||||||
|
return res.data;
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
|
console.error(err);
|
||||||
throw err;
|
throw err;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadStartMap(){
|
|
||||||
return this.ConnectionInstance.loadStartMap().then((data) => {
|
|
||||||
return data;
|
|
||||||
}).catch((err) => {
|
|
||||||
throw err;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
setCurrentGameScene(gameScene: GameScene) {
|
|
||||||
this.currentGameScene = gameScene;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Permit to create player in started room
|
|
||||||
*/
|
|
||||||
/*createCurrentPlayer(): void {
|
|
||||||
//Get started room send by the backend
|
|
||||||
this.currentGameScene.createCurrentPlayer();
|
|
||||||
//this.status = StatusGameManagerEnum.CURRENT_USER_CREATED;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
joinRoom(sceneKey: string, startX: number, startY: number, direction: string, moving: boolean){
|
|
||||||
this.ConnectionInstance.joinARoom(sceneKey, startX, startY, direction, moving);
|
|
||||||
}
|
|
||||||
|
|
||||||
onUserJoins(message: MessageUserJoined): void {
|
|
||||||
let userMessage: AddPlayerInterface = {
|
|
||||||
userId: message.userId,
|
|
||||||
character: message.character,
|
|
||||||
name: message.name,
|
|
||||||
position: message.position
|
|
||||||
}
|
|
||||||
this.getCurrentGameScene().addPlayer(userMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
onUserMoved(message: MessageUserMovedInterface): void {
|
|
||||||
this.getCurrentGameScene().updatePlayerPosition(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
onUserLeft(userId: string): void {
|
|
||||||
this.getCurrentGameScene().removePlayer(userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
initUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
|
|
||||||
// Shall we wait for room to be loaded?
|
|
||||||
/*if (this.status === StatusGameManagerEnum.IN_PROGRESS) {
|
|
||||||
return;
|
|
||||||
}*/
|
|
||||||
try {
|
|
||||||
this.getCurrentGameScene().initUsersPosition(usersPosition)
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Share group position in game
|
|
||||||
*/
|
|
||||||
shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface): void {
|
|
||||||
/*if (this.status === StatusGameManagerEnum.IN_PROGRESS) {
|
|
||||||
return;
|
|
||||||
}*/
|
|
||||||
try {
|
|
||||||
this.getCurrentGameScene().shareGroupPosition(groupPositionMessage)
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteGroup(groupId: string): void {
|
|
||||||
/*if (this.status === StatusGameManagerEnum.IN_PROGRESS) {
|
|
||||||
return;
|
|
||||||
}*/
|
|
||||||
try {
|
|
||||||
this.getCurrentGameScene().deleteGroup(groupId)
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getPlayerName(): string {
|
getPlayerName(): string {
|
||||||
return this.playerName;
|
return this.playerName;
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlayerId(): string|null {
|
|
||||||
return this.ConnectionInstance.userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
getCharacterSelected(): string {
|
getCharacterSelected(): string {
|
||||||
return this.characterUserSelected;
|
return this.characterUserSelected;
|
||||||
}
|
}
|
||||||
|
|
||||||
pushPlayerPosition(event: HasMovedEvent) {
|
|
||||||
this.ConnectionInstance.sharePosition(event.x, event.y, event.direction, event.moving);
|
|
||||||
}
|
|
||||||
|
|
||||||
loadMap(mapUrl: string, scene: Phaser.Scenes.ScenePlugin, instance: string): string {
|
loadMap(mapUrl: string, scene: Phaser.Scenes.ScenePlugin, instance: string): string {
|
||||||
let sceneKey = GameScene.getMapKeyByUrl(mapUrl);
|
const sceneKey = GameScene.getMapKeyByUrl(mapUrl);
|
||||||
|
|
||||||
let gameIndex = scene.getIndex(sceneKey);
|
const gameIndex = scene.getIndex(sceneKey);
|
||||||
if(gameIndex === -1){
|
if(gameIndex === -1){
|
||||||
let game : Phaser.Scene = GameScene.createFromUrl(mapUrl, instance);
|
const game : Phaser.Scene = GameScene.createFromUrl(mapUrl, instance);
|
||||||
scene.add(sceneKey, game, false);
|
scene.add(sceneKey, game, false);
|
||||||
}
|
}
|
||||||
return sceneKey;
|
return sceneKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
private oldSceneKey : string;
|
|
||||||
private oldMapUrlFile : string;
|
|
||||||
private oldInstance : string;
|
|
||||||
private scenePlugin: ScenePlugin;
|
|
||||||
private reconnectScene: Scene|null = null;
|
|
||||||
switchToDisconnectedScene(): void {
|
|
||||||
if (this.currentGameScene === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.log('Switching to disconnected scene');
|
|
||||||
this.oldSceneKey = this.currentGameScene.scene.key;
|
|
||||||
this.oldMapUrlFile = this.currentGameScene.MapUrlFile;
|
|
||||||
this.oldInstance = this.currentGameScene.instance;
|
|
||||||
this.currentGameScene.scene.start(ReconnectingSceneName);
|
|
||||||
this.reconnectScene = this.currentGameScene.scene.get(ReconnectingSceneName);
|
|
||||||
// Let's completely delete an purge the disconnected scene. We will start again from 0.
|
|
||||||
this.currentGameScene.scene.remove(this.oldSceneKey);
|
|
||||||
this.scenePlugin = this.currentGameScene.scene;
|
|
||||||
this.currentGameScene = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private timeoutCallback: NodeJS.Timeout|null = null;
|
|
||||||
reconnectToGameScene(lastPositionShared: PointInterface): void {
|
|
||||||
if (this.timeoutCallback !== null) {
|
|
||||||
console.log('Reconnect called but setTimeout in progress for the reconnection');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (this.reconnectScene === null) {
|
|
||||||
console.log('Reconnect called without switchToDisconnectedScene called first');
|
|
||||||
|
|
||||||
if (!this.currentGameScene) {
|
|
||||||
console.error('Reconnect called but we are not on a GameScene');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// In case we are asked to reconnect even if switchToDisconnectedScene was not triggered (can happen when a laptop goes to sleep)
|
|
||||||
this.switchToDisconnectedScene();
|
|
||||||
// Wait a bit for scene to load. Otherwise, starting ReconnectingSceneName and then starting GameScene one after the other fails for some reason.
|
|
||||||
this.timeoutCallback = setTimeout(() => {
|
|
||||||
console.log('Reconnecting to game scene from setTimeout');
|
|
||||||
this.timeoutCallback = null;
|
|
||||||
this.reconnectToGameScene(lastPositionShared);
|
|
||||||
}, 500);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.log('Reconnecting to game scene');
|
|
||||||
const game : Phaser.Scene = GameScene.createFromUrl(this.oldMapUrlFile, this.oldInstance);
|
|
||||||
this.reconnectScene.scene.add(this.oldSceneKey, game, true, { initPosition: lastPositionShared });
|
|
||||||
this.reconnectScene = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getCurrentGameScene(): GameScene {
|
|
||||||
if (this.currentGameScene === null) {
|
|
||||||
throw new Error('No current game scene enabled');
|
|
||||||
}
|
|
||||||
return this.currentGameScene;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const gameManager = new GameManager();
|
export const gameManager = new GameManager();
|
||||||
|
@ -1,13 +1,19 @@
|
|||||||
import {GameManager, gameManager, HasMovedEvent} from "./GameManager";
|
import {GameManager, gameManager, HasMovedEvent} from "./GameManager";
|
||||||
import {
|
import {
|
||||||
GroupCreatedUpdatedMessageInterface,
|
Connection,
|
||||||
|
GroupCreatedUpdatedMessageInterface, MessageUserJoined,
|
||||||
MessageUserMovedInterface,
|
MessageUserMovedInterface,
|
||||||
MessageUserPositionInterface, PointInterface, PositionInterface
|
MessageUserPositionInterface, PointInterface, PositionInterface
|
||||||
} from "../../Connection";
|
} from "../../Connection";
|
||||||
import {CurrentGamerInterface, hasMovedEventName, Player} from "../Player/Player";
|
import {CurrentGamerInterface, hasMovedEventName, Player} from "../Player/Player";
|
||||||
import { DEBUG_MODE, ZOOM_LEVEL, POSITION_DELAY } from "../../Enum/EnvironmentVariable";
|
import { DEBUG_MODE, ZOOM_LEVEL, POSITION_DELAY } from "../../Enum/EnvironmentVariable";
|
||||||
import {ITiledMap, ITiledMapLayer, ITiledTileSet} from "../Map/ITiledMap";
|
import {
|
||||||
import {PLAYER_RESOURCES} from "../Entity/Character";
|
ITiledMap,
|
||||||
|
ITiledMapLayer,
|
||||||
|
ITiledMapLayerProperty,
|
||||||
|
ITiledTileSet
|
||||||
|
} from "../Map/ITiledMap";
|
||||||
|
import {PLAYER_RESOURCES, PlayerResourceDescriptionInterface} from "../Entity/Character";
|
||||||
import Texture = Phaser.Textures.Texture;
|
import Texture = Phaser.Textures.Texture;
|
||||||
import Sprite = Phaser.GameObjects.Sprite;
|
import Sprite = Phaser.GameObjects.Sprite;
|
||||||
import CanvasTexture = Phaser.Textures.CanvasTexture;
|
import CanvasTexture = Phaser.Textures.CanvasTexture;
|
||||||
@ -16,6 +22,11 @@ import {PlayerAnimationNames} from "../Player/Animation";
|
|||||||
import {PlayerMovement} from "./PlayerMovement";
|
import {PlayerMovement} from "./PlayerMovement";
|
||||||
import {PlayersPositionInterpolator} from "./PlayersPositionInterpolator";
|
import {PlayersPositionInterpolator} from "./PlayersPositionInterpolator";
|
||||||
import {RemotePlayer} from "../Entity/RemotePlayer";
|
import {RemotePlayer} from "../Entity/RemotePlayer";
|
||||||
|
import GameObject = Phaser.GameObjects.GameObject;
|
||||||
|
import { Queue } from 'queue-typescript';
|
||||||
|
import {SimplePeer} from "../../WebRtc/SimplePeer";
|
||||||
|
import {ReconnectingSceneName} from "../Reconnecting/ReconnectingScene";
|
||||||
|
|
||||||
|
|
||||||
export enum Textures {
|
export enum Textures {
|
||||||
Player = "male1"
|
Player = "male1"
|
||||||
@ -26,6 +37,36 @@ export interface GameSceneInitInterface {
|
|||||||
startLayerName: string|undefined
|
startLayerName: string|undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface InitUserPositionEventInterface {
|
||||||
|
type: 'InitUserPositionEvent'
|
||||||
|
event: MessageUserPositionInterface[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AddPlayerEventInterface {
|
||||||
|
type: 'AddPlayerEvent'
|
||||||
|
event: AddPlayerInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RemovePlayerEventInterface {
|
||||||
|
type: 'RemovePlayerEvent'
|
||||||
|
userId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserMovedEventInterface {
|
||||||
|
type: 'UserMovedEvent'
|
||||||
|
event: MessageUserMovedInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GroupCreatedUpdatedEventInterface {
|
||||||
|
type: 'GroupCreatedUpdatedEvent'
|
||||||
|
event: GroupCreatedUpdatedMessageInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeleteGroupEventInterface {
|
||||||
|
type: 'DeleteGroupEvent'
|
||||||
|
groupId: string
|
||||||
|
}
|
||||||
|
|
||||||
export class GameScene extends Phaser.Scene {
|
export class GameScene extends Phaser.Scene {
|
||||||
GameManager : GameManager;
|
GameManager : GameManager;
|
||||||
Terrains : Array<Phaser.Tilemaps.Tileset>;
|
Terrains : Array<Phaser.Tilemaps.Tileset>;
|
||||||
@ -40,8 +81,12 @@ export class GameScene extends Phaser.Scene {
|
|||||||
startX: number;
|
startX: number;
|
||||||
startY: number;
|
startY: number;
|
||||||
circleTexture: CanvasTexture;
|
circleTexture: CanvasTexture;
|
||||||
|
pendingEvents: Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface>();
|
||||||
private initPosition: PositionInterface|null = null;
|
private initPosition: PositionInterface|null = null;
|
||||||
private playersPositionInterpolator = new PlayersPositionInterpolator();
|
private playersPositionInterpolator = new PlayersPositionInterpolator();
|
||||||
|
private connection: Connection;
|
||||||
|
private simplePeer : SimplePeer;
|
||||||
|
private connectionPromise: Promise<Connection>
|
||||||
|
|
||||||
MapKey: string;
|
MapKey: string;
|
||||||
MapUrlFile: string;
|
MapUrlFile: string;
|
||||||
@ -57,17 +102,20 @@ export class GameScene extends Phaser.Scene {
|
|||||||
y: -1000
|
y: -1000
|
||||||
}
|
}
|
||||||
|
|
||||||
PositionNextScene: Array<any> = new Array<any>();
|
private PositionNextScene: Array<Array<{ key: string, hash: string }>> = new Array<Array<{ key: string, hash: string }>>();
|
||||||
private startLayerName: string|undefined;
|
private startLayerName: string|undefined;
|
||||||
|
|
||||||
static createFromUrl(mapUrlFile: string, instance: string): GameScene {
|
static createFromUrl(mapUrlFile: string, instance: string, key: string|null = null): GameScene {
|
||||||
let key = GameScene.getMapKeyByUrl(mapUrlFile);
|
const mapKey = GameScene.getMapKeyByUrl(mapUrlFile);
|
||||||
return new GameScene(key, mapUrlFile, instance);
|
if (key === null) {
|
||||||
|
key = mapKey;
|
||||||
|
}
|
||||||
|
return new GameScene(mapKey, mapUrlFile, instance, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(MapKey : string, MapUrlFile: string, instance: string) {
|
constructor(MapKey : string, MapUrlFile: string, instance: string, key: string) {
|
||||||
super({
|
super({
|
||||||
key: MapKey
|
key: key
|
||||||
});
|
});
|
||||||
|
|
||||||
this.GameManager = gameManager;
|
this.GameManager = gameManager;
|
||||||
@ -77,13 +125,12 @@ export class GameScene extends Phaser.Scene {
|
|||||||
|
|
||||||
this.MapKey = MapKey;
|
this.MapKey = MapKey;
|
||||||
this.MapUrlFile = MapUrlFile;
|
this.MapUrlFile = MapUrlFile;
|
||||||
this.RoomId = this.instance + '__' + this.MapKey;
|
this.RoomId = this.instance + '__' + MapKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
//hook preload scene
|
//hook preload scene
|
||||||
preload(): void {
|
preload(): void {
|
||||||
this.GameManager.setCurrentGameScene(this);
|
this.load.on('filecomplete-tilemapJSON-'+this.MapKey, (key: string, type: string, data: unknown) => {
|
||||||
this.load.on('filecomplete-tilemapJSON-'+this.MapKey, (key: string, type: string, data: any) => {
|
|
||||||
this.onMapLoad(data);
|
this.onMapLoad(data);
|
||||||
});
|
});
|
||||||
//TODO strategy to add access token
|
//TODO strategy to add access token
|
||||||
@ -91,12 +138,12 @@ export class GameScene extends Phaser.Scene {
|
|||||||
// If the map has already been loaded as part of another GameScene, the "on load" event will not be triggered.
|
// If the map has already been loaded as part of another GameScene, the "on load" event will not be triggered.
|
||||||
// In this case, we check in the cache to see if the map is here and trigger the event manually.
|
// In this case, we check in the cache to see if the map is here and trigger the event manually.
|
||||||
if (this.cache.tilemap.exists(this.MapKey)) {
|
if (this.cache.tilemap.exists(this.MapKey)) {
|
||||||
let data = this.cache.tilemap.get(this.MapKey);
|
const data = this.cache.tilemap.get(this.MapKey);
|
||||||
this.onMapLoad(data);
|
this.onMapLoad(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
//add player png
|
//add player png
|
||||||
PLAYER_RESOURCES.forEach((playerResource: any) => {
|
PLAYER_RESOURCES.forEach((playerResource: PlayerResourceDescriptionInterface) => {
|
||||||
this.load.spritesheet(
|
this.load.spritesheet(
|
||||||
playerResource.name,
|
playerResource.name,
|
||||||
playerResource.img,
|
playerResource.img,
|
||||||
@ -105,13 +152,76 @@ export class GameScene extends Phaser.Scene {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
||||||
|
|
||||||
|
this.connectionPromise = Connection.createConnection(gameManager.getPlayerName(), gameManager.getCharacterSelected()).then((connection : Connection) => {
|
||||||
|
this.connection = connection;
|
||||||
|
|
||||||
|
connection.onUserJoins((message: MessageUserJoined) => {
|
||||||
|
const userMessage: AddPlayerInterface = {
|
||||||
|
userId: message.userId,
|
||||||
|
character: message.character,
|
||||||
|
name: message.name,
|
||||||
|
position: message.position
|
||||||
|
}
|
||||||
|
this.addPlayer(userMessage);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onUserMoved((message: MessageUserMovedInterface) => {
|
||||||
|
this.updatePlayerPosition(message);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onUserLeft((userId: string) => {
|
||||||
|
this.removePlayer(userId);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onGroupUpdatedOrCreated((groupPositionMessage: GroupCreatedUpdatedMessageInterface) => {
|
||||||
|
this.shareGroupPosition(groupPositionMessage);
|
||||||
|
})
|
||||||
|
|
||||||
|
connection.onGroupDeleted((groupId: string) => {
|
||||||
|
try {
|
||||||
|
this.deleteGroup(groupId);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
connection.onServerDisconnected(() => {
|
||||||
|
console.log('Player disconnected from server. Reloading scene.');
|
||||||
|
|
||||||
|
this.simplePeer.closeAllConnections();
|
||||||
|
|
||||||
|
const key = 'somekey'+Math.round(Math.random()*10000);
|
||||||
|
const game : Phaser.Scene = GameScene.createFromUrl(this.MapUrlFile, this.instance, key);
|
||||||
|
this.scene.add(key, game, true,
|
||||||
|
{
|
||||||
|
initPosition: {
|
||||||
|
x: this.CurrentPlayer.x,
|
||||||
|
y: this.CurrentPlayer.y
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.scene.stop(this.scene.key);
|
||||||
|
this.scene.remove(this.scene.key);
|
||||||
|
})
|
||||||
|
|
||||||
|
// When connection is performed, let's connect SimplePeer
|
||||||
|
this.simplePeer = new SimplePeer(this.connection);
|
||||||
|
|
||||||
|
this.scene.wake();
|
||||||
|
this.scene.sleep(ReconnectingSceneName);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FIXME: we need to put a "unknown" instead of a "any" and validate the structure of the JSON we are receiving.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
private onMapLoad(data: any): void {
|
private onMapLoad(data: any): void {
|
||||||
// Triggered when the map is loaded
|
// Triggered when the map is loaded
|
||||||
// Load tiles attached to the map recursively
|
// Load tiles attached to the map recursively
|
||||||
this.mapFile = data.data;
|
this.mapFile = data.data;
|
||||||
let url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/'));
|
const url = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/'));
|
||||||
this.mapFile.tilesets.forEach((tileset) => {
|
this.mapFile.tilesets.forEach((tileset) => {
|
||||||
if (typeof tileset.name === 'undefined' || typeof tileset.image === 'undefined') {
|
if (typeof tileset.name === 'undefined' || typeof tileset.image === 'undefined') {
|
||||||
console.warn("Don't know how to handle tileset ", tileset)
|
console.warn("Don't know how to handle tileset ", tileset)
|
||||||
@ -145,7 +255,7 @@ export class GameScene extends Phaser.Scene {
|
|||||||
//add layer on map
|
//add layer on map
|
||||||
this.Layers = new Array<Phaser.Tilemaps.StaticTilemapLayer>();
|
this.Layers = new Array<Phaser.Tilemaps.StaticTilemapLayer>();
|
||||||
let depth = -2;
|
let depth = -2;
|
||||||
for (let layer of this.mapFile.layers) {
|
for (const layer of this.mapFile.layers) {
|
||||||
if (layer.type === 'tilelayer') {
|
if (layer.type === 'tilelayer') {
|
||||||
this.addLayer(this.Map.createStaticLayer(layer.name, this.Terrains, 0, 0).setDepth(depth));
|
this.addLayer(this.Map.createStaticLayer(layer.name, this.Terrains, 0, 0).setDepth(depth));
|
||||||
}
|
}
|
||||||
@ -167,9 +277,9 @@ export class GameScene extends Phaser.Scene {
|
|||||||
} else {
|
} else {
|
||||||
// Now, let's find the start layer
|
// Now, let's find the start layer
|
||||||
if (this.startLayerName) {
|
if (this.startLayerName) {
|
||||||
for (let layer of this.mapFile.layers) {
|
for (const layer of this.mapFile.layers) {
|
||||||
if (this.startLayerName === layer.name && layer.type === 'tilelayer' && this.isStartLayer(layer)) {
|
if (this.startLayerName === layer.name && layer.type === 'tilelayer' && this.isStartLayer(layer)) {
|
||||||
let startPosition = this.startUser(layer);
|
const startPosition = this.startUser(layer);
|
||||||
this.startX = startPosition.x;
|
this.startX = startPosition.x;
|
||||||
this.startY = startPosition.y;
|
this.startY = startPosition.y;
|
||||||
}
|
}
|
||||||
@ -177,9 +287,9 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
if (this.startX === undefined) {
|
if (this.startX === undefined) {
|
||||||
// If we have no start layer specified or if the hash passed does not exist, let's go with the default start position.
|
// If we have no start layer specified or if the hash passed does not exist, let's go with the default start position.
|
||||||
for (let layer of this.mapFile.layers) {
|
for (const layer of this.mapFile.layers) {
|
||||||
if (layer.type === 'tilelayer' && layer.name === "start") {
|
if (layer.type === 'tilelayer' && layer.name === "start") {
|
||||||
let startPosition = this.startUser(layer);
|
const startPosition = this.startUser(layer);
|
||||||
this.startX = startPosition.x;
|
this.startX = startPosition.x;
|
||||||
this.startY = startPosition.y;
|
this.startY = startPosition.y;
|
||||||
}
|
}
|
||||||
@ -211,12 +321,12 @@ export class GameScene extends Phaser.Scene {
|
|||||||
|
|
||||||
|
|
||||||
// Let's generate the circle for the group delimiter
|
// Let's generate the circle for the group delimiter
|
||||||
let circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite');
|
const circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite');
|
||||||
if(circleElement) {
|
if(circleElement) {
|
||||||
this.textures.remove('circleSprite');
|
this.textures.remove('circleSprite');
|
||||||
}
|
}
|
||||||
this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
|
this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
|
||||||
let context = this.circleTexture.context;
|
const context = this.circleTexture.context;
|
||||||
context.beginPath();
|
context.beginPath();
|
||||||
context.arc(48, 48, 48, 0, 2 * Math.PI, false);
|
context.arc(48, 48, 48, 0, 2 * Math.PI, false);
|
||||||
// context.lineWidth = 5;
|
// context.lineWidth = 5;
|
||||||
@ -225,12 +335,23 @@ export class GameScene extends Phaser.Scene {
|
|||||||
this.circleTexture.refresh();
|
this.circleTexture.refresh();
|
||||||
|
|
||||||
// Let's alter browser history
|
// Let's alter browser history
|
||||||
let url = new URL(this.MapUrlFile);
|
const url = new URL(this.MapUrlFile);
|
||||||
let path = '/_/'+this.instance+'/'+url.host+url.pathname;
|
let path = '/_/'+this.instance+'/'+url.host+url.pathname;
|
||||||
if (this.startLayerName) {
|
if (this.startLayerName) {
|
||||||
path += '#'+this.startLayerName;
|
path += '#'+this.startLayerName;
|
||||||
}
|
}
|
||||||
window.history.pushState({}, 'WorkAdventure', path);
|
window.history.pushState({}, 'WorkAdventure', path);
|
||||||
|
|
||||||
|
// Let's pause the scene if the connection is not established yet
|
||||||
|
if (this.connection === undefined) {
|
||||||
|
// Let's wait 0.5 seconds before printing the "connecting" screen to avoid blinking
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.connection === undefined) {
|
||||||
|
this.scene.sleep();
|
||||||
|
this.scene.launch(ReconnectingSceneName);
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private getExitSceneUrl(layer: ITiledMapLayer): string|undefined {
|
private getExitSceneUrl(layer: ITiledMapLayer): string|undefined {
|
||||||
@ -246,11 +367,11 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private getProperty(layer: ITiledMapLayer, name: string): string|boolean|number|undefined {
|
private getProperty(layer: ITiledMapLayer, name: string): string|boolean|number|undefined {
|
||||||
let properties : any = layer.properties;
|
const properties = layer.properties;
|
||||||
if (!properties) {
|
if (!properties) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
let obj = properties.find((property:any) => property.name === name);
|
const obj = properties.find((property: ITiledMapLayerProperty) => property.name === name);
|
||||||
if (obj === undefined) {
|
if (obj === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@ -265,7 +386,7 @@ export class GameScene extends Phaser.Scene {
|
|||||||
* @param tileHeight
|
* @param tileHeight
|
||||||
*/
|
*/
|
||||||
private loadNextGame(layer: ITiledMapLayer, mapWidth: number, tileWidth: number, tileHeight: number){
|
private loadNextGame(layer: ITiledMapLayer, mapWidth: number, tileWidth: number, tileHeight: number){
|
||||||
let exitSceneUrl = this.getExitSceneUrl(layer);
|
const exitSceneUrl = this.getExitSceneUrl(layer);
|
||||||
if (exitSceneUrl === undefined) {
|
if (exitSceneUrl === undefined) {
|
||||||
throw new Error('Layer is not an exit scene layer.');
|
throw new Error('Layer is not an exit scene layer.');
|
||||||
}
|
}
|
||||||
@ -275,18 +396,18 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: eventually compute a relative URL
|
// TODO: eventually compute a relative URL
|
||||||
let absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href;
|
const absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href;
|
||||||
let exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene, instance);
|
const exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene, instance);
|
||||||
|
|
||||||
let tiles : number[] = layer.data as number[];
|
const tiles : number[] = layer.data as number[];
|
||||||
for (let key=0; key < tiles.length; key++) {
|
for (let key=0; key < tiles.length; key++) {
|
||||||
let objectKey = tiles[key];
|
const objectKey = tiles[key];
|
||||||
if(objectKey === 0){
|
if(objectKey === 0){
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
//key + 1 because the start x = 0;
|
//key + 1 because the start x = 0;
|
||||||
let y : number = parseInt(((key + 1) / mapWidth).toString());
|
const y : number = parseInt(((key + 1) / mapWidth).toString());
|
||||||
let x : number = key - (y * mapWidth);
|
const x : number = key - (y * mapWidth);
|
||||||
|
|
||||||
let hash = new URL(exitSceneUrl, this.MapUrlFile).hash;
|
let hash = new URL(exitSceneUrl, this.MapUrlFile).hash;
|
||||||
if (hash) {
|
if (hash) {
|
||||||
@ -294,15 +415,13 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//push and save switching case
|
//push and save switching case
|
||||||
// TODO: this is not efficient. We should refactor that to enable a search by key. For instance: this.PositionNextScene[y][x] = exitSceneKey
|
if (this.PositionNextScene[y] === undefined) {
|
||||||
this.PositionNextScene.push({
|
this.PositionNextScene[y] = new Array<{key: string, hash: string}>();
|
||||||
xStart: (x * tileWidth),
|
}
|
||||||
yStart: (y * tileWidth),
|
this.PositionNextScene[y][x] = {
|
||||||
xEnd: ((x +1) * tileHeight),
|
|
||||||
yEnd: ((y + 1) * tileHeight),
|
|
||||||
key: exitSceneKey,
|
key: exitSceneKey,
|
||||||
hash
|
hash
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -310,14 +429,17 @@ export class GameScene extends Phaser.Scene {
|
|||||||
* @param layer
|
* @param layer
|
||||||
*/
|
*/
|
||||||
private startUser(layer: ITiledMapLayer): PositionInterface {
|
private startUser(layer: ITiledMapLayer): PositionInterface {
|
||||||
let tiles : any = layer.data;
|
const tiles = layer.data;
|
||||||
let possibleStartPositions : PositionInterface[] = [];
|
if (typeof(tiles) === 'string') {
|
||||||
|
throw new Error('The content of a JSON map must be filled as a JSON array, not as a string');
|
||||||
|
}
|
||||||
|
const possibleStartPositions : PositionInterface[] = [];
|
||||||
tiles.forEach((objectKey : number, key: number) => {
|
tiles.forEach((objectKey : number, key: number) => {
|
||||||
if(objectKey === 0){
|
if(objectKey === 0){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let y = Math.floor(key / layer.width);
|
const y = Math.floor(key / layer.width);
|
||||||
let x = key % layer.width;
|
const x = key % layer.width;
|
||||||
|
|
||||||
possibleStartPositions.push({x: x*32, y: y*32});
|
possibleStartPositions.push({x: x*32, y: y*32});
|
||||||
});
|
});
|
||||||
@ -347,7 +469,7 @@ export class GameScene extends Phaser.Scene {
|
|||||||
createCollisionWithPlayer() {
|
createCollisionWithPlayer() {
|
||||||
//add collision layer
|
//add collision layer
|
||||||
this.Layers.forEach((Layer: Phaser.Tilemaps.StaticTilemapLayer) => {
|
this.Layers.forEach((Layer: Phaser.Tilemaps.StaticTilemapLayer) => {
|
||||||
this.physics.add.collider(this.CurrentPlayer, Layer, (object1: any, object2: any) => {
|
this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => {
|
||||||
//this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name)
|
//this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name)
|
||||||
});
|
});
|
||||||
Layer.setCollisionByProperty({collides: true});
|
Layer.setCollisionByProperty({collides: true});
|
||||||
@ -363,11 +485,11 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createCollisionObject(){
|
createCollisionObject(){
|
||||||
this.Objects.forEach((Object : Phaser.Physics.Arcade.Sprite) => {
|
/*this.Objects.forEach((Object : Phaser.Physics.Arcade.Sprite) => {
|
||||||
this.physics.add.collider(this.CurrentPlayer, Object, (object1: any, object2: any) => {
|
this.physics.add.collider(this.CurrentPlayer, Object, (object1, object2) => {
|
||||||
//this.CurrentPlayer.say("Collision with object : " + (object2 as Phaser.Physics.Arcade.Sprite).texture.key)
|
this.CurrentPlayer.say("Collision with object : " + (object2 as Phaser.Physics.Arcade.Sprite).texture.key)
|
||||||
});
|
});
|
||||||
})
|
})*/
|
||||||
}
|
}
|
||||||
|
|
||||||
createCurrentPlayer(){
|
createCurrentPlayer(){
|
||||||
@ -388,10 +510,14 @@ export class GameScene extends Phaser.Scene {
|
|||||||
this.createCollisionObject();
|
this.createCollisionObject();
|
||||||
|
|
||||||
//join room
|
//join room
|
||||||
this.GameManager.joinRoom(this.RoomId, this.startX, this.startY, PlayerAnimationNames.WalkDown, false);
|
this.connectionPromise.then((connection: Connection) => {
|
||||||
|
connection.joinARoom(this.RoomId, this.startX, this.startY, PlayerAnimationNames.WalkDown, false).then((userPositions: MessageUserPositionInterface[]) => {
|
||||||
|
this.initUsersPosition(userPositions);
|
||||||
|
});
|
||||||
|
|
||||||
//listen event to share position of user
|
//listen event to share position of user
|
||||||
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
|
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pushPlayerPosition(event: HasMovedEvent) {
|
pushPlayerPosition(event: HasMovedEvent) {
|
||||||
@ -423,18 +549,18 @@ export class GameScene extends Phaser.Scene {
|
|||||||
private doPushPlayerPosition(event: HasMovedEvent): void {
|
private doPushPlayerPosition(event: HasMovedEvent): void {
|
||||||
this.lastMoveEventSent = event;
|
this.lastMoveEventSent = event;
|
||||||
this.lastSentTick = this.currentTick;
|
this.lastSentTick = this.currentTick;
|
||||||
this.GameManager.pushPlayerPosition(event);
|
this.connection.sharePosition(event.x, event.y, event.direction, event.moving);
|
||||||
}
|
}
|
||||||
|
|
||||||
EventToClickOnTile(){
|
EventToClickOnTile(){
|
||||||
// debug code to get a tile properties by clicking on it
|
// debug code to get a tile properties by clicking on it
|
||||||
this.input.on("pointerdown", (pointer: Phaser.Input.Pointer)=>{
|
/*this.input.on("pointerdown", (pointer: Phaser.Input.Pointer)=>{
|
||||||
//pixel position toz tile position
|
//pixel position toz tile position
|
||||||
let tile = this.Map.getTileAt(this.Map.worldToTileX(pointer.worldX), this.Map.worldToTileY(pointer.worldY));
|
const tile = this.Map.getTileAt(this.Map.worldToTileX(pointer.worldX), this.Map.worldToTileY(pointer.worldY));
|
||||||
if(tile){
|
if(tile){
|
||||||
this.CurrentPlayer.say("Your touch " + tile.layer.name);
|
this.CurrentPlayer.say("Your touch " + tile.layer.name);
|
||||||
}
|
}
|
||||||
});
|
});*/
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -445,19 +571,46 @@ export class GameScene extends Phaser.Scene {
|
|||||||
this.currentTick = time;
|
this.currentTick = time;
|
||||||
this.CurrentPlayer.moveUser(delta);
|
this.CurrentPlayer.moveUser(delta);
|
||||||
|
|
||||||
|
// Let's handle all events
|
||||||
|
while (this.pendingEvents.length !== 0) {
|
||||||
|
const event = this.pendingEvents.dequeue();
|
||||||
|
switch (event.type) {
|
||||||
|
case "InitUserPositionEvent":
|
||||||
|
this.doInitUsersPosition(event.event);
|
||||||
|
break;
|
||||||
|
case "AddPlayerEvent":
|
||||||
|
this.doAddPlayer(event.event);
|
||||||
|
break;
|
||||||
|
case "RemovePlayerEvent":
|
||||||
|
this.doRemovePlayer(event.userId);
|
||||||
|
break;
|
||||||
|
case "UserMovedEvent":
|
||||||
|
this.doUpdatePlayerPosition(event.event);
|
||||||
|
break;
|
||||||
|
case "GroupCreatedUpdatedEvent":
|
||||||
|
this.doShareGroupPosition(event.event);
|
||||||
|
break;
|
||||||
|
case "DeleteGroupEvent":
|
||||||
|
this.doDeleteGroup(event.groupId);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Let's move all users
|
// Let's move all users
|
||||||
let updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time);
|
const updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time);
|
||||||
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: string) => {
|
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: string) => {
|
||||||
let player : RemotePlayer | undefined = this.MapPlayersByKey.get(userId);
|
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(userId);
|
||||||
if (player === undefined) {
|
if (player === undefined) {
|
||||||
throw new Error('Cannot find player with ID "' + userId +'"');
|
throw new Error('Cannot find player with ID "' + userId +'"');
|
||||||
}
|
}
|
||||||
player.updatePosition(moveEvent);
|
player.updatePosition(moveEvent);
|
||||||
});
|
});
|
||||||
|
|
||||||
let nextSceneKey = this.checkToExit();
|
const nextSceneKey = this.checkToExit();
|
||||||
if(nextSceneKey){
|
if(nextSceneKey){
|
||||||
// We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map.
|
// We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map.
|
||||||
|
this.connection.closeConnection();
|
||||||
|
this.scene.stop();
|
||||||
this.scene.remove(this.scene.key);
|
this.scene.remove(this.scene.key);
|
||||||
this.scene.start(nextSceneKey.key, {
|
this.scene.start(nextSceneKey.key, {
|
||||||
startLayerName: nextSceneKey.hash
|
startLayerName: nextSceneKey.hash
|
||||||
@ -468,23 +621,33 @@ export class GameScene extends Phaser.Scene {
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
checkToExit(){
|
checkToExit(): {key: string, hash: string} | null {
|
||||||
if(this.PositionNextScene.length === 0){
|
const x = Math.floor(this.CurrentPlayer.x / 32);
|
||||||
|
const y = Math.floor(this.CurrentPlayer.y / 32);
|
||||||
|
|
||||||
|
if (this.PositionNextScene[y] !== undefined && this.PositionNextScene[y][x] !== undefined) {
|
||||||
|
return this.PositionNextScene[y][x];
|
||||||
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return this.PositionNextScene.find((position : any) => {
|
|
||||||
return position.xStart <= this.CurrentPlayer.x && this.CurrentPlayer.x <= position.xEnd
|
|
||||||
&& position.yStart <= this.CurrentPlayer.y && this.CurrentPlayer.y <= position.yEnd
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public initUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
|
/**
|
||||||
if(!this.CurrentPlayer){
|
* Called by the connexion when the full list of user position is received.
|
||||||
console.error('Cannot initiate users list because map is not loaded yet')
|
*/
|
||||||
return;
|
private initUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
|
||||||
|
this.pendingEvents.enqueue({
|
||||||
|
type: "InitUserPositionEvent",
|
||||||
|
event: usersPosition
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let currentPlayerId = this.GameManager.getPlayerId();
|
/**
|
||||||
|
* Put all the players on the map on map load.
|
||||||
|
*/
|
||||||
|
private doInitUsersPosition(usersPosition: MessageUserPositionInterface[]): void {
|
||||||
|
const currentPlayerId = this.connection.getUserId();
|
||||||
|
|
||||||
// clean map
|
// clean map
|
||||||
this.MapPlayersByKey.forEach((player: RemotePlayer) => {
|
this.MapPlayersByKey.forEach((player: RemotePlayer) => {
|
||||||
@ -503,9 +666,19 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create new player
|
* Called by the connexion when a new player arrives on a map
|
||||||
*/
|
*/
|
||||||
public addPlayer(addPlayerData : AddPlayerInterface) : void {
|
public addPlayer(addPlayerData : AddPlayerInterface) : void {
|
||||||
|
this.pendingEvents.enqueue({
|
||||||
|
type: "AddPlayerEvent",
|
||||||
|
event: addPlayerData
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create new player
|
||||||
|
*/
|
||||||
|
private doAddPlayer(addPlayerData : AddPlayerInterface) : void {
|
||||||
//check if exist player, if exist, move position
|
//check if exist player, if exist, move position
|
||||||
if(this.MapPlayersByKey.has(addPlayerData.userId)){
|
if(this.MapPlayersByKey.has(addPlayerData.userId)){
|
||||||
this.updatePlayerPosition({
|
this.updatePlayerPosition({
|
||||||
@ -515,7 +688,7 @@ export class GameScene extends Phaser.Scene {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
//initialise player
|
//initialise player
|
||||||
let player = new RemotePlayer(
|
const player = new RemotePlayer(
|
||||||
addPlayerData.userId,
|
addPlayerData.userId,
|
||||||
this,
|
this,
|
||||||
addPlayerData.position.x,
|
addPlayerData.position.x,
|
||||||
@ -535,9 +708,18 @@ export class GameScene extends Phaser.Scene {
|
|||||||
});*/
|
});*/
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called by the connexion when a player is removed from the map
|
||||||
|
*/
|
||||||
public removePlayer(userId: string) {
|
public removePlayer(userId: string) {
|
||||||
console.log('Removing player ', userId)
|
this.pendingEvents.enqueue({
|
||||||
let player = this.MapPlayersByKey.get(userId);
|
type: "RemovePlayerEvent",
|
||||||
|
userId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private doRemovePlayer(userId: string) {
|
||||||
|
const player = this.MapPlayersByKey.get(userId);
|
||||||
if (player === undefined) {
|
if (player === undefined) {
|
||||||
console.error('Cannot find user with id ', userId);
|
console.error('Cannot find user with id ', userId);
|
||||||
} else {
|
} else {
|
||||||
@ -548,27 +730,43 @@ export class GameScene extends Phaser.Scene {
|
|||||||
this.playersPositionInterpolator.removePlayer(userId);
|
this.playersPositionInterpolator.removePlayer(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
updatePlayerPosition(message: MessageUserMovedInterface): void {
|
public updatePlayerPosition(message: MessageUserMovedInterface): void {
|
||||||
let player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
|
this.pendingEvents.enqueue({
|
||||||
|
type: "UserMovedEvent",
|
||||||
|
event: message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private doUpdatePlayerPosition(message: MessageUserMovedInterface): void {
|
||||||
|
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).
|
||||||
// Instead we use the PlayersPositionInterpolator that will do a smooth animation over the next 200ms.
|
// Instead we use the PlayersPositionInterpolator that will do a smooth animation over the next 200ms.
|
||||||
let playerMovement = new PlayerMovement({ x: player.x, y: player.y }, this.currentTick, message.position, this.currentTick + POSITION_DELAY);
|
const playerMovement = new PlayerMovement({ x: player.x, y: player.y }, this.currentTick, message.position, this.currentTick + POSITION_DELAY);
|
||||||
this.playersPositionInterpolator.updatePlayerPosition(player.userId, playerMovement);
|
this.playersPositionInterpolator.updatePlayerPosition(player.userId, playerMovement);
|
||||||
}
|
}
|
||||||
|
|
||||||
shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) {
|
public shareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) {
|
||||||
let groupId = groupPositionMessage.groupId;
|
this.pendingEvents.enqueue({
|
||||||
|
type: "GroupCreatedUpdatedEvent",
|
||||||
|
event: groupPositionMessage
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let group = this.groups.get(groupId);
|
private doShareGroupPosition(groupPositionMessage: GroupCreatedUpdatedMessageInterface) {
|
||||||
|
const groupId = groupPositionMessage.groupId;
|
||||||
|
|
||||||
|
const group = this.groups.get(groupId);
|
||||||
if (group !== undefined) {
|
if (group !== undefined) {
|
||||||
group.setPosition(Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.y));
|
group.setPosition(Math.round(groupPositionMessage.position.x), Math.round(groupPositionMessage.position.y));
|
||||||
} else {
|
} else {
|
||||||
// TODO: circle radius should not be hard stored
|
// TODO: circle radius should not be hard stored
|
||||||
let sprite = new Sprite(
|
const sprite = new Sprite(
|
||||||
this,
|
this,
|
||||||
Math.round(groupPositionMessage.position.x),
|
Math.round(groupPositionMessage.position.x),
|
||||||
Math.round(groupPositionMessage.position.y),
|
Math.round(groupPositionMessage.position.y),
|
||||||
@ -580,7 +778,14 @@ export class GameScene extends Phaser.Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
deleteGroup(groupId: string): void {
|
deleteGroup(groupId: string): void {
|
||||||
let group = this.groups.get(groupId);
|
this.pendingEvents.enqueue({
|
||||||
|
type: "DeleteGroupEvent",
|
||||||
|
groupId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
doDeleteGroup(groupId: string): void {
|
||||||
|
const group = this.groups.get(groupId);
|
||||||
if(!group){
|
if(!group){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -590,8 +795,8 @@ export class GameScene extends Phaser.Scene {
|
|||||||
|
|
||||||
public static getMapKeyByUrl(mapUrlStart: string) : string {
|
public static getMapKeyByUrl(mapUrlStart: string) : string {
|
||||||
// FIXME: the key should be computed from the full URL of the map.
|
// FIXME: the key should be computed from the full URL of the map.
|
||||||
let startPos = mapUrlStart.indexOf('://')+3;
|
const startPos = mapUrlStart.indexOf('://')+3;
|
||||||
let endPos = mapUrlStart.indexOf(".json");
|
const endPos = mapUrlStart.indexOf(".json");
|
||||||
return mapUrlStart.substring(startPos, endPos);
|
return mapUrlStart.substring(startPos, endPos);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -23,8 +23,8 @@ export class PlayerMovement {
|
|||||||
return this.endPosition;
|
return this.endPosition;
|
||||||
}
|
}
|
||||||
|
|
||||||
let x = (this.endPosition.x - this.startPosition.x) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.x;
|
const x = (this.endPosition.x - this.startPosition.x) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.x;
|
||||||
let y = (this.endPosition.y - this.startPosition.y) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.y;
|
const y = (this.endPosition.y - this.startPosition.y) * ((tick - this.startTick) / (this.endTick - this.startTick)) + this.startPosition.y;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
x,
|
x,
|
||||||
|
@ -17,7 +17,7 @@ export class PlayersPositionInterpolator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getUpdatedPositions(tick: number) : Map<string, HasMovedEvent> {
|
getUpdatedPositions(tick: number) : Map<string, HasMovedEvent> {
|
||||||
let positions = new Map<string, HasMovedEvent>();
|
const positions = new Map<string, HasMovedEvent>();
|
||||||
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: string) => {
|
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: string) => {
|
||||||
if (playerMovement.isOutdated(tick)) {
|
if (playerMovement.isOutdated(tick)) {
|
||||||
//console.log("outdated")
|
//console.log("outdated")
|
||||||
|
@ -4,7 +4,7 @@ import {TextInput} from "../Components/TextInput";
|
|||||||
import {ClickButton} from "../Components/ClickButton";
|
import {ClickButton} from "../Components/ClickButton";
|
||||||
import Image = Phaser.GameObjects.Image;
|
import Image = Phaser.GameObjects.Image;
|
||||||
import Rectangle = Phaser.GameObjects.Rectangle;
|
import Rectangle = Phaser.GameObjects.Rectangle;
|
||||||
import {PLAYER_RESOURCES} from "../Entity/Character";
|
import {PLAYER_RESOURCES, PlayerResourceDescriptionInterface} from "../Entity/Character";
|
||||||
import {cypressAsserter} from "../../Cypress/CypressAsserter";
|
import {cypressAsserter} from "../../Cypress/CypressAsserter";
|
||||||
import {SelectCharacterSceneInitDataInterface, SelectCharacterSceneName} from "./SelectCharacterScene";
|
import {SelectCharacterSceneInitDataInterface, SelectCharacterSceneName} from "./SelectCharacterScene";
|
||||||
|
|
||||||
@ -40,7 +40,7 @@ export class LoginScene extends Phaser.Scene {
|
|||||||
this.load.bitmapFont(LoginTextures.mainFont, 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
this.load.bitmapFont(LoginTextures.mainFont, 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
||||||
cypressAsserter.preloadFinished();
|
cypressAsserter.preloadFinished();
|
||||||
//add player png
|
//add player png
|
||||||
PLAYER_RESOURCES.forEach((playerResource: any) => {
|
PLAYER_RESOURCES.forEach((playerResource: PlayerResourceDescriptionInterface) => {
|
||||||
this.load.spritesheet(
|
this.load.spritesheet(
|
||||||
playerResource.name,
|
playerResource.name,
|
||||||
playerResource.img,
|
playerResource.img,
|
||||||
@ -67,7 +67,7 @@ export class LoginScene extends Phaser.Scene {
|
|||||||
this.logo = new Image(this, this.game.renderer.width - 30, this.game.renderer.height - 20, LoginTextures.icon);
|
this.logo = new Image(this, this.game.renderer.width - 30, this.game.renderer.height - 20, LoginTextures.icon);
|
||||||
this.add.existing(this.logo);
|
this.add.existing(this.logo);
|
||||||
|
|
||||||
let infoText = "Commands: \n - Arrows or Z,Q,S,D to move\n - SHIFT to run";
|
const infoText = "Commands: \n - Arrows or Z,Q,S,D to move\n - SHIFT to run";
|
||||||
this.infoTextField = new TextField(this, 10, this.game.renderer.height - 35, infoText);
|
this.infoTextField = new TextField(this, 10, this.game.renderer.height - 35, infoText);
|
||||||
|
|
||||||
this.input.keyboard.on('keyup-ENTER', () => {
|
this.input.keyboard.on('keyup-ENTER', () => {
|
||||||
|
@ -3,8 +3,9 @@ import {TextField} from "../Components/TextField";
|
|||||||
import {ClickButton} from "../Components/ClickButton";
|
import {ClickButton} from "../Components/ClickButton";
|
||||||
import Image = Phaser.GameObjects.Image;
|
import Image = Phaser.GameObjects.Image;
|
||||||
import Rectangle = Phaser.GameObjects.Rectangle;
|
import Rectangle = Phaser.GameObjects.Rectangle;
|
||||||
import {PLAYER_RESOURCES} from "../Entity/Character";
|
import {PLAYER_RESOURCES, PlayerResourceDescriptionInterface} from "../Entity/Character";
|
||||||
import {GameSceneInitInterface} from "../Game/GameScene";
|
import {GameSceneInitInterface} from "../Game/GameScene";
|
||||||
|
import {StartMapInterface} from "../../Connection";
|
||||||
|
|
||||||
//todo: put this constants in a dedicated file
|
//todo: put this constants in a dedicated file
|
||||||
export const SelectCharacterSceneName = "SelectCharacterScene";
|
export const SelectCharacterSceneName = "SelectCharacterScene";
|
||||||
@ -47,7 +48,7 @@ export class SelectCharacterScene extends Phaser.Scene {
|
|||||||
// Note: arcade.png from the Phaser 3 examples at: https://github.com/photonstorm/phaser3-examples/tree/master/public/assets/fonts/bitmap
|
// Note: arcade.png from the Phaser 3 examples at: https://github.com/photonstorm/phaser3-examples/tree/master/public/assets/fonts/bitmap
|
||||||
this.load.bitmapFont(LoginTextures.mainFont, 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
this.load.bitmapFont(LoginTextures.mainFont, 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
||||||
//add player png
|
//add player png
|
||||||
PLAYER_RESOURCES.forEach((playerResource: any) => {
|
PLAYER_RESOURCES.forEach((playerResource: PlayerResourceDescriptionInterface) => {
|
||||||
this.load.spritesheet(
|
this.load.spritesheet(
|
||||||
playerResource.name,
|
playerResource.name,
|
||||||
playerResource.img,
|
playerResource.img,
|
||||||
@ -63,7 +64,7 @@ export class SelectCharacterScene extends Phaser.Scene {
|
|||||||
this.pressReturnField = new TextField(this, this.game.renderer.width / 2, 230, 'Press enter to start');
|
this.pressReturnField = new TextField(this, this.game.renderer.width / 2, 230, 'Press enter to start');
|
||||||
this.pressReturnField.setOrigin(0.5).setCenterAlign()
|
this.pressReturnField.setOrigin(0.5).setCenterAlign()
|
||||||
|
|
||||||
let rectangleXStart = this.game.renderer.width / 2 - (this.nbCharactersPerRow / 2) * 32 + 16;
|
const rectangleXStart = this.game.renderer.width / 2 - (this.nbCharactersPerRow / 2) * 32 + 16;
|
||||||
|
|
||||||
this.selectedRectangle = this.add.rectangle(rectangleXStart, 90, 32, 32).setStrokeStyle(2, 0xFFFFFF);
|
this.selectedRectangle = this.add.rectangle(rectangleXStart, 90, 32, 32).setStrokeStyle(2, 0xFFFFFF);
|
||||||
|
|
||||||
@ -103,8 +104,8 @@ export class SelectCharacterScene extends Phaser.Scene {
|
|||||||
this.createCurrentPlayer();
|
this.createCurrentPlayer();
|
||||||
|
|
||||||
if (window.localStorage) {
|
if (window.localStorage) {
|
||||||
let playerNumberStr: string = window.localStorage.getItem('selectedPlayer') ?? '0';
|
const playerNumberStr: string = window.localStorage.getItem('selectedPlayer') ?? '0';
|
||||||
let playerNumber: number = Number(playerNumberStr);
|
const playerNumber: number = Number(playerNumberStr);
|
||||||
this.selectedRectangleXPos = playerNumber % this.nbCharactersPerRow;
|
this.selectedRectangleXPos = playerNumber % this.nbCharactersPerRow;
|
||||||
this.selectedRectangleYPos = Math.floor(playerNumber / this.nbCharactersPerRow);
|
this.selectedRectangleYPos = Math.floor(playerNumber / this.nbCharactersPerRow);
|
||||||
this.updateSelectedPlayer();
|
this.updateSelectedPlayer();
|
||||||
@ -115,63 +116,60 @@ export class SelectCharacterScene extends Phaser.Scene {
|
|||||||
this.pressReturnField.setVisible(!!(Math.floor(time / 500) % 2));
|
this.pressReturnField.setVisible(!!(Math.floor(time / 500) % 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async login(name: string) {
|
private async login(name: string): Promise<StartMapInterface> {
|
||||||
return gameManager.connect(name, this.selectedPlayer.texture.key).then(() => {
|
gameManager.storePlayerDetails(name, this.selectedPlayer.texture.key);
|
||||||
|
|
||||||
// Do we have a start URL in the address bar? If so, let's redirect to this address
|
// Do we have a start URL in the address bar? If so, let's redirect to this address
|
||||||
let instanceAndMapUrl = this.findMapUrl();
|
const instanceAndMapUrl = this.findMapUrl();
|
||||||
if (instanceAndMapUrl !== null) {
|
if (instanceAndMapUrl !== null) {
|
||||||
let [mapUrl, instance] = instanceAndMapUrl;
|
const [mapUrl, instance] = instanceAndMapUrl;
|
||||||
let key = gameManager.loadMap(mapUrl, this.scene, instance);
|
const key = gameManager.loadMap(mapUrl, this.scene, instance);
|
||||||
this.scene.start(key, {
|
this.scene.start(key, {
|
||||||
startLayerName: window.location.hash ? window.location.hash.substr(1) : undefined
|
startLayerName: window.location.hash ? window.location.hash.substr(1) : undefined
|
||||||
} as GameSceneInitInterface);
|
} as GameSceneInitInterface);
|
||||||
return mapUrl;
|
return {
|
||||||
|
mapUrlStart: mapUrl,
|
||||||
|
startInstance: instance
|
||||||
|
};
|
||||||
} else {
|
} else {
|
||||||
// If we do not have a map address in the URL, let's ask the server for a start map.
|
// If we do not have a map address in the URL, let's ask the server for a start map.
|
||||||
return gameManager.loadStartMap().then((scene : any) => {
|
return gameManager.loadStartMap().then((startMap: StartMapInterface) => {
|
||||||
if (!scene) {
|
const key = gameManager.loadMap(window.location.protocol + "//" + startMap.mapUrlStart, this.scene, startMap.startInstance);
|
||||||
return;
|
|
||||||
}
|
|
||||||
let key = gameManager.loadMap(window.location.protocol + "//" + scene.mapUrlStart, this.scene, scene.startInstance);
|
|
||||||
this.scene.start(key);
|
this.scene.start(key);
|
||||||
return scene;
|
return startMap;
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
throw err;
|
throw err;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}).catch((err) => {
|
|
||||||
console.error(err);
|
|
||||||
throw err;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the map URL and the instance from the current URL
|
* Returns the map URL and the instance from the current URL
|
||||||
*/
|
*/
|
||||||
private findMapUrl(): [string, string]|null {
|
private findMapUrl(): [string, string]|null {
|
||||||
let path = window.location.pathname;
|
const path = window.location.pathname;
|
||||||
if (!path.startsWith('/_/')) {
|
if (!path.startsWith('/_/')) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
let instanceAndMap = path.substr(3);
|
const instanceAndMap = path.substr(3);
|
||||||
let firstSlash = instanceAndMap.indexOf('/');
|
const firstSlash = instanceAndMap.indexOf('/');
|
||||||
if (firstSlash === -1) {
|
if (firstSlash === -1) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
let instance = instanceAndMap.substr(0, firstSlash);
|
const instance = instanceAndMap.substr(0, firstSlash);
|
||||||
return [window.location.protocol+'//'+instanceAndMap.substr(firstSlash+1), instance];
|
return [window.location.protocol+'//'+instanceAndMap.substr(firstSlash+1), instance];
|
||||||
}
|
}
|
||||||
|
|
||||||
createCurrentPlayer(): void {
|
createCurrentPlayer(): void {
|
||||||
for (let i = 0; i <PLAYER_RESOURCES.length; i++) {
|
for (let i = 0; i <PLAYER_RESOURCES.length; i++) {
|
||||||
let playerResource = PLAYER_RESOURCES[i];
|
const playerResource = PLAYER_RESOURCES[i];
|
||||||
|
|
||||||
let col = i % this.nbCharactersPerRow;
|
const col = i % this.nbCharactersPerRow;
|
||||||
let row = Math.floor(i / this.nbCharactersPerRow);
|
const row = Math.floor(i / this.nbCharactersPerRow);
|
||||||
|
|
||||||
let [x, y] = this.getCharacterPosition(col, row);
|
const [x, y] = this.getCharacterPosition(col, row);
|
||||||
let player = this.physics.add.sprite(x, y, playerResource.name, 0);
|
const player = this.physics.add.sprite(x, y, playerResource.name, 0);
|
||||||
player.setBounce(0.2);
|
player.setBounce(0.2);
|
||||||
player.setCollideWorldBounds(true);
|
player.setCollideWorldBounds(true);
|
||||||
this.anims.create({
|
this.anims.create({
|
||||||
@ -203,11 +201,11 @@ export class SelectCharacterScene extends Phaser.Scene {
|
|||||||
|
|
||||||
private updateSelectedPlayer(): void {
|
private updateSelectedPlayer(): void {
|
||||||
this.selectedPlayer.anims.pause();
|
this.selectedPlayer.anims.pause();
|
||||||
let [x, y] = this.getCharacterPosition(this.selectedRectangleXPos, this.selectedRectangleYPos);
|
const [x, y] = this.getCharacterPosition(this.selectedRectangleXPos, this.selectedRectangleYPos);
|
||||||
this.selectedRectangle.setX(x);
|
this.selectedRectangle.setX(x);
|
||||||
this.selectedRectangle.setY(y);
|
this.selectedRectangle.setY(y);
|
||||||
let playerNumber = this.selectedRectangleXPos + this.selectedRectangleYPos * this.nbCharactersPerRow;
|
const playerNumber = this.selectedRectangleXPos + this.selectedRectangleYPos * this.nbCharactersPerRow;
|
||||||
let player = this.players[playerNumber];
|
const player = this.players[playerNumber];
|
||||||
player.play(PLAYER_RESOURCES[playerNumber].name);
|
player.play(PLAYER_RESOURCES[playerNumber].name);
|
||||||
this.selectedPlayer = player;
|
this.selectedPlayer = player;
|
||||||
if (window.localStorage) {
|
if (window.localStorage) {
|
||||||
|
@ -26,12 +26,24 @@ export interface ITiledMap {
|
|||||||
version: number;
|
version: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ITiledMapLayerProperty {
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
value: string|boolean|number|undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*export interface ITiledMapLayerBooleanProperty {
|
||||||
|
name: string,
|
||||||
|
type: 'bool',
|
||||||
|
value: boolean
|
||||||
|
}*/
|
||||||
|
|
||||||
export interface ITiledMapLayer {
|
export interface ITiledMapLayer {
|
||||||
data: number[]|string;
|
data: number[]|string;
|
||||||
height: number;
|
height: number;
|
||||||
name: string;
|
name: string;
|
||||||
opacity: number;
|
opacity: number;
|
||||||
properties: {[key: string]: string};
|
properties: ITiledMapLayerProperty[];
|
||||||
encoding: string;
|
encoding: string;
|
||||||
compression?: string;
|
compression?: string;
|
||||||
|
|
||||||
|
@ -39,9 +39,9 @@ export class Player extends Character implements CurrentGamerInterface {
|
|||||||
let direction = null;
|
let direction = null;
|
||||||
let moving = false;
|
let moving = false;
|
||||||
|
|
||||||
let activeEvents = this.userInputManager.getEventListForGameTick();
|
const activeEvents = this.userInputManager.getEventListForGameTick();
|
||||||
let speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9;
|
const speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9;
|
||||||
let moveAmount = speedMultiplier * 20;
|
const moveAmount = speedMultiplier * 20;
|
||||||
|
|
||||||
let x = 0;
|
let x = 0;
|
||||||
let y = 0;
|
let y = 0;
|
||||||
|
@ -1,11 +1,5 @@
|
|||||||
import {gameManager} from "../Game/GameManager";
|
|
||||||
import {TextField} from "../Components/TextField";
|
import {TextField} from "../Components/TextField";
|
||||||
import {TextInput} from "../Components/TextInput";
|
|
||||||
import {ClickButton} from "../Components/ClickButton";
|
|
||||||
import Image = Phaser.GameObjects.Image;
|
import Image = Phaser.GameObjects.Image;
|
||||||
import Rectangle = Phaser.GameObjects.Rectangle;
|
|
||||||
import {PLAYER_RESOURCES} from "../Entity/Character";
|
|
||||||
import {cypressAsserter} from "../../Cypress/CypressAsserter";
|
|
||||||
import Sprite = Phaser.GameObjects.Sprite;
|
import Sprite = Phaser.GameObjects.Sprite;
|
||||||
|
|
||||||
export const ReconnectingSceneName = "ReconnectingScene";
|
export const ReconnectingSceneName = "ReconnectingScene";
|
||||||
@ -43,7 +37,7 @@ export class ReconnectingScene extends Phaser.Scene {
|
|||||||
this.reconnectingField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2, "Connection lost. Reconnecting...");
|
this.reconnectingField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2, "Connection lost. Reconnecting...");
|
||||||
this.reconnectingField.setOrigin(0.5, 0.5).setCenterAlign();
|
this.reconnectingField.setOrigin(0.5, 0.5).setCenterAlign();
|
||||||
|
|
||||||
let cat = this.physics.add.sprite(this.game.renderer.width / 2, this.game.renderer.height / 2 - 32, 'cat');
|
const cat = this.physics.add.sprite(this.game.renderer.width / 2, this.game.renderer.height / 2 - 32, 'cat');
|
||||||
this.anims.create({
|
this.anims.create({
|
||||||
key: 'right',
|
key: 'right',
|
||||||
frames: this.anims.generateFrameNumbers('cat', { start: 6, end: 8 }),
|
frames: this.anims.generateFrameNumbers('cat', { start: 6, end: 8 }),
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import Map = Phaser.Structs.Map;
|
|
||||||
import {GameScene} from "../Game/GameScene";
|
import {GameScene} from "../Game/GameScene";
|
||||||
|
|
||||||
interface UserInputManagerDatum {
|
interface UserInputManagerDatum {
|
||||||
@ -18,15 +17,13 @@ export enum UserInputEvent {
|
|||||||
|
|
||||||
//we cannot the map structure so we have to create a replacment
|
//we cannot the map structure so we have to create a replacment
|
||||||
export class ActiveEventList {
|
export class ActiveEventList {
|
||||||
private KeysCode : any;
|
private KeysCode : Map<UserInputEvent, boolean> = new Map<UserInputEvent, boolean>();
|
||||||
constructor() {
|
|
||||||
this.KeysCode = {};
|
|
||||||
}
|
|
||||||
get(event: UserInputEvent): boolean {
|
get(event: UserInputEvent): boolean {
|
||||||
return this.KeysCode[event] || false;
|
return this.KeysCode.get(event) || false;
|
||||||
}
|
}
|
||||||
set(event: UserInputEvent, value: boolean): boolean {
|
set(event: UserInputEvent, value: boolean): void {
|
||||||
return this.KeysCode[event] = true;
|
this.KeysCode.set(event, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,7 +52,7 @@ export class UserInputManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getEventListForGameTick(): ActiveEventList {
|
getEventListForGameTick(): ActiveEventList {
|
||||||
let eventsMap = new ActiveEventList();
|
const eventsMap = new ActiveEventList();
|
||||||
this.KeysCode.forEach(d => {
|
this.KeysCode.forEach(d => {
|
||||||
if (d. keyInstance.isDown) {
|
if (d. keyInstance.isDown) {
|
||||||
eventsMap.set(d.event, true);
|
eventsMap.set(d.event, true);
|
||||||
|
@ -1,53 +1,53 @@
|
|||||||
const videoConstraint: {width : any, height: any, facingMode : string} = {
|
const videoConstraint: boolean|MediaTrackConstraints = {
|
||||||
width: { ideal: 1280 },
|
width: { ideal: 1280 },
|
||||||
height: { ideal: 720 },
|
height: { ideal: 720 },
|
||||||
facingMode: "user"
|
facingMode: "user"
|
||||||
};
|
};
|
||||||
export class MediaManager {
|
export class MediaManager {
|
||||||
localStream: MediaStream|null = null;
|
localStream: MediaStream|null = null;
|
||||||
remoteVideo: Array<any> = new Array<any>();
|
private remoteVideo: Map<string, HTMLVideoElement> = new Map<string, HTMLVideoElement>();
|
||||||
myCamVideo: HTMLVideoElement;
|
myCamVideo: HTMLVideoElement;
|
||||||
cinemaClose: any = null;
|
cinemaClose: HTMLImageElement;
|
||||||
cinema: any = null;
|
cinema: HTMLImageElement;
|
||||||
microphoneClose: any = null;
|
microphoneClose: HTMLImageElement;
|
||||||
microphone: any = null;
|
microphone: HTMLImageElement;
|
||||||
webrtcInAudio: HTMLAudioElement;
|
webrtcInAudio: HTMLAudioElement;
|
||||||
constraintsMedia : {audio : any, video : any} = {
|
constraintsMedia : MediaStreamConstraints = {
|
||||||
audio: true,
|
audio: true,
|
||||||
video: videoConstraint
|
video: videoConstraint
|
||||||
};
|
};
|
||||||
updatedLocalStreamCallBack : Function;
|
updatedLocalStreamCallBack : (media: MediaStream) => void;
|
||||||
|
|
||||||
constructor(updatedLocalStreamCallBack : Function) {
|
constructor(updatedLocalStreamCallBack : (media: MediaStream) => void) {
|
||||||
this.updatedLocalStreamCallBack = updatedLocalStreamCallBack;
|
this.updatedLocalStreamCallBack = updatedLocalStreamCallBack;
|
||||||
|
|
||||||
this.myCamVideo = this.getElementByIdOrFail<HTMLVideoElement>('myCamVideo');
|
this.myCamVideo = this.getElementByIdOrFail<HTMLVideoElement>('myCamVideo');
|
||||||
this.webrtcInAudio = this.getElementByIdOrFail<HTMLAudioElement>('audio-webrtc-in');
|
this.webrtcInAudio = this.getElementByIdOrFail<HTMLAudioElement>('audio-webrtc-in');
|
||||||
this.webrtcInAudio.volume = 0.2;
|
this.webrtcInAudio.volume = 0.2;
|
||||||
|
|
||||||
this.microphoneClose = document.getElementById('microphone-close');
|
this.microphoneClose = this.getElementByIdOrFail<HTMLImageElement>('microphone-close');
|
||||||
this.microphoneClose.style.display = "none";
|
this.microphoneClose.style.display = "none";
|
||||||
this.microphoneClose.addEventListener('click', (e: any) => {
|
this.microphoneClose.addEventListener('click', (e: MouseEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.enabledMicrophone();
|
this.enabledMicrophone();
|
||||||
//update tracking
|
//update tracking
|
||||||
});
|
});
|
||||||
this.microphone = document.getElementById('microphone');
|
this.microphone = this.getElementByIdOrFail<HTMLImageElement>('microphone');
|
||||||
this.microphone.addEventListener('click', (e: any) => {
|
this.microphone.addEventListener('click', (e: MouseEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.disabledMicrophone();
|
this.disabledMicrophone();
|
||||||
//update tracking
|
//update tracking
|
||||||
});
|
});
|
||||||
|
|
||||||
this.cinemaClose = document.getElementById('cinema-close');
|
this.cinemaClose = this.getElementByIdOrFail<HTMLImageElement>('cinema-close');
|
||||||
this.cinemaClose.style.display = "none";
|
this.cinemaClose.style.display = "none";
|
||||||
this.cinemaClose.addEventListener('click', (e: any) => {
|
this.cinemaClose.addEventListener('click', (e: MouseEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.enabledCamera();
|
this.enabledCamera();
|
||||||
//update tracking
|
//update tracking
|
||||||
});
|
});
|
||||||
this.cinema = document.getElementById('cinema');
|
this.cinema = this.getElementByIdOrFail<HTMLImageElement>('cinema');
|
||||||
this.cinema.addEventListener('click', (e: any) => {
|
this.cinema.addEventListener('click', (e: MouseEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.disabledCamera();
|
this.disabledCamera();
|
||||||
//update tracking
|
//update tracking
|
||||||
@ -55,7 +55,7 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
activeVisio(){
|
activeVisio(){
|
||||||
let webRtc = this.getElementByIdOrFail('webRtc');
|
const webRtc = this.getElementByIdOrFail('webRtc');
|
||||||
webRtc.classList.add('active');
|
webRtc.classList.add('active');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,7 +63,7 @@ export class MediaManager {
|
|||||||
this.cinemaClose.style.display = "none";
|
this.cinemaClose.style.display = "none";
|
||||||
this.cinema.style.display = "block";
|
this.cinema.style.display = "block";
|
||||||
this.constraintsMedia.video = videoConstraint;
|
this.constraintsMedia.video = videoConstraint;
|
||||||
this.getCamera().then((stream) => {
|
this.getCamera().then((stream: MediaStream) => {
|
||||||
this.updatedLocalStreamCallBack(stream);
|
this.updatedLocalStreamCallBack(stream);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -107,8 +107,13 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//get camera
|
//get camera
|
||||||
getCamera() {
|
getCamera(): Promise<MediaStream> {
|
||||||
let promise = null;
|
let promise = null;
|
||||||
|
|
||||||
|
if (navigator.mediaDevices === undefined) {
|
||||||
|
return Promise.reject<MediaStream>(new Error('Unable to access your camera or microphone. Your browser is too old (or you are running a development version of WorkAdventure on Firefox)'));
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
promise = navigator.mediaDevices.getUserMedia(this.constraintsMedia)
|
promise = navigator.mediaDevices.getUserMedia(this.constraintsMedia)
|
||||||
.then((stream: MediaStream) => {
|
.then((stream: MediaStream) => {
|
||||||
@ -123,11 +128,12 @@ export class MediaManager {
|
|||||||
|
|
||||||
return stream;
|
return stream;
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
console.info(`error get media {video: ${this.constraintsMedia.video}},{audio: ${this.constraintsMedia.audio}}`,err);
|
console.info("error get media ", this.constraintsMedia.video, this.constraintsMedia.audio, err);
|
||||||
this.localStream = null;
|
this.localStream = null;
|
||||||
|
throw err;
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
promise = Promise.reject(false);
|
promise = Promise.reject<MediaStream>(e);
|
||||||
}
|
}
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
@ -138,9 +144,9 @@ export class MediaManager {
|
|||||||
*/
|
*/
|
||||||
addActiveVideo(userId : string, userName: string = ""){
|
addActiveVideo(userId : string, userName: string = ""){
|
||||||
this.webrtcInAudio.play();
|
this.webrtcInAudio.play();
|
||||||
let elementRemoteVideo = this.getElementByIdOrFail("activeCam");
|
const elementRemoteVideo = this.getElementByIdOrFail("activeCam");
|
||||||
userName = userName.toUpperCase();
|
userName = userName.toUpperCase();
|
||||||
let color = this.getColorByString(userName);
|
const color = this.getColorByString(userName);
|
||||||
elementRemoteVideo.insertAdjacentHTML('beforeend', `
|
elementRemoteVideo.insertAdjacentHTML('beforeend', `
|
||||||
<div id="div-${userId}" class="video-container" style="border-color: ${color};">
|
<div id="div-${userId}" class="video-container" style="border-color: ${color};">
|
||||||
<div class="connecting-spinner"></div>
|
<div class="connecting-spinner"></div>
|
||||||
@ -150,7 +156,7 @@ export class MediaManager {
|
|||||||
<video id="${userId}" autoplay></video>
|
<video id="${userId}" autoplay></video>
|
||||||
</div>
|
</div>
|
||||||
`);
|
`);
|
||||||
this.remoteVideo[(userId as any)] = document.getElementById(userId);
|
this.remoteVideo.set(userId, this.getElementByIdOrFail<HTMLVideoElement>(userId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -158,7 +164,7 @@ export class MediaManager {
|
|||||||
* @param userId
|
* @param userId
|
||||||
*/
|
*/
|
||||||
disabledMicrophoneByUserId(userId: string){
|
disabledMicrophoneByUserId(userId: string){
|
||||||
let element = document.getElementById(`microphone-${userId}`);
|
const element = document.getElementById(`microphone-${userId}`);
|
||||||
if(!element){
|
if(!element){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -170,7 +176,7 @@ export class MediaManager {
|
|||||||
* @param userId
|
* @param userId
|
||||||
*/
|
*/
|
||||||
enabledMicrophoneByUserId(userId: string){
|
enabledMicrophoneByUserId(userId: string){
|
||||||
let element = document.getElementById(`microphone-${userId}`);
|
const element = document.getElementById(`microphone-${userId}`);
|
||||||
if(!element){
|
if(!element){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -215,7 +221,12 @@ export class MediaManager {
|
|||||||
* @param stream
|
* @param stream
|
||||||
*/
|
*/
|
||||||
addStreamRemoteVideo(userId : string, stream : MediaStream){
|
addStreamRemoteVideo(userId : string, stream : MediaStream){
|
||||||
this.remoteVideo[(userId as any)].srcObject = stream;
|
const remoteVideo = this.remoteVideo.get(userId);
|
||||||
|
if (remoteVideo === undefined) {
|
||||||
|
console.error('Unable to find video for ', userId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remoteVideo.srcObject = stream;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -223,15 +234,16 @@ export class MediaManager {
|
|||||||
* @param userId
|
* @param userId
|
||||||
*/
|
*/
|
||||||
removeActiveVideo(userId : string){
|
removeActiveVideo(userId : string){
|
||||||
let element = document.getElementById(`div-${userId}`);
|
const element = document.getElementById(`div-${userId}`);
|
||||||
if(!element){
|
if(!element){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
element.remove();
|
element.remove();
|
||||||
|
this.remoteVideo.delete(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
isConnecting(userId : string): void {
|
isConnecting(userId : string): void {
|
||||||
let connectingSpinnerDiv = this.getSpinner(userId);
|
const connectingSpinnerDiv = this.getSpinner(userId);
|
||||||
if (connectingSpinnerDiv === null) {
|
if (connectingSpinnerDiv === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -239,7 +251,7 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isConnected(userId : string): void {
|
isConnected(userId : string): void {
|
||||||
let connectingSpinnerDiv = this.getSpinner(userId);
|
const connectingSpinnerDiv = this.getSpinner(userId);
|
||||||
if (connectingSpinnerDiv === null) {
|
if (connectingSpinnerDiv === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -247,11 +259,11 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isError(userId : string): void {
|
isError(userId : string): void {
|
||||||
let element = document.getElementById(`div-${userId}`);
|
const element = document.getElementById(`div-${userId}`);
|
||||||
if(!element){
|
if(!element){
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let errorDiv = element.getElementsByClassName('rtc-error').item(0) as HTMLDivElement|null;
|
const errorDiv = element.getElementsByClassName('rtc-error').item(0) as HTMLDivElement|null;
|
||||||
if (errorDiv === null) {
|
if (errorDiv === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -259,11 +271,11 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private getSpinner(userId : string): HTMLDivElement|null {
|
private getSpinner(userId : string): HTMLDivElement|null {
|
||||||
let element = document.getElementById(`div-${userId}`);
|
const element = document.getElementById(`div-${userId}`);
|
||||||
if(!element){
|
if(!element){
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
let connnectingSpinnerDiv = element.getElementsByClassName('connecting-spinner').item(0) as HTMLDivElement|null;
|
const connnectingSpinnerDiv = element.getElementsByClassName('connecting-spinner').item(0) as HTMLDivElement|null;
|
||||||
return connnectingSpinnerDiv;
|
return connnectingSpinnerDiv;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -280,14 +292,14 @@ export class MediaManager {
|
|||||||
}
|
}
|
||||||
let color = '#';
|
let color = '#';
|
||||||
for (let i = 0; i < 3; i++) {
|
for (let i = 0; i < 3; i++) {
|
||||||
let value = (hash >> (i * 8)) & 255;
|
const value = (hash >> (i * 8)) & 255;
|
||||||
color += ('00' + value.toString(16)).substr(-2);
|
color += ('00' + value.toString(16)).substr(-2);
|
||||||
}
|
}
|
||||||
return color;
|
return color;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getElementByIdOrFail<T extends HTMLElement>(id: string): T {
|
private getElementByIdOrFail<T extends HTMLElement>(id: string): T {
|
||||||
let elem = document.getElementById(id);
|
const elem = document.getElementById(id);
|
||||||
if (elem === null) {
|
if (elem === null) {
|
||||||
throw new Error("Cannot find HTML element with id '"+id+"'");
|
throw new Error("Cannot find HTML element with id '"+id+"'");
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,12 @@
|
|||||||
import {ConnectionInterface, WebRtcDisconnectMessageInterface, WebRtcStartMessageInterface} from "../Connection";
|
import {
|
||||||
|
Connection,
|
||||||
|
WebRtcDisconnectMessageInterface,
|
||||||
|
WebRtcSignalMessageInterface,
|
||||||
|
WebRtcStartMessageInterface
|
||||||
|
} from "../Connection";
|
||||||
import {MediaManager} from "./MediaManager";
|
import {MediaManager} from "./MediaManager";
|
||||||
import * as SimplePeerNamespace from "simple-peer";
|
import * as SimplePeerNamespace from "simple-peer";
|
||||||
let Peer: SimplePeerNamespace.SimplePeer = require('simple-peer');
|
const Peer: SimplePeerNamespace.SimplePeer = require('simple-peer');
|
||||||
|
|
||||||
export interface UserSimplePeer{
|
export interface UserSimplePeer{
|
||||||
userId: string;
|
userId: string;
|
||||||
@ -13,7 +18,7 @@ export interface UserSimplePeer{
|
|||||||
* This class manages connections to all the peers in the same group as me.
|
* This class manages connections to all the peers in the same group as me.
|
||||||
*/
|
*/
|
||||||
export class SimplePeer {
|
export class SimplePeer {
|
||||||
private Connection: ConnectionInterface;
|
private Connection: Connection;
|
||||||
private WebRtcRoomId: string;
|
private WebRtcRoomId: string;
|
||||||
private Users: Array<UserSimplePeer> = new Array<UserSimplePeer>();
|
private Users: Array<UserSimplePeer> = new Array<UserSimplePeer>();
|
||||||
|
|
||||||
@ -21,7 +26,7 @@ export class SimplePeer {
|
|||||||
|
|
||||||
private PeerConnectionArray: Map<string, SimplePeerNamespace.Instance> = new Map<string, SimplePeerNamespace.Instance>();
|
private PeerConnectionArray: Map<string, SimplePeerNamespace.Instance> = new Map<string, SimplePeerNamespace.Instance>();
|
||||||
|
|
||||||
constructor(Connection: ConnectionInterface, WebRtcRoomId: string = "test-webrtc") {
|
constructor(Connection: Connection, WebRtcRoomId: string = "test-webrtc") {
|
||||||
this.Connection = Connection;
|
this.Connection = Connection;
|
||||||
this.WebRtcRoomId = WebRtcRoomId;
|
this.WebRtcRoomId = WebRtcRoomId;
|
||||||
this.MediaManager = new MediaManager((stream : MediaStream) => {
|
this.MediaManager = new MediaManager((stream : MediaStream) => {
|
||||||
@ -36,7 +41,7 @@ export class SimplePeer {
|
|||||||
private initialise() {
|
private initialise() {
|
||||||
|
|
||||||
//receive signal by gemer
|
//receive signal by gemer
|
||||||
this.Connection.receiveWebrtcSignal((message: any) => {
|
this.Connection.receiveWebrtcSignal((message: WebRtcSignalMessageInterface) => {
|
||||||
this.receiveWebrtcSignal(message);
|
this.receiveWebrtcSignal(message);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -95,7 +100,7 @@ export class SimplePeer {
|
|||||||
|
|
||||||
let name = user.name;
|
let name = user.name;
|
||||||
if(!name){
|
if(!name){
|
||||||
let userSearch = this.Users.find((userSearch: UserSimplePeer) => userSearch.userId === user.userId);
|
const userSearch = this.Users.find((userSearch: UserSimplePeer) => userSearch.userId === user.userId);
|
||||||
if(userSearch) {
|
if(userSearch) {
|
||||||
name = userSearch.name;
|
name = userSearch.name;
|
||||||
}
|
}
|
||||||
@ -103,7 +108,7 @@ export class SimplePeer {
|
|||||||
this.MediaManager.removeActiveVideo(user.userId);
|
this.MediaManager.removeActiveVideo(user.userId);
|
||||||
this.MediaManager.addActiveVideo(user.userId, name);
|
this.MediaManager.addActiveVideo(user.userId, name);
|
||||||
|
|
||||||
let peer : SimplePeerNamespace.Instance = new Peer({
|
const peer : SimplePeerNamespace.Instance = new Peer({
|
||||||
initiator: user.initiator ? user.initiator : false,
|
initiator: user.initiator ? user.initiator : false,
|
||||||
reconnectTimer: 10000,
|
reconnectTimer: 10000,
|
||||||
config: {
|
config: {
|
||||||
@ -122,7 +127,7 @@ export class SimplePeer {
|
|||||||
this.PeerConnectionArray.set(user.userId, peer);
|
this.PeerConnectionArray.set(user.userId, peer);
|
||||||
|
|
||||||
//start listen signal for the peer connection
|
//start listen signal for the peer connection
|
||||||
peer.on('signal', (data: any) => {
|
peer.on('signal', (data: unknown) => {
|
||||||
this.sendWebrtcSignal(data, user.userId);
|
this.sendWebrtcSignal(data, user.userId);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -159,6 +164,7 @@ export class SimplePeer {
|
|||||||
this.closeConnection(user.userId);
|
this.closeConnection(user.userId);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
peer.on('error', (err: any) => {
|
peer.on('error', (err: any) => {
|
||||||
console.error(`error => ${user.userId} => ${err.code}`, err);
|
console.error(`error => ${user.userId} => ${err.code}`, err);
|
||||||
this.MediaManager.isError(user.userId);
|
this.MediaManager.isError(user.userId);
|
||||||
@ -170,7 +176,7 @@ export class SimplePeer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
peer.on('data', (chunk: Buffer) => {
|
peer.on('data', (chunk: Buffer) => {
|
||||||
let data = JSON.parse(chunk.toString('utf8'));
|
const data = JSON.parse(chunk.toString('utf8'));
|
||||||
if(data.type === "stream"){
|
if(data.type === "stream"){
|
||||||
this.stream(user.userId, data.stream);
|
this.stream(user.userId, data.stream);
|
||||||
}
|
}
|
||||||
@ -187,7 +193,7 @@ export class SimplePeer {
|
|||||||
private closeConnection(userId : string) {
|
private closeConnection(userId : string) {
|
||||||
try {
|
try {
|
||||||
this.MediaManager.removeActiveVideo(userId);
|
this.MediaManager.removeActiveVideo(userId);
|
||||||
let peer = this.PeerConnectionArray.get(userId);
|
const peer = this.PeerConnectionArray.get(userId);
|
||||||
if (peer === undefined) {
|
if (peer === undefined) {
|
||||||
console.warn("Tried to close connection for user "+userId+" but could not find user")
|
console.warn("Tried to close connection for user "+userId+" but could not find user")
|
||||||
return;
|
return;
|
||||||
@ -203,12 +209,18 @@ export class SimplePeer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public closeAllConnections() {
|
||||||
|
for (const userId of this.PeerConnectionArray.keys()) {
|
||||||
|
this.closeConnection(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param userId
|
* @param userId
|
||||||
* @param data
|
* @param data
|
||||||
*/
|
*/
|
||||||
private sendWebrtcSignal(data: any, userId : string) {
|
private sendWebrtcSignal(data: unknown, userId : string) {
|
||||||
try {
|
try {
|
||||||
this.Connection.sendWebrtcSignal(data, this.WebRtcRoomId, null, userId);
|
this.Connection.sendWebrtcSignal(data, this.WebRtcRoomId, null, userId);
|
||||||
}catch (e) {
|
}catch (e) {
|
||||||
@ -216,13 +228,14 @@ export class SimplePeer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private receiveWebrtcSignal(data: any) {
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
private receiveWebrtcSignal(data: WebRtcSignalMessageInterface) {
|
||||||
try {
|
try {
|
||||||
//if offer type, create peer connection
|
//if offer type, create peer connection
|
||||||
if(data.signal.type === "offer"){
|
if(data.signal.type === "offer"){
|
||||||
this.createPeerConnection(data);
|
this.createPeerConnection(data);
|
||||||
}
|
}
|
||||||
let peer = this.PeerConnectionArray.get(data.userId);
|
const peer = this.PeerConnectionArray.get(data.userId);
|
||||||
if (peer !== undefined) {
|
if (peer !== undefined) {
|
||||||
peer.signal(data.signal);
|
peer.signal(data.signal);
|
||||||
} else {
|
} else {
|
||||||
@ -251,10 +264,10 @@ export class SimplePeer {
|
|||||||
*
|
*
|
||||||
* @param userId
|
* @param userId
|
||||||
*/
|
*/
|
||||||
private addMedia (userId : any = null) {
|
private addMedia (userId : string) {
|
||||||
try {
|
try {
|
||||||
let localStream: MediaStream|null = this.MediaManager.localStream;
|
const localStream: MediaStream|null = this.MediaManager.localStream;
|
||||||
let peer = this.PeerConnectionArray.get(userId);
|
const peer = this.PeerConnectionArray.get(userId);
|
||||||
if(localStream === null) {
|
if(localStream === null) {
|
||||||
//send fake signal
|
//send fake signal
|
||||||
if(peer === undefined){
|
if(peer === undefined){
|
||||||
|
@ -24,7 +24,7 @@ const config: GameConfig = {
|
|||||||
|
|
||||||
cypressAsserter.gameStarted();
|
cypressAsserter.gameStarted();
|
||||||
|
|
||||||
let game = new Phaser.Game(config);
|
const game = new Phaser.Game(config);
|
||||||
|
|
||||||
window.addEventListener('resize', function (event) {
|
window.addEventListener('resize', function (event) {
|
||||||
game.scale.resize(window.innerWidth / RESOLUTION, window.innerHeight / RESOLUTION);
|
game.scale.resize(window.innerWidth / RESOLUTION, window.innerHeight / RESOLUTION);
|
||||||
|
@ -3,7 +3,7 @@ import {PlayerMovement} from "../../../src/Phaser/Game/PlayerMovement";
|
|||||||
|
|
||||||
describe("Interpolation / Extrapolation", () => {
|
describe("Interpolation / Extrapolation", () => {
|
||||||
it("should interpolate", () => {
|
it("should interpolate", () => {
|
||||||
let playerMovement = new PlayerMovement({
|
const playerMovement = new PlayerMovement({
|
||||||
x: 100, y: 200
|
x: 100, y: 200
|
||||||
}, 42000,
|
}, 42000,
|
||||||
{
|
{
|
||||||
@ -39,7 +39,7 @@ describe("Interpolation / Extrapolation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should not extrapolate if we stop", () => {
|
it("should not extrapolate if we stop", () => {
|
||||||
let playerMovement = new PlayerMovement({
|
const playerMovement = new PlayerMovement({
|
||||||
x: 100, y: 200
|
x: 100, y: 200
|
||||||
}, 42000,
|
}, 42000,
|
||||||
{
|
{
|
||||||
@ -57,7 +57,7 @@ describe("Interpolation / Extrapolation", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should should keep moving until it stops", () => {
|
it("should should keep moving until it stops", () => {
|
||||||
let playerMovement = new PlayerMovement({
|
const playerMovement = new PlayerMovement({
|
||||||
x: 100, y: 200
|
x: 100, y: 200
|
||||||
}, 42000,
|
}, 42000,
|
||||||
{
|
{
|
||||||
|
@ -6,6 +6,7 @@
|
|||||||
"noImplicitAny": true,
|
"noImplicitAny": true,
|
||||||
"module": "CommonJS",
|
"module": "CommonJS",
|
||||||
"target": "es5",
|
"target": "es5",
|
||||||
|
"downlevelIteration": true,
|
||||||
"jsx": "react",
|
"jsx": "react",
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
|
|
||||||
|
@ -2602,6 +2602,11 @@ levn@^0.3.0, levn@~0.3.0:
|
|||||||
prelude-ls "~1.1.2"
|
prelude-ls "~1.1.2"
|
||||||
type-check "~0.3.2"
|
type-check "~0.3.2"
|
||||||
|
|
||||||
|
linked-list-typescript@^1.0.11:
|
||||||
|
version "1.0.15"
|
||||||
|
resolved "https://registry.yarnpkg.com/linked-list-typescript/-/linked-list-typescript-1.0.15.tgz#faeed93cf9203f102e2158c29edcddda320abe82"
|
||||||
|
integrity sha512-RIyUu9lnJIyIaMe63O7/aFv/T2v3KsMFuXMBbUQCHX+cgtGro86ETDj5ed0a8gQL2+DFjzYYsgVG4I36/cUwgw==
|
||||||
|
|
||||||
loader-runner@^2.4.0:
|
loader-runner@^2.4.0:
|
||||||
version "2.4.0"
|
version "2.4.0"
|
||||||
resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-2.4.0.tgz#ed47066bfe534d7e84c4c7b9998c2a75607d9357"
|
resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-2.4.0.tgz#ed47066bfe534d7e84c4c7b9998c2a75607d9357"
|
||||||
@ -3400,6 +3405,13 @@ queue-microtask@^1.1.0:
|
|||||||
resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.1.2.tgz#139bf8186db0c545017ec66c2664ac646d5c571e"
|
resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.1.2.tgz#139bf8186db0c545017ec66c2664ac646d5c571e"
|
||||||
integrity sha512-F9wwNePtXrzZenAB3ax0Y8TSKGvuB7Qw16J30hspEUTbfUM+H827XyN3rlpwhVmtm5wuZtbKIHjOnwDn7MUxWQ==
|
integrity sha512-F9wwNePtXrzZenAB3ax0Y8TSKGvuB7Qw16J30hspEUTbfUM+H827XyN3rlpwhVmtm5wuZtbKIHjOnwDn7MUxWQ==
|
||||||
|
|
||||||
|
queue-typescript@^1.0.1:
|
||||||
|
version "1.0.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/queue-typescript/-/queue-typescript-1.0.1.tgz#2d7842fc3b3e0e3f33d077887a8f2a5bb0baf460"
|
||||||
|
integrity sha512-tkK08uPfmpPl0cX1WRSU3EoNb/T5zSoZPGkkpfGX4E8QayWvEmLS2cI3pFngNPkNTCU5pCDQ1IwlzN0L5gdFPg==
|
||||||
|
dependencies:
|
||||||
|
linked-list-typescript "^1.0.11"
|
||||||
|
|
||||||
randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.3, randombytes@^2.0.5:
|
randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.3, randombytes@^2.0.5:
|
||||||
version "2.1.0"
|
version "2.1.0"
|
||||||
resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"
|
resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"
|
||||||
|
Loading…
Reference in New Issue
Block a user