-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1768 lines (1502 loc) · 47.5 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//TODO: buzzing in immediately when question opens causes question timer to go down/question repeat
//ipads getting blocked out of answering
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
app.use(express.static(__dirname + '/'));
app.get('/home', function(req, res){
//res.sendFile(__dirname + '/index.html');
res.sendFile(__dirname + '/html/game_select.html');
});
app.get('/game', function(req, res){
res.sendFile(__dirname + '/html/index.html');
});
app.get('/player', function(req, res){
res.sendFile(__dirname + '/html/player_field.html');
});
//select socket
var playerSelect = io.of('/home');
//game socket
var gameSpc = io.of('/game');
//player socket
var playerSpc = io.of('/player');
//babyparse is deprecated now
var Baby = require('papaparse');
var gameData = new Array();
var players = new Array();
var questions = new Array();
var curQuestionId;
var curActivePlayer; //player who holds the current lead for picking questions
var file = __dirname + '/data/JEOPARDY_CSV_test.csv';
var lastNameFile = __dirname + '/data/last_name_stripped.csv';
var gameHistory = __dirname + '/data/games_played.csv';
var gameHighScore = __dirname + '/data/game_high_score.csv';
var buzzerFlipped = false;
var buzzedInPlayerName; //tracks player currently answering questions
//TIMERS
var roundTimerObject;
const ROUND_TIME = 600;//600;
var ANSWER_TIME = 15;
var roundTimer = ROUND_TIME;
var ROUND_QUESTIONS = 30;
var DECADE = "10s";
var AIRDATE = "0";
var GAME_ID = 0;
var questionTimer = null;
var questionTimerCount = 6;
var buzzedInTimer = null;
var buzzedInTimerCount = ANSWER_TIME;
var dailyDoubleTimer = null;
var dailyDoubleTimerCount = ANSWER_TIME;
var isSecondRound = false;
var finalJeopardyCheck = false;
var newGameCounter = 0;
var gameState = {"active": false};
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/clues.db');
class Player
{
constructor(name)
{
this._name = name;
this._score = 0;
this._isActive = false;
this._givenAnswer = false;
this._finalJeopardyBet = 0;
}
get name()
{
return this._name;
}
get score()
{
return this._score;
}
set score(score)
{
this._score = score;
}
get finalJeopardyBet()
{
return this._finalJeopardyBet;
}
set finalJeopardyBet(bet)
{
this._finalJeopardyBet = bet;
}
get active()
{
return this._isActive;
}
set isActive(active)
{
this._isActive = active;
}
get givenAnswer()
{
return this._givenAnswer;
}
set givenAnswer(answerGiven)
{
this._givenAnswer = answerGiven;
}
}
class Question
{
constructor(category, value, question, answer, dailyDouble, questionId, mediaLink, round)
{
this._category = category;
this._value = value;
this._question = question;
this._answer = answer;
this._dailyDouble = dailyDouble;
this._questionId = questionId;
this._mediaLink = mediaLink;
this._mediaType = "none";
this._isProperName = false;
this._round = round;
}
get round()
{
return this._round;
}
get category()
{
return this._category;
}
get question()
{
return this._question;
}
set question(newQuestion)
{
this._question = newQuestion;
}
get questionId()
{
return this._questionId;
}
set questionId(newQuestionId)
{
this._questionId = newQuestionId;
}
get isProperName()
{
return this._isProperName;
}
set isProperName(properName){
this._isProperName = properName;
}
get answer()
{
return this._answer;
}
set answer(newAnswer)
{
this._answer = newAnswer;
}
get mediaLink()
{
return this._mediaLink;
}
set mediaLink(newLink)
{
this._mediaLink = newLink;
}
get mediaType()
{
return this._mediaType;
}
set mediaType(media)
{
this._mediaType = media;
}
get dailyDouble()
{
return this._dailyDouble;
}
set dailyDouble(valueDD)
{
this._dailyDouble = valueDD;
}
get value()
{
return this._value;
}
set value(value)
{
this._value = value;
}
}
function parseMediaType(media)
{
var urlLink = media;
var mediaType = "none";
if (urlLink)//link exists
{
// Use a regular expression to trim everything before final dot
var extension = urlLink.replace(/^.*\./, '');
var extension = extension.toLowerCase();
console.log("EXTENSION TRIM IS " + extension);
switch(extension) {
case 'jpg':
mediaType = "image";
break;
case 'jpeg':
mediaType = "image";
break;
case 'png':
mediaType = "image";
break;
case 'wmv':
mediaType = "video_wmv";
break;
case 'mp4':
mediaType = "video_mp4";
break;
case 'mp3':
mediaType = "audio";
break;
case 'wav':
mediaType = "audio";
break;
case 'aiff':
mediaType = "audio";
break;
default:
mediaType = "none";
}
}
return mediaType;
}
function parseAnswer(answer)
{
//remove any information in brackets
var newAnswer = answer.replace(/ *\([^)]*\) */g, "");
newAnswer = newAnswer.toUpperCase();
var tempActualAnswerSearch = newAnswer.substring(0,1);
var tempActualAnswerSearchEnd = newAnswer.substring((newAnswer.length - 1), newAnswer.length);
if (tempActualAnswerSearch == "\"" && tempActualAnswerSearchEnd == "\""){
newAnswer = newAnswer.substring(1, (newAnswer.length-1));
}
tempActualAnswerSearch = newAnswer.substring(0, 2);
if (tempActualAnswerSearch == "A "){
newAnswer = newAnswer.substring(2, newAnswer.length);
newAnswer = newAnswer.trim();
}
tempActualAnswerSearch = newAnswer.substring(0, 3);
if (tempActualAnswerSearch == "AN ") //remove the
{
newAnswer = newAnswer.substring(3, newAnswer.length);
newAnswer = newAnswer.trim();
}
if (tempActualAnswerSearch == "THE") //remove the
{
newAnswer = newAnswer.substring(3, newAnswer.length);
newAnswer = newAnswer.trim();
}
return newAnswer;
}
checkForFullGame();
function checkForFullGame(){
//TODO COUNT RESULTS FROM DB QUERY
}
/*DOWNLOAD REQUIRED IMAGES*/
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback, type){
console.log("DOWNLOAD: " + filename);
console.log("TYPE: " + type);
console.log("URI: " + uri);
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream('./temp-media/' + type + '/' + filename)).on('close', callback);
});
};
var curRoomCodes = new Array();
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ');
playerSelect.on('connection', function(socket){
curRoomCodes.push(randomString(4, rString));
socket.on('room code sent', function(roomCode){
console.log(curRoomCodes);
var _roomCode = roomCode.toUpperCase();
console.log("ROOM CODE SENT " + _roomCode);
if(curRoomCodes.indexOf(_roomCode) != -1){
socket.emit('room code validated', true);
socket.join(_roomCode);
socket.emit('send to room', "http://localhost:3000/player");
}
else{
socket.emit('room code validated', false);
}
});
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
gameSpc.on('connection', function(socket){
//buzzers on/off
socket.on('open buzzer', function () {
openTheBuzzer();
});
socket.on('close buzzer', function () {
playerSpc.emit('close buzzer');
});
socket.on('open response final jeopardy', function(){
playerSpc.emit('open response final jeopardy', questions["FJ_0_0"]._question);
});
socket.on('second round started', function(content){
playerSpc.emit('second round started', content);
});
socket.on('open question category new round', function(){
playerSpc.emit('open question category new round', getPlayerActive());
});
socket.on('open question category', function(playerNameActive){
console.log("Showing Category Select");
setPlayerActive(players[playerNameActive]);
playerSpc.emit('open question category', playerNameActive);
});
socket.on('next round started', function(){
changeActivePlayerNewRound();
gameSpc.emit('next round start confirmed', getPlayerActive());
playerSpc.emit('next round start confirmed', getPlayerActive());
});
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
socket.on('question timer out', function(){
questionTimesUp();
})
//assign random player, pass in game markup
socket.on('player random', function(data){
var playerActive = players[findRandomPlayer()];
gameState['active'] = true;
playerActive.isActive = true;
playerSpc.emit('active player', {playerName: getPlayerActive(), gameMarkup: data.gameMarkup, newGame: "new game", airdate: AIRDATE});
gameSpc.emit('active player', {playerName: getPlayerActive(), newGame: "new game", airdate: AIRDATE});
});
socket.on('final jeopardy started', function(){
playerSpc.emit('final jeopardy started');
});
socket.on('final jeopardy bid', function()
{
playerSpc.emit('final jeopardy bid', questions["FJ_0_0"]._category);
});
socket.on('final jeopardy time out', function()
{
playerSpc.emit('final jeopardy time out');
});
socket.on('game over', function(winningPlayerData){
fs.appendFileSync(gameHistory, '\n' + GAME_ID);
fs.appendFileSync(gameHighScore, '\n' + winningPlayerData.winningPlayerName + ',' + winningPlayerData.winningPlayerScore);
playerSpc.emit('game over', winningPlayerData.winningPlayerName);
});
socket.on('fetch high scores', function(){
var highScores = findHighScores();
gameSpc.emit('high scores', highScores);
});
function findHighScores(){
var gameHighScoreSend = fs.readFileSync(gameHighScore, {
encoding: 'binary'
});
// pass in the contents of a csv file
var parsedHighScore = Baby.parse(gameHighScoreSend);
// voila
var rowsHighScore = parsedHighScore.data;
var highScoreArray = new Array();
for(var row in rowsHighScore){
var score=rowsHighScore[row][1];
var name=rowsHighScore[row][0];
if (row==0){
highScoreArray.push({name: name, score: score});
}else{
if(score<highScoreArray[0].score){
highScoreArray.unshift({name: name, score:score});
}else{
var indexCounter = highScoreArray.length - 1;
while(score<highScoreArray[indexCounter].score){
indexCounter--;
}
highScoreArray.splice( indexCounter, 0, {name:name, score:score});
}
}
}
highScoreArray.reverse();
return highScoreArray;
}
console.log("Master Screen Connected");
function findRandomPlayer()
{
var names = new Array();
for (player in players)
{
names.push(players[player].name);
}
return names[Math.floor(Math.random() * objectLength(players))];
}
//TIMERS
socket.on('begin round timer', function(){
roundTimer = ROUND_TIME;
setRoundTimer();
});
socket.on('start countdown', function(questionId){
curQuestionId = questionId;
questionBeginCountdown();
gameSpc.emit('countdown', {timerCount: questionTimerCount, questionId: questionId});
playerSpc.emit('expose question');
});
socket.on('continue countdown', function(questionId){
questionContinueCountdown();
gameSpc.emit('countdown', {timerCount: questionTimerCount, questionId: questionId}); //is this being called earlier somehow>SSS
});
socket.on('open submit dd', function(){
dailyDoubleTimerCount = ANSWER_TIME;
dailyDoubleTimer = null;
playerSpc.emit('daily double question finished being read');
dailyDoubleBeginCountdown();
});
//after all messages are done move play to next active player
socket.on('finished all messages dd', function(){
console.log('finished all messages dd');
//if (!finalJeopardyCheck){
playerSpc.emit('active player', {playerName: getPlayerActive(), correct: false, newGame: "no"});
gameSpc.emit('active player', {playerName: getPlayerActive(), correct: false});
//}
});
socket.on('all messages done score update correct', function(){
//if(!finalJeopardyCheck){
console.log("Next player should be going...");
playerSpc.emit('active player', {playerName: getPlayerActive(), correct: true, newGame: "no"});
gameSpc.emit('active player', {playerName: getPlayerActive(), correct: true});
//}
});
socket.on('all messages done score update', function(){
//if(!finalJeopardyCheck){
console.log("Next player should be going...");
playerSpc.emit('active player', {playerName: getPlayerActive(), correct: false, newGame: "no"});
gameSpc.emit('active player', {playerName: getPlayerActive(), correct: false});
//}
});
socket.on('all messages done buzzed in time out', function(){
console.log('all messages done buzzed in time out');
if (checkIfAllPlayersAnswered()/*&& !finalJeopardyCheck*/){
playerSpc.emit('active player', {playerName: getPlayerActive(), correct: false, newGame: "no"});
gameSpc.emit('active player', {playerName: getPlayerActive(), correct: false});
}
});
socket.on('new game ready game board', function(){
newGameCounter = 0;
buzzerFlipped =false;
somecounter = 0;
gameData.length = 0;
gameData = [];
questions.length = 0;
questions = [];
finalJeopardyCheck = false;
isSecondRound = false;
roundTimer = ROUND_TIME;
for(player in players){
players[player].score = 0;
players[player].givenAnswer = false;
players[player].isActive = false;
}
//pick next possible game
//CHOOSE GAME FROM DB
console.log(gameData);
setGameDataNew();
});
socket.on('buzzer pressed confirmed', function(nameData){
playerSpc.emit('buzzer pressed', {playerName: nameData.playerName, questionId: nameData.questionId});
});
});
var currentConnections = new Array();
var disconnectedUserNames = new Array();
playerSpc.on('connection', function(socket){
console.log('player connected.');
currentConnections.push(socket);
if (gameState["active"] == true){
console.log("player attempting to reconnect")
loadGame(disconnectedUserNames[0], socket, players);
}
//handle player login name/ player join
socket.on('login name', function(name){
console.log("PLAYER JOINED WITH NAME: " + name);
socket.username = name;
currentConnections[socket.id] = {socket: socket};
currentConnections[socket.id].username = name;
console.log("CONNECTION USER DATA " + currentConnections);
gameSpc.emit('login name', name);
players[name] = new Player(name);
console.log(players);
if (objectLength(players)== 3)
{
playerSpc.emit('option select new', name);
}
else
{
playerSpc.emit('wait for start game', name);
}
});
//TESTS
socket.on('buzzer press test', function(playerNameBuzzed){
console.log("THIS PLAYER JUST BUZZED IN: " + playerNameBuzzed);
});
socket.on('expose question test', function(playerNameExposed){
console.log("PLAYER NAMED EXPOSED QUESTION " + playerNameExposed);
});
//set global turn time, grab game id
socket.on('option select new', function(optionArray){
console.log(optionArray);
ANSWER_TIME = optionArray[0];
DECADE = optionArray[1];
playerSpc.emit('answer time data', ANSWER_TIME);
gameSpc.emit('answer time data', ANSWER_TIME);
selectByDecade(DECADE, function(returnValue) {
GAME_ID = returnValue.game;
AIRDATE = returnValue.airdate;
var tempDate = new Date(AIRDATE);
AIRDATE = formatDate(tempDate);
console.log("GAME_ID: " + GAME_ID + " AIRDATE " + AIRDATE);
setGameDataNew();
});
});
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return monthNames[monthIndex] + ' ' + day + ', ' + year;
}
socket.on('new game', function(){
playerSpc.emit('new game');
});
socket.on('new game ready', function(){
console.log("NEW GAME COUNTER: " + newGameCounter);
newGameCounter+=1; //used to determine when all 3 player clients have reset their local values
if (newGameCounter == 3){
gameSpc.emit('new game', gameData);
}
});
//When active user selects a question
socket.on('question selected', function (questionId) {
questionTimerCount = 6;
console.log("QUESTION SELECTED ID: " + questionId);
buzzerFlipped = false;
//TODO: pause timer resume when question is received
if(roundTimer>0)
{
questionTimer = null;
allPlayersNoAnswer();
curQuestionId = questionId;
console.log("Question:" + JSON.stringify(questions[questionId]));
gameSpc.emit('question reveal', {question: questions[questionId]._question, questionId: questionId, playerName: getPlayerActive()});
playerSpc.emit('question reveal', {question: questions[questionId]._question, dailyDouble: questions[questionId]._dailyDouble, questionId: questionId, playerName: getPlayerActive()});
}
});
//When a player buzzes in
socket.on('buzzer pressed', function(playerName)
{
console.log("BUZZER PRESSED BY: " + playerName);
if (!buzzerFlipped)
{
console.log('buzzer pressed inside buzzerflip check: ' + playerName);
buzzerFlipped = true;
stopTimer(questionTimer);
if(questionTimerCount>0)
{
buzzedInPlayerName = playerName;
gameSpc.emit('buzzer pressed', {playerName: playerName, questionId: curQuestionId});
players[playerName].givenAnswer = true;
buzzedInTimerCount = ANSWER_TIME;
buzzedInBeginCountdown();
}
}
});
socket.on('buzzers opened',function(){
console.log("buzzers opened");
if (questionTimer == null){
console.log("should be initiating timer");
questionTimer = setInterval(function() {
questionTimerCount--;
playerSpc.emit('update interval', questionTimerCount);
gameSpc.emit('update interval', questionTimerCount);
if (questionTimerCount <= 0) {
console.log('stopping timer.');
stopTimer(questionTimer);
//stopTimer(this.int);
//questionTimesUp();
questionTimer = null;
}
}, 1000);
}
});
socket.on('player no answer final jeopardy', function(playerName){
players[playerName].score -= final_jeopardy_bet[playerName];
});
//On answer selection
socket.on('answer selection', function (answer) {
buzzerFlipped = false;
if (answer.finalJeopardyCheck){
checkAnswer(answer.answer, answer.questionId, answer.playerName, answer.finalJeopardyCheck);
}
else if (buzzedInTimerCount > 0){
stopTimer(buzzedInTimer);
stopTimer(dailyDoubleTimer);
buzzedInTimer = null;
dailyDoubleTimer = null;
checkAnswer(answer.answer, answer.questionId, answer.playerName, answer.finalJeopardyCheck);
}
});
var final_jeopardy_bet = new Array();
//for daily double bets and final jeopardy
socket.on('bet selection', function (bet){
//set question value to bet
if (!bet.finalJeopardyCheck)
{
questions[bet.questionId]._value = bet.betValue;
playerSpc.emit('daily double response', {playerName: bet.playerName, questionId: bet.questionId, question: questions[bet.questionId]._question, isDailyDouble: true});
gameSpc.emit('question reveal dd', {question: questions[bet.questionId]._question, questionId: bet.questionId, bet: bet.betValue});
}
else
{
final_jeopardy_bet[bet.playerName] = {playerName: bet.playerName, bet: bet.betValue};
gameSpc.emit('final jeopardy response', {playerName: bet.playerName, bet: bet.betValue});
}
});
socket.on('player field fj time out', function(playerName){
console.log("sending data: score "+ players[playerName].score + "name " + playerName);
var timeOutScore = parseInt(players[playerName].score);
timeOutScore -= parseInt(final_jeopardy_bet[playerName].bet);
gameSpc.emit('score update final jeopardy buzzed out', {playerName: playerName, score: timeOutScore, correct: false, answer:"", buzzedInFJ: false});
});
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
if(currentConnections[this.id]){
disconnectedUserNames.push(currentConnections[this.id].username);
}
console.log("DISCONNECTED USERNAME DATA " + disconnectedUserNames);
});
function checkAnswer(answer, questionId, playerName, finalJeopardy)
{
if (finalJeopardy)
{
questionId = "FJ_0_0";
}
console.log("question ID: " + questionId);
console.log("answer" + answer);
var originalPlayerAnswer = answer.toUpperCase();
var originalActualAnswer = questions[questionId]._answer.toUpperCase();
var actualAnswer = questions[questionId]._answer;
var playerAnswer = answer;
var score = players[playerName].score;
var value = questions[questionId]._value;
var correct = false;
var skimmedAnswer = false;
var andAnswer = false;
value = parseInt(value, 10);
actualAnswer = actualAnswer.toUpperCase();
playerAnswer = playerAnswer.toUpperCase();
console.log("ACTUAL ANSWER BEFORE MODIFICATION: " + actualAnswer);
console.log("PLAYER ANSWER BEFORE MODIFICATION: "+ playerAnswer);
tempActualAnswerSearch = actualAnswer.substring(0, 2);
if (tempActualAnswerSearch == "A "){
actualAnswer = actualAnswer.substring(2, actualAnswer.length);
actualAnswer.trim();
}
tempINGAnswerSearch = actualAnswer.substring(actualAnswer.length-4);
tempINGPlayerAnswerSearch = actualAnswer.substring(actualAnswer.length-4);
if(tempINGAnswerSearch == "ING"){
actualAnswer = actualAnswer.substring(0, actualAnswer.length-4);
}
if(tempINGPlayerAnswerSearch == "ING"){
playerAnswer = playerAnswer.substring(0, playerAnswer.length-4);
}
//remove what is, who is, who are, the
var regexCommon = new RegExp("^\\b(WHAT IS|WHO IS|WHO ARE|WHAT ARE|WHAT IS|WHO IS A|WHO ARE A|WHAT ARE A|WHAT IS A|LIKE A| LIKE)\\b", "g");
playerAnswer = playerAnswer.replace(regexCommon,'');
//change all instances of & to AND
if(actualAnswer.includes("&") || actualAnswer.includes("AND"))
{
//andAnswer = true;
actualAnswer = actualAnswer.replace("&", "AND");
}
if(playerAnswer.includes("&"))
{
playerAnswer = playerAnswer.replace("&", "AND");
}
console.log("actualAnswer before remove special characters" + actualAnswer);
console.log("playerAnswer before remove special characters" + playerAnswer);
actualAnswer = removeSpecialCharacters(actualAnswer);
playerAnswer = removeSpecialCharacters(playerAnswer);
actualAnswer = actualAnswer.trim();
playerAnswer = playerAnswer.trim();
console.log("actualAnswer after remove special characters" + actualAnswer);
console.log("playerAnswer after remove special characters" + playerAnswer);
//check if answer is proper name
var isName = false;
console.log("Player Answer before name check: " + playerAnswer);
var playerAnswerArrayTemp = playerAnswer.split(" ");
console.log(playerAnswerArrayTemp.length);
tempPlayerAnswerSearch = playerAnswer.substring(0, 3);
//make sure the string isn't inside the answer or a "bad" word
var badWords = new Array(
"THE",
"THEN",
"ST",
"ST.",
"IS",
"WHAT ",
"A",
"WHO",
"WHERE",
"WHEN",
"AFTER",
"IN",
"TO",
"AS",
"WHY",
"AN",
"ON",
"WITH",
"AND");
actualAnswer = actualAnswer.split(" ");
playerAnswer = playerAnswer.split(" ");
console.log("player Array length: " + playerAnswer.length);
console.log("answer Array length: " + actualAnswer.length);
if (playerAnswer.length == 1){
playerAnswer = equateNumberLiterals(playerAnswer);
}
if (actualAnswer.length == 1){
actualAnswer = equateNumberLiterals(actualAnswer);
}
/*if (actualAnswer.includes(playerAnswer)) //check if answer includes the players response
{
if (badWords.indexOf(playerAnswer) === -1) //check if the answer was something silly from the array above
{
var stringToGoIntoTheRegex = playerAnswer;
var regex = new RegExp("\\b" + stringToGoIntoTheRegex + "\\b", "g"); ///\bsdda\b/g //check if the answer has any part inside the word
// at this point, the line above is the same as: var regex = /#abc#/g;
var searchResult = actualAnswer.search(regex);
console.log("String: " + regex);
console.log("Reg ex: " + searchResult);
if(searchResult != -1)
{
if(closeEnough(playerAnswer, actualAnswer))
{
skimmedAnswer = true;
}
}
}
}*/
var answerObject = checkForPlural(playerAnswer, actualAnswer);
actualAnswer = answerObject.actualAnswer;
playerAnswer = answerObject.playerAnswer;
console.log("player answer after plural check: " + playerAnswer);
console.log("player Array length: " + playerAnswer.length);
console.log("answer Array length: " + actualAnswer.length);
//remove all "spaces" from array
for (var word in actualAnswer){
if(actualAnswer[word] == " "){
actualAnswer.splice(word, 1);
}
}
for (var word in playerAnswer){
console.log("WORD VAR: " + word);
console.log("ANSWER INDEX: " + playerAnswer[word]);
if(playerAnswer[word] == " "){
playerAnswer.splice(word, 1);
}
}
console.log("player Array length: " + playerAnswer.length);
console.log("answer Array length: " + actualAnswer.length);
var actualAnswer = actualAnswer.filter(function(x) {
return badWords.indexOf(x) < 0;
});
var playerAnswer = playerAnswer.filter(function(x) {
return badWords.indexOf(x) < 0;
});
console.log("removed bad words from answer : " + actualAnswer + "\n removed bad words from player answer: " + playerAnswer);
if (actualAnswer.length <= 3){
console.log("THIS MIGHT BE A PROPER NAME");
if(actualAnswer.length==3){
isName = checkIfName(actualAnswer[2]);
}else if(actualAnswer.length==2){
isName = checkIfName(actualAnswer[1]);
}else if(actualAnswer.length==1){
isName = checkIfName(actualAnswer[0]);
}
}
if (isName){
if(playerAnswer.length == 1){
if(actualAnswer.length==1){
if(playerAnswer[0] == actualAnswer[0]){
skimmedAnswer = true;
}
}else if(actualAnswer.length==2){
if(playerAnswer[0] == actualAnswer[1]){
skimmedAnswer = true;
}
}
}else if(playerAnswer.length == 2){
if(actualAnswer.length==1){
if(playerAnswer[1] == actualAnswer[0]){
skimmedAnswer = true;
}
}else if(actualAnswer.length==2){
if(playerAnswer[1] == actualAnswer[1]){
skimmedAnswer = true;
}
}
}else if(playerAnswer.length == 3){
if(actualAnswer.length==1){
if(playerAnswer[1] == actualAnswer[0]){
skimmedAnswer = true;
}
}else if(actualAnswer.length==2){
if(playerAnswer[1] == actualAnswer[1]){
skimmedAnswer = true;
}
}else if(actualAnswer.length==3){
if(playerAnswer[2] == actualAnswer[2]){
skimmedAnswer = true;