-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
571 lines (509 loc) · 15.8 KB
/
app.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
562
563
564
565
566
567
568
569
570
571
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, connect = require('connect')
, user = require('./routes/user')
, http = require('http')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, path = require('path');
var app = express();
var io = require('socket.io');
var nextID = 1;
var users = [];
// usernames which are currently connected to the chat
var usernames = {};
function findById(id, fn) {
var idx = id - 1;
if (users[idx]) {
fn(null, users[idx]);
} else {
fn(new Error('User ' + id + ' does not exist'));
}
}
function findUserIndexByID(id) {
for (var i = 0; i < users.length; i++) {
if (Number(users[i].id) === Number(id)) {
return i;
}
}
}
function findByUsername(username, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username) {
return fn(null, user);
}
}
return fn(null, null);
}
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/users');
}
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
function(username, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
return done(null, user);
});
});
}
));
app.configure(function(){
app.set('port', 8000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
var serverCrosswords = [];
var clientCrosswords = [];
////////// Server only logic //////////
var buildGrid = function(obj, gameID) {
var grid = [];
// Create empty array for guessed words
var gridGuessed = [];
var gridCorrect = [];
for (i=0; i < 225; i++){
gridGuessed.push('');
gridCorrect.push(0);
}
// initialize acrossWordGrid with array of 255 empty strings.
var acrossWordGrid = [];
for (i=0; i < 225; i++){
acrossWordGrid.push('');
}
// for each word, find gridnum
for (i=0; i < obj.answers.across.length; i++) {
word = obj.answers.across[i];
questionNum = Number(obj.clues.across[i].split('.')[0]);
start = obj.gridnums.indexOf(questionNum);
// add wordnum to all letters of word
for (x=start; x < start + obj.answers.across[i].length; x++) {
acrossWordGrid[x] = i;
}
}
// initialize downWordGrid with array of 255 empty strings.
var downWordGrid = [];
for (i=0; i < 225; i++){
downWordGrid.push('');
}
// for each word, find gridnum
for (i=0; i < obj.answers.down.length; i++) {
word = obj.answers.down[i];
questionNum = Number(obj.clues.down[i].split('.')[0]);
start = obj.gridnums.indexOf(questionNum);
end = start + (word.length * 15);
// add wordnum to all letters of word
for (x=start; x < end + obj.answers.down[i].length; x += 15) {
downWordGrid[x] = i;
}
}
// Loop through and process square objects
for (i=0; i < 225; i++){
// initialize attributes of square
var letter =obj.grid[i];
var num = obj.gridnums[i];
var active = 'active';
var wordAcross = '';
var wordDown = '';
// disable it is an empty square
if (letter === ".") {
letter = '';
active = 'disabled';
gridCorrect[i] = 1; // the blank ones are already what they need to be
}
// otherwise add words letter belongs to
else {
if (acrossWordGrid[i] !== '') {
wordAcross = acrossWordGrid[i];
}
if (downWordGrid[i] !== '') {
wordDown = downWordGrid[i];
}
}
if (num === 0) {
num = '';
}
item = {letter: '', num: num, active: active, index:i, wordAcross:wordAcross, wordDown: wordDown};
grid.push(item);
}
console.log('Game loaded for: ' + gameID);
clientCrossword = {
gameID: gameID,
grid: grid,
answers: obj.answers,
guessed: gridGuessed,
correct: gridCorrect,
gridnums: obj.gridnums,
across: obj.clues.across,
down: obj.clues.down,
date: obj.date
};
serverCrossword = {
gameID: gameID,
answers: obj.answers,
grid: grid,
guessed: gridGuessed,
correct: gridCorrect,
gridnums: obj.gridnums,
across: obj.clues.across,
down: obj.clues.down
};
replace = -1;
for(i=0; i<clientCrosswords.length; i++) {
if (clientCrosswords[i].gameID === gameID) {
replace = i;
}
}
if (replace >= 0 ) {
clientCrosswords[replace] = clientCrossword;
serverCrosswords[replace] = serverCrossword;
io.sockets.emit('updategrid', clientCrosswords[replace]);
}
else {
clientCrosswords.push(clientCrossword);
serverCrosswords.push(serverCrossword);
}
};
var usedPuzzles = [];
// Get a random crossword from xwordinfo
var getPuzzle = function(gameID, usedPuzzles) {
http.get("http://www.xwordinfo.com/JSON/Data.aspx?date=random", function(res) {
console.log("Got response: " + res.statusCode);
var data = '';
res.on('data', function (chunk){
data += chunk;
});
res.on('end',function(){
var obj = JSON.parse(data);
//console.log(obj);
if (obj.size.rows === 15
&& usedPuzzles['front'] != obj.date
&& usedPuzzles['back'] != obj.date
&& usedPuzzles['left'] != obj.date
&& usedPuzzles['right'] != obj.date
&& usedPuzzles['top'] != obj.date
&& usedPuzzles['bottom'] != obj.date ) {
console.log('its good');
buildGrid(obj, gameID);
usedPuzzles[gameID] = obj.date;
console.log('face ' + gameID + ' is using puzzle ' + usedPuzzles[gameID]);
}
else {
console.log('no good');
getPuzzle(gameID, usedPuzzles);
}
});
});
};
var findSideByID = function(id) {
for (var i = 0; i < serverCrosswords.length; i++) {
if (serverCrosswords[i].gameID === id) {
return serverCrosswords[i];
}
}
};
function findIndexByClue(crossword, clue){
console.log(clue);
if (!clue){
return false;
}
var clueid = parseInt(clue.split('.')[0]);
return crossword.gridnums.indexOf(clueid);
}
function getWordFromIndex(crossword, direction, index){
var word = {
complete: false,
letters : '',
index : null,
first : null
};
console.log(index);
if (direction == 'vertical'){
while (index >= 15){
if (crossword.grid[index-15].active == 'disabled'){
break;
}else {
index-=15;
}
}
var start = index;
while (index < crossword.grid.length){
word.letters += crossword.guessed[index] || ' ';
if (crossword.grid[index+15] && crossword.grid[index+15].active == 'disabled'){
break;
}else {
index+=15;
}
}
console.log(start);
word.index = crossword.gridnums[start]-1;
}else {
var place = index % 15;
var min = index - place;
var max = index + (15-place);
while (index > min){
if (crossword.grid[index-1].active == 'disabled'){
break;
}else {
index--;
}
}
var start = index;
console.log(start);
while (index < crossword.grid.length){
word.letters += crossword.guessed[index] || ' ';
if (crossword.grid[index+1] && crossword.grid[index+1].active == 'disabled'){
break;
}else {
index++;
}
}
word.index = crossword.gridnums[start]-1;
}
if (word.letters.indexOf(' ') == -1){
word.complete = true;
}
word.first = start;
return word;
}
function checkWord(data){
if (!data ||
!data.index){
return;
}
var crossword = findSideByID(data.side);
var result = '';
var intersections = [];
var intersection = data.direction == 'horizontal' ? 'vertical' : 'horizontal';
if (data.direction === 'horizontal') {
if (data.guess.toUpperCase() === crossword.answers.across[data.index]) {
var userDidFinish = false;
var i = findIndexByClue(crossword, crossword.across[data.index]);
if (i=== false) {
console.log('THIS SHOULD NEVER HAPPEN1');;
console.log(data);
return;
}
for (var l = data.guess.length+i; i < l; i++){
if (crossword.correct[i] == 0){
crossword.correct[i] = 1;
intersections.push(getWordFromIndex(crossword, intersection, i));
userDidFinish = true;
}
}
if (userDidFinish){
result = 'correct';
}else {
result = 'cheating';
}
}
else {
result = 'incorrect';
var i = findIndexByClue(crossword, crossword.across[data.index]);
if (i=== false) {
console.log('THIS SHOULD NEVER HAPPEN2');;
console.log(data);
return;
}
for (var l = data.guess.length+i; i < l; i++){
if (crossword.correct[i] !== 1){
crossword.guessed[i] = '';
}
}
}
}
else if (data.direction === 'vertical') {
if (data.guess.toUpperCase() === crossword.answers.down[data.index]) {
var userDidFinish = false;
var i = findIndexByClue(crossword, crossword.down[data.index]);
if (i=== false) {
console.log('THIS SHOULD NEVER HAPPEN3');;
console.log(data);
return;
}
for (var l = data.guess.length*15+i; i < l; i+=15){
if (crossword.correct[i] == 0){
crossword.correct[i] = 1;
intersections.push(getWordFromIndex(crossword, intersection, i));
userDidFinish = true;
}
}
if (userDidFinish){
result = 'correct';
}else {
result = 'cheating';
}
}
else {
result = 'incorrect';
var i = findIndexByClue(crossword, crossword.down[data.index]);
if (i=== false) {
console.log('THIS SHOULD NEVER HAPPEN4');;
console.log(data);
return;
}
for (var l = data.guess.length*15+i; i < l; i+=15){
if (crossword.correct[i] !== 1){
crossword.guessed[i] = '';
}
}
}
}
if (result === 'correct') {
findById(data.user, function(err, user) {
if (user) {
var newScore = user.score + data.guess.length;
user.score = newScore;
usernames[user.id].score = newScore;
io.sockets.emit('updateusers', usernames);
if (crossword.correct.indexOf(0) === -1) {
console.log('side complete');
getPuzzle(data.side, usedPuzzles);
}
}
});
}
io.sockets.emit('guessresults', {data: data, result: result});
data.direction = intersection;
for(var i in intersections){
console.log(intersections[i]);
if (!intersections[i].complete){
continue;
}
data.firstSquare = intersections[i].first+"";
data.guess = intersections[i].letters+"";
data.index = intersections[i].index*1;
checkWord(data);
}
}
getPuzzle('front', usedPuzzles);
getPuzzle('back', usedPuzzles);
getPuzzle('left', usedPuzzles);
getPuzzle('right', usedPuzzles);
getPuzzle('top', usedPuzzles);
getPuzzle('bottom', usedPuzzles);
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/register', function(req, resp){
var username = req.body.username.replace(/(<([^>]+)>)/ig,"");
var user = {id: nextID, score: 0, username: username};
users.push(user);
nextID++;
// user is the user instance you just registered and created
req.logIn(user, function(err) {
if (err) {
return err;
}
// login success!
resp.redirect('/');
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io = io.listen(server);
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(data){
// we store the username in the socket session for this client
socket.username = data.username;
socket.userID = data.id;
socket.userColor = data.color;
findById(socket.userID, function(err, user) {
if (user) {
usernames[socket.userID] = {id: socket.userID, username: socket.username, score: user.score, color: socket.userColor};
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
for (i=0; i < clientCrosswords.length; i++) {
socket.emit('updategrid', clientCrosswords[i]);
}
}
else {
//socket.emit('refreshuser', data.id);
}
});
});
socket.on('updateSelection', function(data) {
console.log('user #' + data.user + ' has selected a word');
io.sockets.emit('updateSelections', data);
});
socket.on('checkword', checkWord);
socket.on('sendletter', function (data) {
var crossword = findSideByID(data.side);
if (!crossword){
return;
}
crossword.guessed[data.index] = data.letter;
socket.broadcast.emit('updateletter', data);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.userID];
//var userIndex = findUserIndexByID(socket.userID);
//users.splice(userIndex,1);
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});