-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.js
225 lines (186 loc) · 5.51 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
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
import _ from 'underscore';
import express from 'express';
import {config} from './config.js';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import http from 'http';
import socketIO from 'socket.io';
import * as engine from './lib/engine.js';
import {Game} from './lib/game.js';
import * as bot from './lib/bot.js';
import * as achievements from "./lib/achievements.js";
import * as winston from 'winston';
const app = express();
const server = http.createServer(app);
const io = socketIO.listen(server);
const shouldBroadcast = true;
const games = { };
const logFile = 'latency.log';
let latencyMeasurers = [];
app.set('view engine', 'ejs');
app.use('/bower_components', express.static('bower_components'));
app.use('/public', express.static('public'));
app.use('/common', express.static('common'));
app.use(cookieParser());
app.use(session({
secret: "nodekick",
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//http
app.get('/', (req, res) => { res.render('index'); });
app.post('/join', ({body}, res) => {
let room = body.room;
if(!room) room = "public";
res.redirect(`/game/${room}`);
});
app.get("/game/:id", ({params}, res) => {
getGame(params.id);
res.render('game');
});
server.listen(process.env.PORT || config.port);
//sockets
function setBroadcast(game) { game.shouldBroadcast = true; }
function broadcast(game) {
if(!game.shouldBroadcast) return;
emit(game.id, 'gamestate', {
frame: engine.getFrame(),
players: engine.getPlayers(game),
});
game.shouldBroadcast = false;
}
function emit(gameId, message, args) {
const game = getGame(gameId);
_.each(game.sockets, socket => {
socket.emit(message, args);
});
}
function getGame(gameId) {
if(!games[gameId]) {
games[gameId] = new Game(gameId);
games[gameId].shouldBroadcast = true;
}
return games[gameId];
}
function input(direction, gameId, playerId, playerName) {
const game = getGame(gameId);
engine[direction](game, playerId, playerName);
setBroadcast(game);
}
io.sockets.on('connection', socket => {
socket.on('joinGame', ({gameId}) => {
const game = getGame(gameId);
socket.game = game;
game.sockets.push(socket);
setBroadcast(game);
});
socket.on('client-ping', (args) => {
socket.emit('client-pong', args);
});
socket.on('disconnect', () => {
if(!socket.game) return;
socket.game.sockets = _.without(socket.game.sockets, socket);
});
socket.on('up', ({gameId, playerId, playerName}) => {
input('up', gameId, playerId, playerName);
});
socket.on('down', ({gameId, playerId, playerName}) => {
input('down', gameId, playerId, playerName);
});
socket.on('left', ({gameId, playerId, playerName}) => {
input('left', gameId, playerId, playerName);
});
socket.on('right', ({gameId, playerId, playerName}) => {
input('right', gameId, playerId, playerName);
});
socket.on('sendchat', data => {
emit(data.session.gameId, 'receivechat', {
name: data.session.playerName,
message: data.message
});
});
socket.on('pongpong', ({pingSentTime, pongSentTime}) => {
latencyMeasurers.push({
pingSentTime,
pongSentTime,
pongReceivedTime: Date.now()
});
});
});
function processAchievements({id}, {deaths}) {
const achievementsThisTick = achievements.get(deaths);
if(achievementsThisTick.length == 0) return;
emit(id, 'achievement', achievementsThisTick);
}
const framesPerSecondInMilliseconds = 1000.0 / engine.fps;
let syncRate = 0;
setInterval(() => {
syncRate += 1;
for(const key in games) {
const game = games[key];
const botAdded = bot.add(game);
const actionMade = bot.tick(game);
const tickResult = engine.tick(game);
const occasionallySync = (syncRate % 300) == 0;
if(occasionallySync) syncRate = 0;
if(actionMade ||
botAdded ||
tickResult.deathsOccurred ||
occasionallySync) {
setBroadcast(game);
}
broadcast(game);
processAchievements(game, tickResult);
}
}, framesPerSecondInMilliseconds);
// latency logging after every 10 seconds if environment variable set to 'true'
(() => {
let shouldLog = process.env.SHOULD_LOG_LATENCY;
if (shouldLog === 'true') {
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
formatter: function(options) {
return options.message;
}
}),
new (winston.transports.File)({
filename: logFile,
json: false,
formatter: function(options) {
return options.message;
}
})
]
});
setInterval(() => {
// do we have anything to log
if (latencyMeasurers.length > 0) {
let clientCount = latencyMeasurers.length;
let latencySum = latencyMeasurers.reduce((acc, curr) => {
return acc + (curr.pongReceivedTime - curr.pingSentTime);
}, 0);
// we can now clear out latencyMeasurers
latencyMeasurers.length = 0;
// write log to file, and send pings again when done
let logObj = {
time: new Date(Date.now() - 10000).toUTCString(),
numberOfPlayers: clientCount,
averagePing: (latencySum / clientCount)
};
logger.info(JSON.stringify(logObj));
}
sendPings();
}, 10000);
}
})();
function sendPings() {
for (const gameId in games) {
emit(gameId, 'pingping', {
pingSentTime: Date.now()
});
}
}