forked from octachrome/treason
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
297 lines (245 loc) · 8.18 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
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
/*
* Copyright 2015-2016 Christopher Brown and Jackie Niebling.
*
* This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License.
*
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to:
* Creative Commons
* PO Box 1866
* Mountain View
* CA 94042
* USA
*/
'use strict';
var dataAccess = require('./dataaccess');
var argv = require('optimist')
.usage('$0 [--debug] [--recreate-views] [--port <port>] [--log <logfile>] [--db <database>]')
.default('port', 8080)
.default('log', 'treason.log')
.default('db', 'treason_db')
.argv;
dataAccess.init(argv.db);
var winston = require('winston');
winston.add(winston.transports.File, {
filename: argv.log,
maxsize: 5*1024*1024,
zippedArchive: true,
json: false
});
winston.remove(winston.transports.Console);
winston.info('server started');
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/web'));
var version = require('./version');
app.get('/version.js', version);
app.get('/', function (req, res) {
res.render('pages/index.ejs');
});
var server = app.listen(argv.port);
dataAccess.setRecreateViews(argv['recreate-views']);
var io = require('socket.io')(server);
var createGame = require('./game');
var createNetPlayer = require('./net-player');
var gameId = 1;
var games = {};
var players = {};
var rankings = [];
dataAccess.getPlayerRankings().then(function (result) {
rankings = result;
//This will submit the rankings to everyone
io.sockets.emit('rankings', result);
});
io.on('connection', function (socket) {
//Emit the global rankings upon connect
socket.emit('rankings', rankings);
socket.on('registerplayer', function (data) {
if (isInvalidPlayerName(data.playerName)) {
//Do not even attempt to register invalid player names
return;
}
var userAgent = socket.request.headers['user-agent'];
dataAccess.register(data.playerId, data.playerName, userAgent).then(function (playerId) {
socket.playerId = playerId;
var playerName = data.playerName;
var currentOnlinePlayers = filterPlayers().concat([{playerName: playerName}]);
socket.emit('handshake', {
playerId: playerId,
games: filterGames(),
players: currentOnlinePlayers
}, function (data) {
//Once the client acknowledged it received the handshake, it will invoke the function passed and let us
//know it was logged in. We will ignore that message and add the player to the list of logged in players.
players[playerId] = {
playerName: playerName
};
broadcastPlayers();
socket.broadcast.emit('globalchatmessage', playerName + ' has joined the lobby.');
});
});
});
socket.on('join', function (data) {
var playerName = data.playerName;
var gameName = data.gameName;
var password = data.password;
if (isInvalidPlayerName(playerName)) {
return;
}
if (gameName) {
joinGame(socket, gameName, playerName, password);
} else {
quickJoin(socket, playerName);
}
});
socket.on('create', function(data) {
if (isInvalidPlayerName(data.playerName)) {
return;
}
createNewGame(socket, data.password);
});
socket.on('showrankings', function () {
dataAccess.getPlayerRankings(socket.playerId).then(function (result) {
socket.emit('rankings', result);
});
});
socket.on('showmyrank', function () {
dataAccess.getPlayerRankings(socket.playerId, true).then(function (result) {
socket.emit('rankings', result);
});
});
socket.on('sendglobalchatmessage', function (data) {
if (data.length > 300) {
data = data.slice(0, 300) + '...';
}
var now = new Date();
var timeStamp = '[' + now.getHours() + ':' + ('0' + now.getMinutes()).slice(-2) + '] ';
var playerName = players[socket.playerId].playerName;
var globalMessage = timeStamp + playerName + ': ' + data;
var localMessage = timeStamp + ' You: ' + data;
socket.emit('globalchatmessage', localMessage);
socket.broadcast.emit('globalchatmessage', globalMessage);
});
socket.on('disconnect', function () {
if (socket.playerId) {
//If a client never registered but only connected, it would not have a player property
var player = players[socket.playerId];
if (player) {
socket.broadcast.emit('globalchatmessage', player.playerName + ' has left the lobby.');
delete players[socket.playerId];
}
}
broadcastGames();
broadcastPlayers();
socket.removeAllListeners();
socket = null;
});
});
function joinGame(socket, gameName, playerName, password) {
var game = games[gameName];
if (game) {
if (!game.password() || game.password() === password) {
playerJoinsGame(game, socket, playerName, gameName);
} else {
socket.emit('incorrectpassword');
}
} else {
socket.emit('gamenotfound');
}
}
function quickJoin(socket, playerName) {
//Discover a game to join. This should prefer the older games in the list
for (var gameName in games) {
if (games.hasOwnProperty(gameName)) {
var game = games[gameName];
if (game && game.canJoin() && !game.password()) {
playerJoinsGame(game, socket, playerName, gameName);
return;
}
}
}
//Failed to find a game, make a new one instead
createNewGame(socket);
}
function playerJoinsGame(game, socket, playerName, gameName) {
createNetPlayer(game, socket, playerName);
socket.emit('joined', {
gameName: gameName,
password: game.password()
});
broadcastGames();
}
function createNewGame(socket, password) {
var gameName = '' + gameId++;
var game = createGame({
debug: argv.debug,
logger: winston,
moveDelay: 1000,
gameName: gameName,
created: new Date(),
password: password || ''
});
games[gameName] = game;
game.once('teardown', function () {
delete games[gameName];
broadcastGames();
});
game.once('end', function () {
dataAccess.getPlayerRankings().then(function (result) {
rankings = result;
});
});
game.on('statechange', function () {
broadcastGames();
});
socket.emit('created', {
gameName: gameName,
password: password
});
}
function isInvalidPlayerName(playerName) {
return !playerName || playerName.length > 30 || !playerName.match(/^[a-zA-Z0-9_ !@#$*]+$/ || !playerName.trim());
}
function broadcastGames() {
var gamesList = filterGames();
io.sockets.emit('updategames', {
games: gamesList
});
}
function broadcastPlayers() {
var playerList = filterPlayers();
io.sockets.emit('updateplayers', {
players: playerList
});
}
function filterPlayers() {
var playerList = [];
for (var playerId in players) {
if (players.hasOwnProperty(playerId)) {
var player = players[playerId];
playerList.push({
playerName: player.playerName
});
}
}
return playerList;
}
function filterGames() {
var gamesList = [];
for (var gameName in games) {
if (games.hasOwnProperty(gameName)) {
var game = games[gameName];
if (game) {
var clientGame = {
gameName: gameName,
status: game.currentState(),
type: game.gameType(),
passwordRequired: game.password() ? true : false,
players: game.playersInGame()
};
gamesList.push(clientGame);
}
}
}
return gamesList;
}