-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
399 lines (347 loc) · 15.5 KB
/
server.js
File metadata and controls
399 lines (347 loc) · 15.5 KB
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
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const Datastore = require('nedb');
const legalmoves = require('./client/illegalMoveCheck.js');
var port = process.env.PORT || 8080;
const accounts = new Datastore('accounts.db')
accounts.loadDatabase();
app.use(express.static(__dirname));
app.get('/', function(req, res){
res.sendFile(__dirname + '/client/communicationSetup.html');
});
http.listen(port, function(){
console.log('listening on ' + port);
});
var sessions = [];
var gamerooms = [];
var queue = [];
io.on('connection', function(socket) {
socket.on('disconnect', function() {
// console.log('\nA client has disconnected');
});
/* Whenever a new page connects to the server, check its session ID. If it was previously playing a game
redirect it to game.html. Otherwise log them in.
*/
socket.on('validation', function(data) {
// check if they were just redirected from another page
var a = true;
for (item of sessions) {
if (item.sessionID == data.sessionID) {
item.socketID = socket.id;
io.to(socket.id).emit('validation_success', {username: item.username});
a = false;
break;
}
}
if (a) {
io.to(socket.id).emit('validation_failed');
}
// check if they should be playing a game, and if so, give them the signal to start
a = true;
for (item of gamerooms) {
if (item.p1sessionID == data.sessionID) {
item.p1socketID = socket.id;
if (!item.playing) {// if they weren't playing a game before
item.p1ready = true;
if (item.p1ready && item.p2ready) {
item.playing = true;
const wdata = {
yourMove: item.whitesTurn,
board: item.board,
rightCastle: true,
leftCastle: true,
color: 'white',
lastMove: item.lastMove,
opponent: item.p2username,
user: item.p1username,
}
const bdata = {
yourMove: !item.whitesTurn,
board: item.board,
rightCastle: true,
leftCastle: true,
color: 'black',
lastMove: item.lastMove,
opponent: item.p1username,
user: item.p2username,
}
io.to(item.p1socketID).emit('play_game', wdata);
io.to(item.p2socketID).emit('play_game', bdata);
}
break;
} else { //if they disconnected while playing a game
if (socket.handshake.headers.referer.substring(socket.handshake.headers.referer.length - 9) != 'game.html') {
io.to(item.p1socketID).emit('redirect', '/client/game.html');
} else {
const data = {
yourMove: item.whitesTurn,
board: item.board,
rightCastle: item.p1RCastle,
leftCastle: item.p1LCastle,
color: 'white',
lastMove: item.lastMove,
opponent: item.p2username,
user: item.p1username
}
io.to(item.p1socketID).emit('play_game', data);
}
}
}
if (item.p2sessionID == data.sessionID) { //same checks for if they are player 2
item.p2socketID = socket.id;
if (!item.playing) {// if they weren't playing a game before
item.p2ready = true;
if (item.p1ready && item.p2ready) {
item.playing = true;
const wdata = {
yourMove: item.whitesTurn,
board: item.board,
rightCastle: true,
leftCastle: true,
color: 'white',
lastMove: item.lastMove,
opponent: item.p2username,
user: item.p1username,
}
const bdata = {
yourMove: !item.whitesTurn,
board: item.board,
rightCastle: true,
leftCastle: true,
color: 'black',
lastMove: item.lastMove,
opponent: item.p1username,
user: item.p2username
}
io.to(item.p1socketID).emit('play_game', wdata);
io.to(item.p2socketID).emit('play_game', bdata);
}
break;
} else { //if they disconnected while playing a game
if (socket.handshake.headers.referer.substring(socket.handshake.headers.referer.length - 9) != 'game.html') {
io.to(item.p2socketID).emit('redirect', '/client/game.html');
} else {
const data = {
yourMove: !item.whitesTurn,
board: item.board,
rightCastle: item.p2RCastle,
leftCastle: item.p2LCastle,
color: 'black',
lastMove: item.lastMove,
opponent: item.p1username,
user: item.p2username
}
io.to(item.p2socketID).emit('play_game', data);
}
}
}
}
for (item of queue) {//if they disconnected while waiting in queue for a game
if (item.sessionID == data.sessionID) {
item.socketID = socket.id;
break;
}
}
if (queue.length >= 2) {//if a new match can be made
queueFull();
}
});
socket.on('new_login', function(data) {
accounts.find({username: data.username}, function(err, docs) {
if (docs.length == 0) {
io.to(socket.id).emit('login_failure', 'No account with that username');
} else if (docs[0].password != data.password) {
io.to(socket.id).emit('login_failure','Incorrect password');
} else {
//check if they need a new session ID, and issue one if they do
var SSID;
var needSSID = true;
for (item of sessions) {
if (item.username == data.username) {
SSID = item.sessionID;
needSSID = false;
break;
}
}
if (needSSID) {
SSID = generateUniqueSessionID();
sessions.push({username: data.username, sessionID: SSID, socketID: socket.id})
}
io.to(socket.id).emit('login_success', {username: data.username, sessionID: SSID});
}
});
});
socket.on('new_register', function(data) {
accounts.find({username: data.username}, function(err, docs) {
if (docs.length == 0) { // username is availiable
accounts.insert({username: data.username, password: data.password});
var SSID = generateUniqueSessionID();
sessions.push({username: data.username, sessionID: SSID, socketID: socket.id})
io.to(socket.id).emit('register_success', {username: data.username, sessionID: SSID});
} else { //username already exists
io.to(socket.id).emit('register_failure', 'Username already in use!');
}
});
});
socket.on('logout', function(data) {
for (item of sessions) {//remove them from current sessions
if (item.sessionID == data.sessionID) {
sessions.splice(item, 1);
break;
}
}
for (var i = 0; i < gamerooms.length; i++) {//remove them from all games, and end the games
if (gamerooms[i].p1sessionID == data.sessionID) {
io.to(gamerooms[i].p2socketID).emit('gameover', {textResult: 'Your opponent disconnected', numResult: '0-1'});
gamerooms.splice(gamerooms[i], 1);
break;
} else if (gamerooms[i].p2sessionID == data.sessionID) {
io.to(gamerooms[i].p1socketID).emit('gameover', {textResult: 'Your opponent disconnected', numResult: '1-0'});
gamerooms.splice(gamerooms[i], 1);
break;
}
}
for (item of queue) {//remove them from queue
if (item.sessionID == data.sessionID) {
queue.splice(item, 1);
break;
}
}
io.to(socket.id).emit('redirect', '/client/loginRegister.html');
});
socket.on('thisIsMySessionID', function(data) {//runs when client is attempting to connect
if (data.sessionID.length != 20) {
io.to(socket.id).emit('redirect', '/client/loginRegister.html');
} else {
io.to(socket.id).emit('redirect', '/client/home.html');
}
});
socket.on('wish_to_play', function(data) {
for (item of sessions) {
if (item.sessionID == data.sessionID) {
queue.push(item);
break;
}
}
io.to(socket.id).emit('redirect', '/client/queue.html');
});
//called after white makes a move. Update any server info about the game, and check if the game should end.
socket.on('white_moved', function(data) {
for (item of gamerooms) {
if (item.p1sessionID == data.sessionID) {
item.board = legalmoves.movepiece(item.board, data.move.from, data.move.to, data.move.piece);
item.whitesTurn = false;
if (data.move.from.x == 4 && data.move.from.y == 0) {
item.p1LCastle = false;
item.p1RCastle = false;
}
if (data.move.from.x == 0 && data.move.from.y == 0) {
item.p1LCastle = false;
}
if (data.move.from.x == 7 && data.move.from.y == 0) {
item.p1RCastle = false;
}
item.lastMove = data.move;
io.to(item.p2socketID).emit('make_a_move', {lastMove: data.move});
var lMoves = legalmoves.getLegalMoves(item.board, 'b', item.lastMove, item.p1LCastle, item.p1RCastle);
if (lMoves.length == 0) {
if (legalmoves.kingInCheck(item.board, 'b')) {
io.to(item.p1socketID).emit('gameover', {textResult: 'You won!', numResult: '1-0'});
io.to(item.p2socketID).emit('gameover', {textResult: 'You lost.', numResult: '0-1'});
} else {
io.to(item.p1socketID).emit('gameover', {textResult: 'Stalemate.', numResult: '0.5-0.5'});
io.to(item.p2socketID).emit('gameover', {textResult: 'Stalemate.', numResult: '0.5-0.5'});
}
gamerooms.splice(item, 1);
}
}
}
});
socket.on('black_moved', function(data) {
for (item of gamerooms) {
if (item.p2sessionID == data.sessionID) {
item.board = legalmoves.movepiece(item.board, data.move.from, data.move.to, data.move.piece);
item.whitesTurn = true;
if (data.move.from.x == 4 && data.move.from.y == 7) {
item.p2LCastle = false;
item.p2RCastle = false;
}
if (data.move.from.x == 0 && data.move.from.y == 7) {
item.p2LCastle = false;
}
if (data.move.from.x == 7 && data.move.from.y == 7) {
item.p2RCastle = false;
}
item.lastMove = data.move;
io.to(item.p1socketID).emit('make_a_move', {lastMove: data.move});
var lMoves = legalmoves.getLegalMoves(item.board, 'w', item.lastMove, item.p1LCastle, item.p1RCastle);
if (lMoves.length == 0) {
if (legalmoves.kingInCheck(item.board, 'w')) {
io.to(item.p1socketID).emit('gameover', {textResult: 'You lost.', numResult: '0-1'});
io.to(item.p2socketID).emit('gameover', {textResult: 'You win!', numResult: '1-0'});
} else {
io.to(item.p1socketID).emit('gameover', {textResult: 'Stalemate.', numResult: '0.5-0.5'});
io.to(item.p2socketID).emit('gameover', {textResult: 'Stalemate.', numResult: '0.5-0.5'});
}
gamerooms.splice(item, 1);
}
}
}
});
});
/* Is called when length of queue > 2.
When it is, setup a new game, add the players to a gameroom and remove them from the queue
*/
function queueFull() {
var room = {
p1username: queue[0].username,
p1sessionID: queue[0].sessionID,
p1socketID: queue[0].socketID,
p1ready: false,
p1LCastle: true,
p1RCastle: true,
p2username: queue[1].username,
p2sessionID: queue[1].sessionID,
p2socketID: queue[1].socketID,
p2ready: false,
p2LCastle: true,
p2RCastle: true,
// roomID: queue[0].sessionID + '-' + queue[1].sessionID,
board: [['wr','wn','wb','wq','wk','wb','wn','wr'],
['wp','wp','wp','wp','wp','wp','wp','wp'],
['__','__','__','__','__','__','__','__'],
['__','__','__','__','__','__','__','__'],
['__','__','__','__','__','__','__','__'],
['__','__','__','__','__','__','__','__'],
['bp','bp','bp','bp','bp','bp','bp','bp'],
['br','bn','bb','bq','bk','bb','bn','br']],
whitesTurn: true,
playing: false,
lastMove: {from: {x: 0, y: 0}, to: {x: 0, y: 0}},
};
gamerooms.push(room);
io.to(room.p1socketID).emit('redirect', '/client/game.html');
io.to(room.p2socketID).emit('redirect', '/client/game.html');
queue.splice(queue[0], 1);
queue.splice(queue[0], 1);
}
//generate random string of 20 characters until one is made that has not been taken
function generateUniqueSessionID() {
while (true) {
var temp = makeid();
if (!sessions.find(row => row.sessionID == temp)) {
break;
};
}
return temp;
}
function makeid() {
var result = '';
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < 20; i++) {
result += chars.charAt(Math.floor(Math.random() * 62));
}
return result;
}