-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathLobby.ts
More file actions
321 lines (275 loc) · 8.46 KB
/
Lobby.ts
File metadata and controls
321 lines (275 loc) · 8.46 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import type Client from "./Client.js";
import GameModes from "./GameMode.js";
import type {
ActionLobbyInfo,
ActionServerToClient,
GameMode,
} from "./actions.js";
export const Lobbies = new Map<string, Lobby>();
const generateUniqueLobbyCode = (): string => {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result = "";
for (let i = 0; i < 5; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return Lobbies.get(result) ? generateUniqueLobbyCode() : result;
};
export const getEnemy = (client: Client): [Lobby | null, Client | null] => {
const lobby = client.lobby
if (!lobby) return [null, null]
if (lobby.host?.id === client.id) {
return [lobby, lobby.guest]
} else if (lobby.guest?.id === client.id) {
return [lobby, lobby.host]
}
return [lobby, null]
}
/** How long to keep a disconnected player's slot reserved (ms) */
const RECONNECT_GRACE_PERIOD = 60000;
interface DisconnectedSlot {
client: Client;
role: 'host' | 'guest';
timer: ReturnType<typeof setTimeout>;
}
class Lobby {
code: string;
host: Client | null;
guest: Client | null;
gameMode: GameMode;
// biome-ignore lint/suspicious/noExplicitAny:
options: { [key: string]: any };
tcgBets: Map<string, number>;
handyAllowMPExtension: Map<string, boolean>;
firstReadyAt: number | null;
/** Tracks disconnected players awaiting reconnection */
disconnectedSlot: DisconnectedSlot | null = null;
/** Whether a game is currently in progress */
isInGame = false;
// Attrition is the default game mode
constructor(host: Client, gameMode: GameMode = "attrition") {
do {
this.code = generateUniqueLobbyCode();
} while (Lobbies.get(this.code));
Lobbies.set(this.code, this);
this.host = host;
this.guest = null;
this.gameMode = gameMode;
this.options = {};
this.tcgBets = new Map();
this.handyAllowMPExtension = new Map();
this.firstReadyAt = null;
host.setLobby(this);
host.isReadyLobby = false;
host.sendAction({
action: "joinedLobby",
code: this.code,
type: this.gameMode,
reconnectToken: host.reconnectToken,
});
}
static get = (code: string) => {
return Lobbies.get(code);
};
/** Voluntary leave — no grace period */
leave = (client: Client) => {
// Clear any pending reconnect slot for this lobby
if (this.disconnectedSlot) {
clearTimeout(this.disconnectedSlot.timer);
this.disconnectedSlot = null;
}
if (this.host?.id === client.id) {
this.host = this.guest;
this.guest = null;
} else if (this.guest?.id === client.id) {
this.guest = null;
}
client.setLobby(null);
this.isInGame = false;
if (this.host === null) {
Lobbies.delete(this.code);
} else {
this.handyAllowMPExtension.delete(client.id)
// TODO: Refactor for more than 2 players
// Stop game if someone leaves
this.broadcastAction({ action: "stopGame" });
this.resetPlayers();
this.broadcastLobbyInfo();
}
};
/** Connection lost — use grace period if game is in progress */
disconnect = (client: Client) => {
const isHost = this.host?.id === client.id;
const isGuest = this.guest?.id === client.id;
if (!isHost && !isGuest) return;
// If no game in progress or no other player, do a regular leave
if (!this.isInGame || (isHost && !this.guest) || (isGuest && !this.host)) {
this.leave(client);
return;
}
const role = isHost ? 'host' : 'guest';
const enemy = isHost ? this.guest : this.host;
// Reserve the slot with a grace period
console.log(`Player ${client.id} disconnected from lobby ${this.code}, reserving slot for ${RECONNECT_GRACE_PERIOD / 1000}s`)
this.disconnectedSlot = {
client,
role,
timer: setTimeout(() => {
// Grace period expired, do a full leave
console.log(`Reconnect grace period expired for lobby ${this.code}`)
this.disconnectedSlot = null;
this.leave(client);
}, RECONNECT_GRACE_PERIOD),
};
// Remove the client from the slot but keep the lobby alive
if (isHost) {
this.host = null;
} else {
this.guest = null;
}
client.setLobby(null);
// Notify the remaining player
enemy?.sendAction({ action: "enemyDisconnected" });
};
/** Reconnecting client reclaims their slot.
* Returns the restored Client (with all game state intact) on success, or null on failure.
* The caller MUST use the returned client for all future messages on this socket. */
rejoin = (newClient: Client, reconnectToken: string): Client | null => {
if (!this.disconnectedSlot || this.disconnectedSlot.client.reconnectToken !== reconnectToken) {
return null;
}
const { client: oldClient, role, timer } = this.disconnectedSlot;
clearTimeout(timer);
this.disconnectedSlot = null;
// Swap the new socket/connection onto the old client, preserving all game state
oldClient.replaceConnection(newClient);
// Place the old client back in the correct slot
if (role === 'host') {
this.host = oldClient;
} else {
this.guest = oldClient;
}
oldClient.setLobby(this);
this.handyAllowMPExtension.set(oldClient.id, false);
// Send rejoin confirmation with new reconnect token
oldClient.sendAction({
action: "rejoinedLobby",
code: this.code,
type: this.gameMode,
reconnectToken: oldClient.reconnectToken,
});
// Notify the other player
const enemy = role === 'host' ? this.guest : this.host;
enemy?.sendAction({ action: "enemyReconnected" });
// Re-sync game state so both sides have correct values
oldClient.sendAction({ action: "playerInfo", lives: oldClient.lives });
enemy?.sendAction({
action: "enemyInfo",
handsLeft: oldClient.handsLeft,
score: oldClient.score.toString(),
skips: oldClient.skips,
lives: oldClient.lives,
});
this.broadcastLobbyInfo();
return oldClient;
};
join = (client: Client) => {
if (this.guest) {
client.sendAction({
action: "error",
message: "Lobby is full or does not exist.",
});
return;
}
this.guest = client;
client.setLobby(this);
client.isReadyLobby = false;
this.handyAllowMPExtension.set(client.id, false)
client.sendAction({
action: "joinedLobby",
code: this.code,
type: this.gameMode,
reconnectToken: client.reconnectToken,
});
client.sendAction({ action: "lobbyOptions", gamemode: this.gameMode, ...this.options });
this.broadcastLobbyInfo();
};
broadcastAction = (action: ActionServerToClient) => {
this.host?.sendAction(action);
this.guest?.sendAction(action);
};
broadcastLobbyInfo = () => {
if (!this.host) {
return;
}
const action: ActionLobbyInfo = {
action: "lobbyInfo",
host: this.host.username,
hostHash: this.host.modHash,
isHost: false,
hostCached: this.host.isCached,
};
if (this.guest?.username) {
action.guest = this.guest.username;
action.guestHash = this.guest.modHash;
action.guestCached = this.guest.isCached;
action.guestReady = this.guest.isReadyLobby;
this.guest.sendAction(action);
}
// Should only sent true to the host
action.isHost = true;
this.host.sendAction(action);
this.broadcastAction({
action: "handyMPExtensionLobbyEnabled",
enabled: Array.from(this.handyAllowMPExtension.values()).every(Boolean)
})
};
setPlayersLives = (lives: number) => {
// TODO: Refactor for more than 2 players
if (this.host) this.host.lives = lives;
if (this.guest) this.guest.lives = lives;
this.broadcastAction({ action: "playerInfo", lives });
};
// Deprecated
sendGameInfo = (client: Client) => {
if (this.host !== client && this.guest !== client) {
return client.sendAction({
action: "error",
message: "Client not in Lobby",
});
}
client.sendAction({
action: "gameInfo",
...GameModes[this.gameMode].getBlindFromAnte(client.ante, this.options),
});
};
setOptions = (options: { [key: string]: string }) => {
for (const key of Object.keys(options)) {
if (options[key] === "true" || options[key] === "false") {
this.options[key] = options[key] === "true";
} else {
this.options[key] = options[key];
}
}
this.guest?.sendAction({ action: "lobbyOptions", gamemode: this.gameMode, ...options });
};
resetPlayers = () => {
this.isInGame = false;
if (this.host) {
this.host.isReady = false;
this.host.resetBlocker();
this.host.setLocation("Blind Select");
this.host.furthestBlind = 0;
this.host.skips = 0;
}
if (this.guest) {
this.guest.isReady = false;
this.guest.resetBlocker();
this.guest.setLocation("Blind Select");
this.guest.furthestBlind = 0;
this.guest.skips = 0;
}
this.tcgBets.clear();
this.firstReadyAt = null;
}
}
export default Lobby;