-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
400 lines (324 loc) · 11.5 KB
/
app.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
var http = require('http');
var express = require('express');
var _ = require('lodash');
var bunyan = require('bunyan');
var log = bunyan.createLogger({name: 'app', level: process.env.LOG_LEVEL || 'info'});
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server, {origins: '*:*'});
app.use(express.static('static'));
var port = process.env.PORT || 5000;
server.listen(port, function(err) {
if (err) return log.error(err.stack);
log.info('http server listening', {port});
});
games = {};
var nextMissileId = 1;
var LOOP_INTERVAL = 100;
var MISSILE_ERROR_MARGINAL_ANGLE = 5;
var MISSILE_COOLDOWN = 500; // milliseconds.
var MISSILE_SPEED_MIN = 5; // % / second.
var MISSILE_SPEED_MAX = 80; // % / second.
var SCORE_TO_WIN = 10;
function getNow() {
return new Date().getTime();
}
function getOrCreateGame(gameId) {
if (!games[gameId]) {
games[gameId] = {
id: gameId,
state: 'waiting_for_players',
players: [],
missiles: [],
loopInterval: null,
prevTime: null,
}
}
return games[gameId];
}
function destroyGame(gameId) {
log.info('destroying game', {gameId});
game = games[gameId];
if (game.loopInterval) {
clearInterval(game.loopInterval);
}
delete games[gameId];
}
function getGame(gameId) {
return games[gameId];
}
function createPlayer(username, socket) {
return {
username: username,
socket: socket,
calibration: null,
score: 0,
missileCooldown: 0,
};
}
function createMissile(game, from, to, speed) {
if (!speed) { speed = 20; } // temp for backwards compatibility.
if (speed > MISSILE_SPEED_MAX) { speed = MISSILE_SPEED_MAX; }
if (speed < MISSILE_SPEED_MIN) { speed = MISSILE_SPEED_MIN; }
return {
id: nextMissileId++,
from: from,
to: to,
distance: 0,
speed: speed,
}
}
function findPlayer(game, username) {
return _.find(game.players, function(p) { return p.username == username });
}
function addPlayer(game, player) {
game.players.push(player);
publishGameState(game);
}
function removePlayer(game, username) {
log.info('removing player', {gameId: game.id, username});
game.players = _.reject(game.players, function(p) {
return p.username == username;
})
publishGameState(game);
if (game.players.length == 0) {
destroyGame(game.id);
}
}
function startGame(game) {
log.info('will start game', {gameId: game.id});
game.state = 'waiting_for_calibration';
publishGameState(game);
}
function setPlayerCalibration(game, username, calibration) {
log.info('setting calibration for player', {gameId: game.id, username, calibration});
var player = findPlayer(game, username);
player.calibration = calibration;
var allCalibrated = _.every(game.players, function(p) { return !!p.calibration })
if (allCalibrated) {
game.state = 'running';
sendToAllPlayers(game, 'game started');
startGameLoop(game);
} else {
log.info('will not start game yet, not all players have calibrated', {gameId: game.id});
}
}
function startGameLoop(game) {
if (game.loopInterval) return log.error('there is already a loop interval', {gameId: game.id});
game.prevTime = getNow();
game.loopInterval = setInterval(function() {
var now = getNow();
var timeDelta = now - game.prevTime;
// Move missiles.
var missilesToRemove = []
_.each(game.missiles, function(m) {
m.distance += m.speed * (timeDelta / 1000.0)
if (m.distance >= 100) {
log.info('missile has hit', m);
missilesToRemove.push(m);
var fromPlayer = findPlayer(game, m.from);
var toPlayer = findPlayer(game, m.to);
if (toPlayer) {
toPlayer.socket.emit('missile status', {status: 'was_hit'});
} else {
log.warn('could not find to player', {username: m.to})
}
if (fromPlayer) {
fromPlayer.score += 1;
log.info('increasing player score', {username: fromPlayer.username, score: fromPlayer.score});
fromPlayer.socket.emit('missile status', {status: 'target_hit'});
if (fromPlayer.score >= SCORE_TO_WIN){
finishRound(game);
}
} else {
log.warn('could not find from player', {username: m.from})
}
}
});
game.missiles = _.reject(game.missiles, function(m) {
return _.find(missilesToRemove, function(m2) { return m2 == m; });
})
// Update cooldowns;
_.each(game.players, function(p) {
if (p.missileCooldown > 0) {
p.missileCooldown = Math.max(p.missileCooldown - timeDelta, 0);
}
});
publishGameState(game);
game.prevTime = now;
}, LOOP_INTERVAL);
}
function finishRound(game){
var playerScores = _.filter(game.players, function(p) { return {username: p.username, score: p.score}});
log.info('game round has finished', {gameId: game.id, playerData: playerScores})
game.state = 'round_finished';
if (game.loopInterval) {
clearInterval(game.loopInterval);
}
}
function publishGameState(game) {
var data = {
id: game.id,
state: game.state,
players: _.map(game.players, function(p) {
return {
username: p.username,
score: p.score,
calibration: p.calibration,
missileCooldown: p.missileCooldown,
};
}),
missiles: game.missiles,
};
sendToAllPlayers(game, 'game state updated', data);
}
function fireMissile(game, username, data) {
logData = {gameId: game.id, username, data};
log.info('firing missile', logData);
var player = findPlayer(game, username);
if (player.missileCooldown > 0) {
return log.info('will not fire missile, waiting for cooldown', logData, {missileCooldown: player.missileCooldown});
}
player.missileCooldown = MISSILE_COOLDOWN;
var target = _.find(player.calibration, function(c) {
var d = angleDistance(c.angle, data.angle);
return d <= MISSILE_ERROR_MARGINAL_ANGLE;
});
if (!target) {
log.warn('no target for missile', logData)
player.socket.emit('missile status', {status: 'no_target'});
return
}
log.info('found missile target', {target}, logData)
if (target.username == username) {
log.warn('dropping missile, cannot target yourself', logData)
player.socket.emit('missile status', {status: 'cannot_target_self'});
return
}
var missile = createMissile(game, username, target.username, data.speed);
game.missiles.push(missile);
}
function removeMissile(game, username, data) {
log.info('removing missile', {gameId: game.id, username, data})
var missile = _.find(game.missiles, function(m) { return m.id == data.id });
if (!missile) return log.info('found no missile with id', {gameId: game.id, username, data})
if (!missile.to == username) return log.warn('missile not meant for user', {gameId: game.id, username, data, missile: missile})
var fromPlayer = findPlayer(game, missile.from);
if (fromPlayer) {
fromPlayer.socket.emit('missile status', {status: 'missile_removed'});
} else {
log.warn('could not find missile from player', {username: missile.from})
}
game.missiles = _.reject(game.missiles, function(m) { return m.id == data.id })
}
function sendToAllPlayers(game, event, data) {
log.debug('publishing to all players', {gameId: game.id, event, data: JSON.stringify(data)})
game.players.forEach(function(p) {
p.socket.emit(event, data);
});
}
function angleDistance(a, b) {
var phi = Math.abs(b - a) % 360; // This is either the distance or 360 - distance
return phi > 180 ? 360 - phi : phi;
}
io.on('connection', function(socket) {
var socketData = {clientIp: socket.request.connection.remoteAddress};
log.info('user connected', socketData);
var username, gameId;
var joined = false;
socket.on('join game', function(data) {
log.debug('join game', data);
if (joined) {
return log.warn('user cannot join, already joined', {username, gameId, data});
}
username = data.username;
gameId = data.gameId;
var game = getOrCreateGame(gameId);
if (findPlayer(game, username)) {
socket.emit('client error', {status: 'cannot_join', reason: 'username_taken', gameId: gameId});
return log.warn('player already joined', {gameId, username});
}
if (game.state != 'waiting_for_players') {
socket.emit('client error', {status: 'cannot_join', reason: 'wrong_game_state', gameId: gameId});
return log.warn('player cannot join game, wrong state', {gameId, username, state: game.state});
}
joined = true;
addPlayer(game, createPlayer(username, socket));
});
socket.on('start game', function(data) {
log.debug('start game', data);
if (!joined) {
socket.emit('client error', {status: 'cannot_start', reason: 'not_joined'});
return;
};
var game = getGame(gameId);
if (!game) {
socket.emit('client error', {status: 'cannot_start', reason: 'game_not_found', gameId: gameId});
return log.info('cannot find game', {gameId});
}
if (game.state != 'waiting_for_players') {
socket.emit('client error', {status: 'cannot_start', reason: 'wrong_game_state', gameId: gameId});
return log.warn('cannot start game, wrong state', {gameId, username, state: game.state})
}
startGame(game);
})
socket.on('set calibration', function(data) {
log.debug('set calibration', data);
if (!joined) return;
var game = getGame(gameId);
if (!game) {
socket.emit('client error', {status: 'cannot_set_calibration', reason: 'game_not_found', gameId: gameId});
return log.info('cannot find game', {gameId});
}
if (game.state != 'waiting_for_calibration') {
socket.emit('client error', {status: 'cannot_set_calibration', reason: 'wrong_game_state', gameId: gameId});
return log.warn('cannot set calibration, wrong state', {gameId, username, state: game.state})
}
setPlayerCalibration(game, username, data)
});
socket.on('fire missile', function(data) {
log.debug('fire missile', data);
if (!joined) return;
var game = getGame(gameId);
if (!game) {
socket.emit('client error', {status: 'cannot_fire_missile', reason: 'game_not_found', gameId: gameId});
return log.warn('cannot find game', {gameId});
}
if (game.state != 'running') {
socket.emit('client error', {status: 'cannot_fire_missile', reason: 'wrong_game_state', gameId: gameId});
return log.warn('game is not running', {gameId, state: game.state});
}
fireMissile(game, username, data)
});
socket.on('remove missile', function(data) {
log.debug('remove missile', data);
if (!joined) return;
var game = getGame(gameId);
if (!game) {
socket.emit('client error', {status: 'cannot_remove_missile', reason: 'game_not_found', gameId: gameId});
return log.warn('cannot find game', {gameId});
}
if (game.state != 'running') {
socket.emit('client error', {status: 'cannot_remove_missile', reason: 'wrong_game_state', gameId: gameId});
return log.warn('game is not running', {gameId, state: game.state});
}
removeMissile(game, username, data)
})
socket.on('disconnect', function() {
log.warn('user disconnected', {socketData});
if (!joined) return;
var game = getGame(gameId);
if (!game) return log.info('cannot find game', {gameId});
removePlayer(game, username)
});
socket.on('leave game', function() {
log.warn('leave game', {joined, gameId, username, socketData});
if (!joined) return log.warn('cannot leave, have not joined');
var game = getGame(gameId);
if (!game) return log.info('cannot find game', {gameId});
removePlayer(game, username)
username = null;
gameId = null;
joined = false;
});
});