-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
200 lines (159 loc) · 4.49 KB
/
server.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const http = require('http')
const express = require('express')
const WebSocket = require('ws')
const uuid = require('uuid')
const snake = require('./output/Main')
const app = express()
const minPlayers = parseInt(process.env.MIN_PLAYERS, 10) || 4
// { id :: UUID, ws :: WebSocketClient, gameId :: Maybe UUID }
const players = {}
// { gameId :: UUID, playerIds :: Array UUID, game :: GAME }
const games = {}
const INFO = {
CREATED: 0,
DESTROYED: 9,
GAME: 3
}
app.use(express.static('public'))
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })
// WebSocketClient -> Eff (eff) UUID
function addPlayer(ws) {
const id = uuid.v4()
players[id] = { id, ws, gameId: null }
console.log('addPlayer :: ', Object.keys(players).length)
return id
}
// String -> Eff (eff) (Maybe UUID)
function removePlayer(id) {
const { gameId } = players[id]
delete players[id]
console.log('removePlayer :: ', Object.keys(players).length)
return gameId
}
const newGame = snake.initGame(50)(50)(4)()
// UUID -> Eff (eff) Unit
function createGame(playerId) {
const minWaitingPlayers = minPlayers - 1
const waitingPlayers = Object.values(players).filter(({ id, gameId }) => gameId === null && id !== playerId)
if (waitingPlayers.length >= minWaitingPlayers) {
const gameId = uuid.v4()
const playerIds = [
playerId,
...waitingPlayers.slice(0, minWaitingPlayers).map(({ id }) => id)
]
const game = newGame
games[gameId] = {
gameId,
playerIds,
game
}
playerIds.forEach((id) => {
players[id] = { ...players[id], gameId }
})
sendGame(playerIds, game)
playerIds.forEach((id, i) => {
sendInfo(players[id].ws, INFO.CREATED, [i])
})
} else {
// waiting
}
}
// UUID -> Eff (eff) Unit
function destroyGame(gameId) {
const { playerIds } = games[gameId]
delete games[gameId]
playerIds.forEach((id) => {
if (!players[id]) return
players[id] = { ...players[id], gameId: null }
sendInfo(players[id].ws, INFO.DESTROYED, [])
})
}
wss.on('connection', (ws) => {
ws.binaryType = 'arraybuffer'
const id = addPlayer(ws)
createGame(id)
console.log('connect :: ', Object.keys(players).length)
ws.on('message', (data) => {
const [tick, code] = new Uint16Array(data)
const { gameId } = players[id]
if (!games[gameId]) return
if (new Set([0, 1, 2, 3]).has(code)) {
games[gameId] = {
...games[gameId],
game: snake.updateDirection
(snake.codeToDirection(code))
(games[gameId].playerIds.findIndex(($id) => $id === id))
(tick)
(games[gameId].game)
}
}
if (code === 4) {
games[gameId] = {
...games[gameId],
game: snake.switchPause(id)(games[gameId].game)
}
}
if (code === 5) {
games[gameId] = {
...games[gameId],
game: newGame
}
}
})
ws.on('close', () => {
const gameId = removePlayer(id)
if (gameId) {
destroyGame(gameId)
// TODO createGame ??
}
console.log('close :: ', Object.keys(players).length)
})
})
function encode(header, snakes) {
const encoded = new Uint16Array(1 + header.length + snakes.reduce((r, s) => r + s.length + 1, 0))
encoded[0] = INFO.GAME
let i
let x = 1
for (i = 0; i < header.length; i++)
encoded[x++] = header[i]
snakes.forEach((snake) => {
const [[live, index], [x_, y_], ...rest] = snake
encoded[x++] = live << 15 | index
encoded[x++] = x_
encoded[x++] = y_
for (i = 0; i < rest.length; i++) {
const [direction, length] = rest[i]
encoded[x++] = direction << 14 | length
}
})
return encoded
}
function sendGame(playerIds, game) {
const { header, snakes } = snake.encode(game)
const encoded = encode(header, snakes).buffer
playerIds.forEach((id) => {
players[id].ws.send(encoded, { binary: true })
})
}
function sendInfo(ws, state, message) {
const bytes = new Uint16Array(1 + message.length)
bytes[0] = state
message.forEach((v, i) => {
bytes[i + 1] = v
})
ws.send(bytes.buffer, { binary: true })
}
server.listen(process.env.PORT || 3000, () => {
console.log('Listening on %d', server.address().port);
setInterval(() => {
Object.values(games).forEach(({ gameId, game, playerIds }) => {
const updatedGame = snake.tick(game)()
games[gameId] = { ...games[gameId], game: updatedGame }
sendGame(playerIds, updatedGame)
})
}, 100)
})