-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathlobby.ts
More file actions
78 lines (63 loc) · 2.2 KB
/
lobby.ts
File metadata and controls
78 lines (63 loc) · 2.2 KB
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
import { v4 } from 'uuid';
import { Server, Socket } from 'socket.io';
import { ServerEvents } from '@shared/server/ServerEvents';
import { AuthenticatedSocket } from '@app/game/types';
import { Instance } from '@app/game/instance/instance';
import { ServerPayloads } from '@shared/server/ServerPayloads';
export class Lobby
{
public readonly id: string = v4();
public readonly createdAt: Date = new Date();
public readonly clients: Map<Socket['id'], AuthenticatedSocket> = new Map<Socket['id'], AuthenticatedSocket>();
public readonly instance: Instance = new Instance(this);
constructor(
private readonly server: Server,
public readonly maxClients: number,
)
{
}
public addClient(client: AuthenticatedSocket): void
{
this.clients.set(client.id, client);
client.join(this.id);
client.data.lobby = this;
if (this.clients.size >= this.maxClients) {
this.instance.triggerStart();
}
this.dispatchLobbyState();
}
public removeClient(client: AuthenticatedSocket): void
{
this.clients.delete(client.id);
client.leave(this.id);
client.data.lobby = null;
// If player leave then the game isn't worth to play anymore
this.instance.triggerFinish();
// Alert the remaining player that client left lobby
this.dispatchToLobby<ServerPayloads[ServerEvents.GameMessage]>(ServerEvents.GameMessage, {
color: 'blue',
message: 'Opponent left lobby',
});
this.dispatchLobbyState();
}
public dispatchLobbyState(): void
{
const payload: ServerPayloads[ServerEvents.LobbyState] = {
lobbyId: this.id,
mode: this.maxClients === 1 ? 'solo' : 'duo',
delayBetweenRounds: this.instance.delayBetweenRounds,
hasStarted: this.instance.hasStarted,
hasFinished: this.instance.hasFinished,
currentRound: this.instance.currentRound,
playersCount: this.clients.size,
cards: this.instance.cards.map(card => card.toDefinition()),
isSuspended: this.instance.isSuspended,
scores: this.instance.scores,
};
this.dispatchToLobby(ServerEvents.LobbyState, payload);
}
public dispatchToLobby<T>(event: ServerEvents, payload: T): void
{
this.server.to(this.id).emit(event, payload);
}
}