MCPcopy Create free account
hub / github.com/code100x/chess / GameManager

Class GameManager

apps/ws/src/GameManager.ts:22–209  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

20import { GameStatus } from '@prisma/client';
21
22export class GameManager {
23 private games: Game[];
24 private pendingGameId: string | null;
25 private users: User[];
26
27 constructor() {
28 this.games = [];
29 this.pendingGameId = null;
30 this.users = [];
31 }
32
33 addUser(user: User) {
34 this.users.push(user);
35 this.addHandler(user);
36 }
37
38 removeUser(socket: WebSocket) {
39 const user = this.users.find((user) => user.socket === socket);
40 if (!user) {
41 console.error('User not found?');
42 return;
43 }
44 this.users = this.users.filter((user) => user.socket !== socket);
45 socketManager.removeUser(user);
46 }
47
48 removeGame(gameId: string) {
49 this.games = this.games.filter((g) => g.gameId !== gameId);
50 }
51
52 private addHandler(user: User) {
53 user.socket.on('message', async (data) => {
54 const message = JSON.parse(data.toString());
55 if (message.type === INIT_GAME) {
56 if (this.pendingGameId) {
57 const game = this.games.find((x) => x.gameId === this.pendingGameId);
58 if (!game) {
59 console.error('Pending game not found?');
60 return;
61 }
62 if (user.userId === game.player1UserId) {
63 socketManager.broadcast(
64 game.gameId,
65 JSON.stringify({
66 type: GAME_ALERT,
67 payload: {
68 message: 'Trying to Connect with yourself?',
69 },
70 }),
71 );
72 return;
73 }
74 socketManager.addUser(user, game.gameId);
75 await game?.updateSecondPlayer(user.userId);
76 this.pendingGameId = null;
77 } else {
78 const game = new Game(user.userId, null);
79 this.games.push(game);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected