-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
561 lines (472 loc) · 13.7 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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var unpairedConnections = []; // socket objects of players not yet assigned to a game
var gameIdToGameState = {}; // maps game id to the state of the game
var socketIdToData = {}; // maps player socket ids to game data (current game id, opponent, username)
var lastGameId = 0; // most recent game id assigned
var size = 19; // board size
var StateEnum = Object.freeze({EMPTY: 0, BLACK: 1, WHITE: -1});
var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
var tagOrComment = new RegExp(
'<(?:'
// Comment body.
+ '!--(?:(?:-*[^->])*--+|-?)'
// Special "raw text" elements whose content should be elided.
+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
+ '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
// Regular name
+ '|/?[a-z]'
+ tagBody
+ ')>',
'gi');
// For input santitation
function removeTags(html) {
var oldHtml;
do {
oldHtml = html;
html = html.replace(tagOrComment, '');
} while (html !== oldHtml);
return html.replace(/</g, '<');
}
app.set('port', process.env.PORT || 5000);
server.listen(app.get('port'), function() {
console.log('Server is running on port ' + app.get('port'));
});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
console.log('Socket connected');
// Called when the user submits a username and intends to join the lobby
socket.on('join lobby', function(username) {
joinLobby(username);
});
// Called when one of the players sends a message
socket.on('send message', function(data) {
sendMessageToOpponent(data);
});
// Called when a player disconnects. Either removes them from
// available matches or notifies their opponent they forfeited
socket.on('disconnect', function(data) {
disconnectUser();
});
// Receives a game move from a player
// 1. Updates the game state
// 2. Notifies players of move
socket.on('place piece', function(data) {
placePiece(data.x, data.y, data.color);
});
// Called when a player presses the request rematch button after a game ends
socket.on('request rematch', function() {
requestRematch();
});
// Requests a rematch or immediately starts on if the opponent has already requested one too
function requestRematch() {
// Prevents crash
if (!(socket.id in socketIdToData)) {
return;
}
// Check if the opponent also wanted a rematch
var opponent = socketIdToData[socket.id].opponent;
var opponentWantsRematch = socketIdToData[opponent.id].rematch;
// If opponent wants a rematch, creates one immediately
// Otherwise, waits for the opponent
if (opponentWantsRematch) {
// Resets rematch values for the next game
socketIdToData[opponent.id].rematch = false;
socketIdToData[socket.id].rematch = false;
startRematch();
} else {
socketIdToData[socket.id].rematch = true;
}
}
// Restarts a new game
// Slightly different from completely starting a new game
// because the same opponents will be used
function startRematch() {
// Assigns a new game id
var gameId = getGameId();
// Same opponent as before
var opponent = socketIdToData[socket.id].opponent;
// Sets the new id in our player map
socketIdToData[socket.id].gameId = gameId;
socketIdToData[opponent.id].gameId = gameId;
// Initializes a new game state
var gameState = createGameState();
gameIdToGameState[gameId] = gameState;
// Adds players to the new game room
socket.join(gameId);
opponent.join(gameId);
// Tells each player we're starting a rematch and who starts
var rand = Math.random() >= 0.5;
socket.emit('starting rematch', {start: rand});
opponent.emit('starting rematch', {start: !rand});
}
// Allows the current socket to join the lobby with
// the specified username. Tries to pair it with an opponent
function joinLobby(username) {
socketIdToData[socket.id] = {username: username};
// Couldn't find a match, join the lobby and wait
if (!tryPairUser()) {
unpairedConnections.push(socket);
}
}
// Sends a message to the player's opponent
function sendMessageToOpponent(message) {
// Prevents crash
if (socket.id in socketIdToData) {
var sanitizedMessage = removeTags(message);
var opponent = socketIdToData[socket.id].opponent;
opponent.emit('new message', sanitizedMessage);
}
}
// Removes the player from the current game or the lobby
function disconnectUser() {
if (contains(unpairedConnections, socket)) {
// Player was in the lobby, no longer available to pair
unpairedConnections.splice(unpairedConnections.indexOf(socket), 1);
} else if (socket.id in socketIdToData) {
// Player was in a game, notify their opponent
var gameId = socketIdToData[socket.id].gameId;
io.to(gameId).emit('opponent left');
// Remove it from socketIdToData
delete socketIdToData[socket.id];
}
console.log('Socket disconnected');
}
// When a player places a piece on a board
function placePiece(x, y, color) {
// Prevents crash
if (!(socket.id in socketIdToData)) {
return;
}
// get player game id
var gameId = socketIdToData[socket.id].gameId;
// update the game state
setState(gameId, x, y, color);
// notify the players ot the state change
io.to(gameId).emit('piece placed', {x: x, y: y, color: color});
// checks if the player won by placing this piece down
if (playerWon(gameId, x, y, color)) {
gameOver();
}
// if there are pieces to remove
else {
var trapped = checkTrappedPieces(gameId, x, y, color);
if (trapped) {
// remove them locally
setState(gameId, trapped.x1, trapped.y1, StateEnum.EMPTY);
setState(gameId, trapped.x2, trapped.y2, StateEnum.EMPTY);
// increment trapped count
var count = incrementTrappedCount(gameId, color);
// notify players to remove pieces
io.to(gameId).emit('trapped pieces',
{
x1: trapped.x1,
y1: trapped.y1,
x2: trapped.x2,
y2: trapped.y2,
color: trapped.color,
count: count
}
);
// game is over if 5 pairs are trapped
if (count == 5) {
gameOver();
}
}
}
}
// Notifies the players that the game is over
// and the current socket won
function gameOver() {
socket.emit('game over', {won: true});
// notify loser
var opponent = socketIdToData[socket.id].opponent;
opponent.emit('game over', {won: false});
// sets their rematch boolean values
socketIdToData[socket.id].rematch = false;
socketIdToData[opponent.id].rematch = false;
// TODO remove players from the game room
}
// Increments the count of the number of pairs color
// has trapped, and returns the new count
function incrementTrappedCount(gameId, color) {
var gameState = gameIdToGameState[gameId];
if (color == StateEnum.BLACK) {
gameState.bTrapped = gameState.bTrapped + 1;
return gameState.bTrapped;
} else {
gameState.wTrapped = gameState.wTrapped + 1;
return gameState.wTrapped;
}
}
// Checks if there are pieces that were just trapped as the result
// of the placement of the piece at (x,y)
function checkTrappedPieces(gameId, x, y, color) {
var gameState = gameIdToGameState[gameId];
var opponentColor = -1 * color;
// north
if (y-3 >= 0) {
if (gameState[x][y-1] == opponentColor
&& gameState[x][y-2] == opponentColor
&& gameState[x][y-3] == color) {
return {
x1: x,
y1: y-1,
x2: x,
y2: y-2,
color: opponentColor
};
}
}
// north east
if (y-3 >= 0 && x+3 < size) {
if (gameState[x+1][y-1] == opponentColor
&& gameState[x+2][y-2] == opponentColor
&& gameState[x+3][y-3] == color) {
return {
x1: x+1,
y1: y-1,
x2: x+2,
y2: y-2,
color: opponentColor
};
}
}
// east
if (x+3 < size) {
if (gameState[x+1][y] == opponentColor
&& gameState[x+2][y] == opponentColor
&& gameState[x+3][y] == color) {
return {
x1: x+1,
y1: y,
x2: x+2,
y2: y,
color: opponentColor
};
}
}
// south east
if (y+3 < size && x+3 < size) {
if (gameState[x+1][y+1] == opponentColor
&& gameState[x+2][y+2] == opponentColor
&& gameState[x+3][y+3] == color) {
return {
x1: x+1,
y1: y+1,
x2: x+2,
y2: y+2,
color: opponentColor
};
}
}
// south
if (y+3 < size) {
if (gameState[x][y+1] == opponentColor
&& gameState[x][y+2] == opponentColor
&& gameState[x][y+3] == color) {
return {
x1: x,
y1: y+1,
x2: x,
y2: y+2,
color: opponentColor
};
}
}
// south west
if (y+3 < size && x-3 >= 0) {
if (gameState[x-1][y+1] == opponentColor
&& gameState[x-2][y+2] == opponentColor
&& gameState[x-3][y+3] == color) {
return {
x1: x-1,
y1: y+1,
x2: x-2,
y2: y+2,
color: opponentColor
};
}
}
// west
if (x-3 >= 0) {
if (gameState[x-1][y] == opponentColor
&& gameState[x-2][y] == opponentColor
&& gameState[x-3][y] == color) {
return {
x1: x-1,
y1: y,
x2: x-2,
y2: y,
color: opponentColor
};
}
}
// north west
if (y-3 >= 0 && x-3 >= 0) {
if (gameState[x-1][y-1] == opponentColor
&& gameState[x-2][y-2] == opponentColor
&& gameState[x-3][y-3] == color) {
return {
x1: x-1,
y1: y-1,
x2: x-2,
y2: y-2,
color: opponentColor
};
}
}
// no trapped pieces
return undefined;
}
// Returns true if the player using color has won
// by placing a piece at the (x, y) position in the
// game corresponding to gameId, false otherwise
function playerWon(gameId, x, y, color) {
var gameState = gameIdToGameState[gameId];
// Only need to check the space with a radius of 4
for (let i = x-4; i <= x+4; i++) {
for (let j = y-4; j <= y+4; j++) {
if (winningTrail(gameState, i, j, color)) {
return true;
}
}
}
return false;
}
// Returns true if the current piece is the leftmost
// piece in a trail of 5 of the same color
// Only need to check down, right, diag up right, diag down right
// If there is a trail of 5 and the current piece is not the left-most one,
// we will eventually find the left most piece
function winningTrail(board, x, y, color) {
// Check for bounds
if (x < 0 || y < 0 || x >= size || y >= size) {
return false;
}
return checkDownTrail(board, x, y, color)
|| checkRightTrail(board, x, y, color)
|| checkUpRightTrail(board, x, y, color)
|| checkDownRightTrail(board, x, y, color);
}
// Returns true if (x,y) is the start of a trail
// of 5 same colored pieces downwards
function checkDownTrail(board, x, y, color) {
// bounds check
if (y+4 >= size) {
return false;
}
for (let i = 0; i <= 4; i++) {
if (board[x][y+i] != color) {
return false;
}
}
return true;
}
// Returns true if (x,y) is the start of a trail of
// 5 same colored pieces to the right
function checkRightTrail(board, x, y, color) {
// bounds check
if (x+4 >= size) {
return false;
}
for (let i = 0; i <= 4; i++) {
if (board[x+i][y] != color) {
return false;
}
}
return true;
}
// Returns true if (x,y) is the start of a trail of
// 5 same colored pieces diag up right
function checkUpRightTrail(board, x, y, color) {
// bounds check
if (x+4 >= size || y-4 < 0) {
return false;
}
for (let i = 0; i <= 4; i++) {
if (board[x+i][y-i] != color) {
return false;
}
}
return true;
}
// Returns true if (x,y) is the start of a trail of
// 5 same colored pieces diag down right
function checkDownRightTrail(board, x, y, color) {
// bounds check
if (x+4 >= size || y+4 >= size) {
return false;
}
for (let i = 0; i <= 4; i++) {
if (board[x+i][y+i] != color) {
return false;
}
}
return true;
}
// Sets the (x, y) position to color in the game state
// corresponding to gameId
function setState(gameId, x, y, color) {
gameIdToGameState[gameId][x][y] = color;
}
// Array contains helper function
function contains(array, item) {
return array.indexOf(item) >= 0;
}
// Assigns a new game id
function getGameId() {
lastGameId = lastGameId + 1;
return lastGameId;
}
// Matches current player with opponent who was waiting in the lobby
function matchPlayer(opponent) {
// Removes opponent from unpaired list
unpairedConnections.splice(unpairedConnections.indexOf(opponent), 1);
// Assigns a game id
var gameId = getGameId();
// Adds the players to our player map
socketIdToData[socket.id].gameId = gameId;
socketIdToData[opponent.id].gameId = gameId;
socketIdToData[socket.id].opponent = opponent;
socketIdToData[opponent.id].opponent = socket;
// Initializes the game state (local copy of board)
var gameState = createGameState();
gameIdToGameState[gameId] = gameState;
// Adds players to the game room
socket.join(gameId);
opponent.join(gameId);
// Tells each player we found a match and their opponent's username
var rand = Math.random() >= 0.5;
socket.emit('found match', {msg: socketIdToData[opponent.id].username, start: rand});
opponent.emit('found match', {msg: socketIdToData[socket.id].username, start: !rand});
}
// Creates a 2D array storing piece positions
function createGameState() {
var arr = new Array(size);
for (i = 0; i < size; i++) {
arr[i] = new Array(size);
for (j = 0; j < size; j++) {
arr[i][j] = StateEnum.EMPTY;
}
}
arr.bTrapped = 0;
arr.wTrapped = 0;
return arr;
}
// Tries to find a game match for the user that just connected
function tryPairUser() {
// If someone is waiting for a match, we have an opponent
if (unpairedConnections.length > 0) {
matchPlayer(unpairedConnections[0]);
return true;
} else {
return false;
}
}
});