-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (65 loc) · 2.18 KB
/
Copy pathserver.js
File metadata and controls
75 lines (65 loc) · 2.18 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
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const players = [];
wss.on('connection', function connection(ws) {
// Generate a random color for the player
const color = '#' + Math.floor(Math.random() * 16777215).toString(16);
// Add the new player to the list
const player = {
id: Math.random().toString(36).substr(2, 9),
x: Math.random() * 380,
y: Math.random() * 380,
color: color,
socket: ws,
};
players.push(player);
// Send the current game state to the new player
const initialState = {
type: "state",
players: players.map(({ id, x, y, color }) => ({ id, x, y, color })),
};
ws.send(JSON.stringify(initialState));
// Broadcast the new player's position to all connected players
const playerJoined = {
type: "state",
players: players.map(({ id, x, y, color }) => ({ id, x, y, color })),
};
broadcast(JSON.stringify(playerJoined));
// Handle messages from the player
ws.on('message', function incoming(message) {
const data = JSON.parse(message);
if (data.type === "move") {
// Update the player's position
player.x += data.dx;
player.y += data.dy;
// Broadcast the updated player list to all connected players
const playerMoved = {
type: "state",
players: players.map(({ id, x, y, color }) => ({ id, x, y, color })),
};
broadcast(JSON.stringify(playerMoved));
}
});
// Handle player disconnection
ws.on('close', function () {
// Remove the player from the list
const index = players.indexOf(player);
if (index > -1) {
players.splice(index, 1);
// Broadcast the updated player list to all connected players
const playerLeft = {
type: "state",
players: players.map(({ id, x, y, color }) => ({ id, x, y, color })),
};
broadcast(JSON.stringify(playerLeft));
}
});
// Broadcast a message to all connected players
function broadcast(message) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
});