-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager.js
56 lines (53 loc) · 1.55 KB
/
manager.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
const crypto = require('crypto')
const { pick } = require('./util')
function makeManager() {
const store = {}
return {
hasPlayer: (gameId, player) => {
if (!gameId || !player) { return false }
const clients = store[gameId] || []
return clients.some((c) => c.player === player)
},
addPlayer: (gameId, player, name, lastMessageTime, ws) => {
const clients = store[gameId] || []
ws.clientId = crypto.randomUUID()
ws.gameId = gameId
ws.player = player
ws.name = name
ws.lastMessageTime = lastMessageTime
store[gameId] = clients.concat([ ws ])
return ws
},
removePlayer: (gameId, clientId) => {
if (!store[gameId]) { return }
let removed = null
store[gameId] = (store[gameId] || []).filter((c) => {
if (c.clientId === clientId) {
removed = c
}
return c.clientId !== clientId
})
return removed
},
getPlayers: (gameId) => {
return store[gameId] || []
},
broadcastUpdate: (gameId, gameJson) => {
console.log('broadcastUpdate', gameId)
if (!(gameId in store)) { return }
const players = (store[gameId] || [])
const update = {
event: 'update',
online: players
.filter((c) => !['admin', 'present'].includes(c.player))
.map((c) => pick(c, ['player', 'name', 'lastMessageTime', 'clientId'])),
...gameJson,
}
const message = JSON.stringify(update)
players.forEach((c) => c.send(message))
}
}
}
module.exports = {
makeManager,
}