/
ClientProxy.ts
85 lines (68 loc) · 2.22 KB
/
ClientProxy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import * as PubSubJS from 'pubsub-js';
import GameWorld from './game/GameWorld';
import Lobby from './game/Lobby';
import PlayerAccount from './PlayerAccount';
import Database from './Database';
const now = require("performance-now");
export default class ClientProxy {
public playerAccount: PlayerAccount;
private _userUUID: string;
private _gameWorld: GameWorld;
private _userToken: any;
private _spawnTime: number;
private _startGameTime: number;
private _startGameTimeOffset: number;
constructor(userUUID: string) {
this._userUUID = userUUID;
this.playerAccount = Database.getPlayerWithUUID(this._userUUID);
this._userToken = PubSubJS.subscribe(`${this._userUUID}.in`, this.userSubscriberIn.bind(this));
this._spawnTime = now();
this._startGameTime = now();
this._startGameTimeOffset = 0;
}
get userUUID(): string {
return this._userUUID;
}
publish(data: any, subtopic: string = 'out'): void {
let topic: string = this._userUUID;
if (subtopic) {
topic = `${topic}.${subtopic}`;
}
console.log(`ClientProxy publishing to: ${topic}`);
PubSubJS.publish(topic, data);
}
userSubscriberIn(msg: any, data: any): void {
console.log(`ClientProxy: userSubscriberIn: ${this._userUUID}: `);
this.sendMessageToGameWorld(data);
}
restartGameTime(): void {
this._startGameTime = now();
}
set gameWorld(gameWorld: GameWorld) {
this._gameWorld = gameWorld;
}
get aliveTime(): number {
return now() - this._spawnTime;
}
get gameTime(): number {
return now() - this._startGameTime + this._startGameTimeOffset;
}
set startGameTimeOffset(time: number) {
this._startGameTimeOffset = time;
}
sendMessageToGameWorld(data: any): void {
this._gameWorld.receiveMessageFromClient(data, this);
}
get shortId(): string {
let shortId: string = 'NA';
if (this._userUUID) {
shortId = this._userUUID.substring(0,8);
}
return shortId;
}
dispose(): void {
this.playerAccount = undefined;
this._gameWorld = undefined;
PubSubJS.unsubscribe(this._userToken);
}
}