-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (58 loc) · 2 KB
/
index.js
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
const WebSocket = require("ws");
const express = require("express");
const PORT = process.env.PORT || 8080;
const app = express(PORT);
app.use(express.static("public"));
server = app.listen(PORT);
const wss = new WebSocket.Server({ server });
const players = {};
const playerName = "";
const playerRadius = 0;
const playerColor = "red";
function generateUniqueId() {
return Math.random().toString(36);
}
wss.on("connection", function connection(ws) {
const playerId = generateUniqueId();
players[playerId] = { ws, x: 0, y: 0 };
//received message from client of player position
ws.on("message", function incoming(message) {
console.log("Received message from client:", message);
const data = JSON.parse(message);
//if the message is player position, update the player position
if (data.type === "playerPosition") {
players[playerId].x = data.x;
players[playerId].y = data.y;
players[playerId].name = data.userName;
players[playerId].radius = data.radius;
players[playerId].color = data.color;
console.log("Player position radius:", players[playerId].radius);
broadcastPlayerPositions();
}
});
ws.on("close", function () {
console.log("Client disconnected:", playerId);
const disconnectedPlayer = players[playerId];
delete players[playerId];
broadcastPlayerPositions();
console.log("Player disconnected:", disconnectedPlayer.name);
});
ws.send(JSON.stringify({ type: "playerId", playerId }));
});
function broadcastPlayerPositions() {
const playerPositions = Object.keys(players)
.map((playerId) => ({
playerId,
name: players[playerId].name,
x: players[playerId].x,
y: players[playerId].y,
radius: players[playerId].radius,
color: players[playerId].color,
}))
.filter((player) => player.name !== undefined);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: "playerPositions", playerPositions }));
}
});
}