aboutsummaryrefslogtreecommitdiffstats
path: root/backend/src/websocket/game.ts
blob: c37b1c5fe0bf2913b51d29f500f52150b5a89b3e (plain)
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
import { Server } from "http";
import { addSessionClient, getSession, setSessionHost, setSessionState } from "../config/session-store.js";
import { WebSocketServer } from "ws";
import { v4 as uuidv4 } from "uuid";

const wss = new WebSocketServer({ noServer: true });

const sendToClient = (clientId: string, message: any) => {
  wss.clients.forEach((client: any) => {
    if (client.clientId === clientId) {
      client.send(JSON.stringify(message));
    }
  });
};

const broadcastToClients = (clientIds: string[], message: any) => {
  wss.clients.forEach((client: any) => {
    if (clientIds.includes(client.clientId)) {
      client.send(JSON.stringify(message));
    }
  });
};

export const createWebsocketServer = (server: Server): WebSocketServer => {
  server.on("upgrade", (req, socket, head) => {
    wss.handleUpgrade(req, socket, head, (ws) => {
      wss.emit("connection", ws, req);
    });
  });

  wss.on("connection", (ws: any) => {
    ws.clientId = uuidv4();

    ws.on("message", (message) => {
      console.log("received: %s", message);
      let data;
      try {
        data = JSON.parse(message.toString());
      } catch (e) {
        console.log("Invalid JSON");
        return;
      }
      
      if (data.action === "host") {
        setSessionHost(data.sessionId, ws.clientId);
      } else if (data.action === "move") {
        const session = getSession(data.sessionId);
        if (!session) {
          return;
        }

        sendToClient(session.host!, {
          action: "move",
          move: data.move,
        });
      } else if (data.action === "join") {
        const session = getSession(data.sessionId);
        if (!session) {
          return;
        }

        addSessionClient(data.sessionId, ws.clientId);
        
        sendToClient(session.host!, {
          action: "join",
          clients: session.clients.length,
        });
        
        ws.send(JSON.stringify({
          action: "state",
          state: session.state,
        }));
      } else if (data.action === "start") {
        const session = getSession(data.sessionId);
        if (!session) {
          return;
        }
        
        setSessionState(data.sessionId, "playing");

        sendToClient(session.host!, {
          action: "state",
          state: "playing",
        });
        
        broadcastToClients(session.clients, {
          action: "state",
          state: "playing",
        });
      }
    });
  });

  return wss;
};

export default createWebsocketServer;