-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.js
445 lines (418 loc) · 18.9 KB
/
socket.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
const Sequelize = require('sequelize');
const EloRating = require('elo-rating');
const Op = Sequelize.Op;
// Load Games Model
const Game = require('./models').Game;
// Load Users Model
const User = require('./models').User;
//Load GameChat Model
const GameChats = require('./models').GameChats;
var socketCount = 0;
module.exports = function (io) {
/* Check for connection between client and server */
io.on('connection', (socket) => {
// Track which user connects/disconnect and how many users connected
socketCount++;
console.log('User connected');
console.log('Connected users: ' + socketCount);
io.emit('users connected', socketCount);
socket.on('disconnect', function () {
socketCount--;
console.log('User disconnected');
console.log('Connected users: ' + socketCount);
io.emit('users connected', socketCount);
});
// Display lobby chat messages to connected clients
socket.on('lobby chat', (data) => {
io.emit('lobby chat', data);
});
// Store game chat messages and display to that specific gameroom
socket.on('game chat', (data) => {
GameChats.create({
gameId: data.gameId,
userName: data.username,
message: data.msg
});
io.in(data.gameId).emit('game chat', data);
});
/**
* Create a new game room and notify the creator of game.
*/
socket.on('createGame', function (data) {
// Unique gameID generator
var gameID = new IDGenerator().generate(),
hours,
minutes,
timeRemFormatted;
return Game.create({
gameId: gameID,
player1: data.player1,
move: data.player1,
moveTimeLimit: data.moveTimeLimit
}).then(function (game) {
console.log(game.player1 + ' created game: ' + game.gameId);
hours = Math.floor((game.moveTimeLimit / (60)));
minutes = game.moveTimeLimit % 60;
timeRemFormatted = parseInt(hours, 10) + 'h' + parseInt(minutes, 10) + 'm';
// handle rendering newly created game in lobby
socket.broadcast.emit('newGameCreated', {
gameID: game.gameId,
player1: game.player1,
moveTime: timeRemFormatted
});
socket.emit('newGame', { gameID: game.gameId });
});
});
/**
* Connect the Player to the room they requested.
*/
socket.on('joinGame', function (data) {
var rejoin = false;
Game.findOne({
where: {
gameId: data.gameID,
result: null
}
}).then(function (game) {
// Check to see if such game exist
if (game) {
// Check if current user belongs to such game
if (game.player1 == data.currUser || game.player2 == data.currUser) {
socket.join(game.gameId);
if (game.player2 == null) {
console.log(data.currUser + ' joined game: ' + game.gameId);
}
else {
console.log(data.currUser + ' has returned back to game: ' + game.gameId);
rejoin = true;
}
//socket.broadcast.to(data.gameID).emit('oppRejoined', { oppName: data.currUser });
// Retrieve game chat messages
GameChats.findAndCountAll({ where: { gameId: data.gameID } }).then(function (messages, err) {
if (err) {
console.log('Error retrieving GameChats messages');
}
else {
for (var i = 0; i < messages.count; i++) {
socket.emit('retrieve game chat', messages.rows[i]);
}
}
}).then(function () {
User.findAll({ where: {
[Op.or]: [{ userName: game.player1 }, { userName: game.player2 }]
} }).then(function (user) {
//console.log(user)
var currUserRating, oppRating, boardTheme2D, pieceTheme2D, pieceTheme3D;
if (user[0].userName == data.currUser) {
boardTheme2D = user[0].boardTheme2D;
pieceTheme2D = user[0].pieceTheme2D;
pieceTheme3D = user[0].pieceTheme3D;
currUserRating = user[0].rating;
if (game.player2 != null) {
oppRating = user[1].rating;
}
}
else {
boardTheme2D = user[1].boardTheme2D;
pieceTheme2D = user[1].pieceTheme2D;
pieceTheme3D = user[1].pieceTheme3D;
currUserRating = user[1].rating;
oppRating = user[0].rating;
}
socket.emit('joinedGame', {
gameID: game.gameId,
player1: game.player1,
player2: game.player2,
fen: game.fen,
pgn: game.pgn,
rejoin: rejoin,
boardTheme2D: boardTheme2D,
pieceTheme2D: pieceTheme2D,
pieceTheme3D: pieceTheme3D,
currUserRating: currUserRating,
oppRating: oppRating
});
});
});
}
// Check to see if game is full; if not, join current user
else if (game.player2 == null) {
game.update({
player2: data.currUser
});
socket.join(game.gameId);
console.log(data.currUser + ' has joined game: ' + game.gameId);
User.findAll({ where: {
[Op.or]: [{ userName: game.player1 }, { userName: data.currUser }]
} }).then(function (user) {
var currUserRating, oppRating, boardTheme2D, pieceTheme2D, pieceTheme3D;
if (user[1].userName == data.currUser) {
boardTheme2D = user[1].boardTheme2D;
pieceTheme2D = user[1].pieceTheme2D;
pieceTheme3D = user[1].pieceTheme3D;
currUserRating = user[1].rating;
oppRating = user[0].rating;
}
else {
boardTheme2D = user[0].boardTheme2D;
pieceTheme2D = user[0].pieceTheme2D;
pieceTheme3D = user[0].pieceTheme3D;
currUserRating = user[0].rating;
oppRating = user[1].rating;
}
socket.emit('joinedGame', {
gameID: game.gameId,
player1: game.player1,
player2: game.player2,
fen: game.fen,
pgn: game.pgn,
rejoin: rejoin,
boardTheme2D: boardTheme2D,
pieceTheme2D: pieceTheme2D,
pieceTheme3D: pieceTheme3D,
currUserRating: currUserRating,
oppRating: oppRating
});
socket.broadcast.to(game.gameId).emit('oppJoined', {
oppName: data.currUser,
oppRating: currUserRating
});
// Let other users know that game is filled
socket.broadcast.emit('gameFilled', { gameID: game.gameId });
});
}
// Game is full
else {
socket.emit('fullGame', { message: 'Game "' + game.gameId + '" is full.' });
console.log('Game "' + game.gameId + '" is full.');
}
}
// Game does not exist
else {
socket.emit('dneGame', { message: 'Such game does not exist.' });
console.log('Game "' + data.gameID + '" does not exist.');
}
});
});
/**
* Handle the turn played by either player and notify the other.
*/
socket.on('playTurn', function (data) {
Game.findOne({ where: { gameId: data.gameID } }).then(function (game) {
var move,
currDateTime = new Date();
if (data.turn == 'w') {
move = game.player1;
}
else {
move = game.player2;
}
currDateTime.setMinutes(currDateTime.getMinutes() + game.moveTimeLimit);
currDateTime.setSeconds(currDateTime.getSeconds() + 1);
game.update({
fen: data.fen,
pgn: data.pgn,
turns: Sequelize.literal('turns + 1'),
move: move,
makeMoveBy: currDateTime.getTime()
});
socket.broadcast.to(game.gameId).emit('turnPlayed', data);
});
});
/**
* Notify the players about the victor.
*/
socket.on('gameEnd', function (data) {
Game.findOne({ where: { gameId: data.gameID } }).then(function (game) {
return game.update({
fen: data.fen,
pgn: data.pgn,
result: data.result
});
}).then(function (game) {
updateUserStat(game);
});
socket.broadcast.to(data.gameID).emit('gameEnded', data);
});
/**
* Player requesting draw. Send request to opponent.
*/
socket.on('offerDraw', function (data) {
socket.broadcast.to(data.gameID).emit('offeredDraw', data);
});
/**
* Player has resigned. Alert opponent.
*/
socket.on('resignGame', function (data) {
socket.broadcast.to(data.gameID).emit('resignedGame');
});
/**
* Move timer.
*/
setInterval(function () {
Game.findAndCountAll({
where: {
[Op.not]: [{ player2: null }],
turns: { [Op.gt]: 0 },
result: null
}, logging: false
}).then(function (results, err) {
var game,
now,
timeRem,
days,
hours,
minutes,
seconds,
timeRemFormatted;
for (var i = 0; i < results.count; i++) {
game = results.rows[i];
now = new Date().getTime();
timeRem = game.makeMoveBy - now;
days = Math.floor(timeRem / (1000 * 60 * 60 * 24));
hours = Math.floor((timeRem % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
minutes = Math.floor((timeRem % (1000 * 60 * 60)) / (1000 * 60));
seconds = Math.floor((timeRem % (1000 * 60)) / 1000);
timeRemFormatted = 'Move Time Left: ' + ('0' + days).slice(-2) + ':' + ('0' + hours).slice(-2) + ':' + ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2)
if (timeRem > 0) {
io.in(game.gameId).emit('moveTimer', { timeRem: timeRemFormatted });
}
else {
if (game.result == null) {
game.update({
result: 'Move Time Expired'
});
}
updateUserStat(game);
socket.in(game.gameId).emit('moveTimeExpired');
}
}
});
}, 1000);
});
function updateUserStat(game) {
var p1Rating,
p2Rating,
k1Factor,
k2Factor;
User.findAndCountAll().then(function(users,error) {
for (var i = 0; i < users.count; i++) {
if (users.rows[i].userName == game.player1) {
p1Rating = users.rows[i].rating;
}
else if (users.rows[i].userName == game.player2) {
p2Rating = users.rows[i].rating;
}
}
console.log('p1 rating: ' + p1Rating);
console.log('p2 rating: ' + p2Rating);
// determine k-factor for p1 and p2
if (p1Rating < 2100) {
k1Factor = 32;
}
else if (p1Rating >= 2100 && p1Rating <= 2400) {
k1Factor = 24;
}
else {
k1Factor = 16;
}
if (p2Rating < 2100) {
k2Factor = 32;
}
else if (p2Rating >= 2100 && p2Rating <= 2400) {
k2Factor = 24;
}
else {
k2Factor = 16;
}
console.log('k1Factor: ' + k1Factor);
console.log('k2Factor: ' + k2Factor);
if (game.result == 'Checkmate' || game.result == 'Move Time Expired' || game.result == 'Resignation') {
if (game.move != game.player1) {
var elo = EloRating.calculate(p1Rating, p2Rating, true, k1Factor);
console.log(game.player1 + ' elo: ' + elo.playerRating + ', ' + game.player2 + ' elo: ' + elo.opponentRating);
// Winner; update user's win count and rating
User.update({
winCount: Sequelize.literal('winCount + 1'),
rating: elo.playerRating
}, { where: { userName: game.player1 } });
// Loser; update user's lose count and rating
User.update({
loseCount: Sequelize.literal('loseCount + 1'),
rating: elo.opponentRating
}, { where: { userName: game.player2 } });
}
else {
var elo = EloRating.calculate(p2Rating, p1Rating, true, k2Factor);
console.log(game.player1 + ' elo: ' + elo.playerRating + ', ' + game.player2 + ' elo: ' + elo.opponentRating);
// Winner; update user's win count
User.update({
winCount: Sequelize.literal('winCount + 1'),
rating: elo.playerRating
}, { where: { userName: game.player2 } });
// Loser; update user's lose count
User.update({
loseCount: Sequelize.literal('loseCount + 1'),
rating: elo.opponentRating
}, { where: { userName: game.player1 } });
}
}
else if (game.result == 'Draw') {
//k1 + [0.5 * expected score] //0.5 is the draw
var expectedScore = EloRating.expected(p1Rating, p2Rating);
var difference = k1Factor + (0.5 * expectedScore);
if (p1Rating > p2Rating) {
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1'),
rating: Sequelize.literal('rating -' + difference)
}, { where: { userName: game.player1 } });
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1'),
rating: Sequelize.literal('rating +' + difference)
}, { where: { userName: game.player2 } });
}
else if (p1Rating < p2Rating) {
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1'),
rating: Sequelize.literal('rating +' + difference)
}, { where: { userName: game.player1 } });
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1'),
rating: Sequelize.literal('rating -' + difference)
}, { where: { userName: game.player2 } });
}
else {
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1')
}, { where: { userName: game.player1 } });
// Update users' draw count
User.update({
drawCount: Sequelize.literal('drawCount + 1')
}, { where: { userName: game.player2 } });
}
}
});
}
function IDGenerator() {
this.length = 8;
this.timestamp = +new Date;
var _getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
this.generate = function () {
var ts = this.timestamp.toString();
var parts = ts.split("").reverse();
var id = "";
for (var i = 0; i < this.length; ++i) {
var index = _getRandomInt(0, parts.length - 1);
id += parts[index];
}
return id;
}
}
}