-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1662 lines (1443 loc) · 48.8 KB
/
index.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
const express = require('express')
const app = express()
const session = require('cookie-session')
const bodyParser = require('body-parser')
const csv = require('csv-parser')
const fs = require('fs')
const { Octokit } = require("@octokit/rest")
const Readable = require('stream').Readable
const { Base64 } = require('js-base64')
const { v4: uuidv4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static(`${__dirname}/static`))
app.use(express.urlencoded({ extended: false }))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('etag', false)
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store')
next()
})
require('dotenv').config()
app.use(session({
secret: process.env.SESSION_SECRET,
name: 'csgodoku',
resave: true,
saveUninitialized: true,
maxAge: 10 * 365 * 24 * 60 * 60 * 1000,
}))
const db = require('./db')
const { get, set } = require('express/lib/response')
const playerData = {}
const playerList = {}
const teamNameToID = {}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function readCSV(playerData, playerList) {
return new Promise(async function (resolve, reject) {
const octokit = new Octokit({
auth: process.env.GH_TOKEN,
})
const res = await octokit.repos.getContent({
owner: 'andrewlamm',
repo: 'csgodoku',
path: 'data/playerData.csv',
})
const data = Base64.decode(res.data.content)
const parseType = ['', 'int', '', '', 'int', 'float', 'float', 'int', 'int', 'int', 'int', 'int', 'float', 'float', 'float', 'float', 'dictionary', 'int', 'set', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int']
let lastUpdated = undefined
let topRow = undefined
// fs.createReadStream('playerData.csv')
Readable.from(data)
.pipe(csv())
.on('headers', (headers) => {
topRow = headers
lastUpdated = headers[0]
})
.on('data', (row) => {
const rowData = Object.values(row)
const playerID = parseInt(rowData[1])
playerData[playerID] = {}
playerData[playerID]['name'] = rowData[0]
for (let i = 1; i < rowData.length; i++) {
if (rowData[i] === 'undefined' || rowData[i] === 'N/A') {
playerData[playerID][topRow[i]] = undefined
}
else if (parseType[i] === 'int') {
playerData[playerID][topRow[i]] = parseInt(rowData[i])
}
else if (parseType[i] === 'float') {
playerData[playerID][topRow[i]] = parseFloat(rowData[i])
}
else if (parseType[i] === 'set') {
const teamSetWithID = new Set(JSON.parse(rowData[i]))
const teamSet = new Set()
playerData[playerID]['teamIDs'] = new Set()
teamSetWithID.forEach(team => {
const teamName = team.substring(team.indexOf('/')+1)
teamSet.add(teamName)
// code for adding team to teamNameToID
if (teamNameToID[teamName] === undefined) {
teamNameToID[teamName] = new Set()
}
teamNameToID[teamName].add(team)
// for infinite puzzle team ids
playerData[playerID]['teamIDs'].add(team)
})
playerData[playerID][topRow[i]] = teamSet
}
else if (parseType[i] === 'dictionary') {
const ratingDictionary = JSON.parse(rowData[i])
playerData[playerID][topRow[i]] = {}
for (const [year, rating] of Object.entries(ratingDictionary)) {
playerData[playerID][topRow[i]][parseInt(year)] = parseFloat(rating)
}
}
else {
playerData[playerID][topRow[i]] = rowData[i]
}
}
playerList[playerID] = {
name: rowData[0],
fullName: rowData[2],
id: playerID,
}
})
.on('end', () => {
resolve(lastUpdated)
})
})
}
/* EJS Helper Functions */
app.locals.displayClue = function(clue) {
if (clue[0] === 'team') {
return `
<div class="flex flex-col relative h-20 w-20 md:h-36 md:w-36 items-center justify-center text-center text-white">
<img src="/images/team/${clue[1].substring(0, clue[1].indexOf('/'))}.png" title="${clue[1].substring(clue[1].indexOf('/')+1)}" class="h-12 md:h-20" onerror="if (this.src != 'images/team/placeholder.png') this.src = 'images/team/placeholder.png';">
<div class="absolute bottom-0 w-full text-center pb-2 text-sm md:text-base">
${clue[1].substring(clue[1].indexOf('/')+1)}
</div>
</div>
`
}
else if (clue[0] === 'country') {
return `
<div class="flex flex-col relative h-20 w-20 md:h-36 md:w-36 items-center justify-center text-center text-white">
<img src="/images/country/${clue[1]}.png" title="${clue[1]}" class="h-4 md:h-12">
<div class="absolute bottom-0 w-full text-center pb-2 text-xs md:text-base">
${clue[1]} nationality
</div>
</div>
`
}
else {
let clueString = ''
if (clue[0] === 'age') {
clueString = `${clue[1]}+ years old`
}
else if (clue[0] === 'rating2') {
clueString = `${clue[1]} career <b>rating 2.0</b>`
}
else if (clue[0] === 'rating1') {
clueString = `${clue[1]} career <b>rating 1.0</b>`
}
else if (clue[0] === 'KDDiff') {
clueString `${clue[1]}+ career K/D difference`
}
else if (clue[0] === 'maps') {
clueString = `${clue[1]}+ maps played`
}
else if (clue[0] === 'rounds') {
clueString = `${clue[1]}+ rounds played`
}
else if (clue[0] === 'KDRatio') {
clueString = `${clue[1]}+ career K/D ratio`
}
else if (clue[0] === 'HSRatio') {
clueString = `${clue[1]}%+ career headshot percentage`
}
else if (clue[0] === 'ratingTop20') {
clueString = `${clue[1]}+ career <b>rating 2.0</b> against top 20 teams`
}
else if (clue[0] === 'clutchesTotal') {
clueString = `${clue[1]}+ clutches won`
}
else if (clue[0] === 'majorsWon') {
clueString = `${clue[1]}+ majors won`
}
else if (clue[0] === 'majorsPlayed') {
clueString = `${clue[1]}+ majors played`
}
else if (clue[0] === 'LANsWon') {
clueString = `${clue[1]}+ LANs won`
}
else if (clue[0] === 'LANsPlayed') {
clueString = `${clue[1]}+ LANs played`
}
else if (clue[0] === 'top20s') {
clueString = `${clue[1]}+ top 20 players of the year finishes`
}
else if (clue[0] === 'top10s') {
clueString = `${clue[1]}+ top 10 players of the year finishes`
}
else if (clue[0] === 'ratingYear') {
clueString = `${clue[1][1]}+ <b>rating 1.0</b> in ${clue[1][0]}`
}
else if (clue[0] === 'topPlacement') {
clueString = `top ${clue[1]} player in at least one year`
}
else {
clueString = `${clue[1]}+ career ${clue[0]}`
}
return `
<div class="flex flex-col relative h-20 w-20 md:h-36 md:w-36 items-center justify-center text-center text-white text-sm md:text-base">
${clueString}
</div>
`
}
}
app.locals.getBorders = function(ind) {
const BORDERS = ['border-r border-b', 'border-r border-b', 'border-b', 'border-r border-b', 'border-r border-b', 'border-b', 'border-r', 'border-r', '']
return BORDERS[ind]
}
app.locals.formatPercentage = function(percent) {
if (percent < 10) {
return `${percent.toFixed(2)}%`
}
else if (percent < 100) {
return `${percent.toFixed(1)}%`
}
else {
return `${percent.toFixed(0)}%`
}
}
let puzzle = undefined
let puzzleDate = undefined
let possiblePlayers = undefined
let lastUpdated = undefined
let puzzleUpdating = false
const TIME_OFFSET = 1690855200 // Jul 31, 10 PM EST
const SECONDS_PER_DAY = 86400
const NUMBER_OF_GUESSES = 9
const PUZZLES_GRID = [[0, 3], [1, 3], [2, 3], [0, 4], [1, 4], [2, 4], [0, 5], [1, 5], [2, 5]]
const PUZZLE_TO_GRID = [[0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 1, 2], [3, 4, 5], [6, 7, 8]]
function checkPlayerGrid(playerID, clue1, clue2, teamNameHasID = true) {
const clue1Type = clue1[0]
const clue1Val = clue1[1]
const clue2Type = clue2[0]
const clue2Val = clue2[1]
let clue1Check = false
let clue2Check = false
if (clue1Type === 'team') {
const team = teamNameHasID ? clue1Val.substring(clue1Val.indexOf('/')+1) : clue1Val
if (playerData[playerID]['teams'].has(team)) {
clue1Check = true
}
}
else if (clue1Type === 'country') {
if (playerData[playerID]['country'] === clue1Val) {
clue1Check = true
}
}
else if (clue1Type === 'ratingYear') {
if (playerData[playerID]['ratingYear'][clue1Val[0]] === undefined) {
clue1Check = false
}
else if (playerData[playerID]['ratingYear'][clue1Val[0]] >= parseFloat(clue1Val[1])) {
clue1Check = true
}
}
else if (clue1Type === 'topPlacement') {
if (playerData[playerID]['topPlacement'] === undefined) {
clue1Check = false
}
else if (playerData[playerID]['topPlacement'] <= parseInt(clue1Val)) {
clue1Check = true
}
}
else {
if (playerData[playerID][clue1Type] === undefined) {
clue1Check = false
}
else if (playerData[playerID][clue1Type] >= parseFloat(clue1Val)) {
clue1Check = true
}
}
if (clue2Type === 'team') {
const team = teamNameHasID ? clue2Val.substring(clue2Val.indexOf('/')+1) : clue2Val
if (playerData[playerID]['teams'].has(team)) {
clue2Check = true
}
}
else if (clue2Type === 'country') {
if (playerData[playerID]['country'] === clue2Val) {
clue2Check = true
}
}
else if (clue2Type === 'ratingYear') {
if (playerData[playerID]['ratingYear'][clue2Val[0]] === undefined) {
clue2Check = false
}
else if (playerData[playerID]['ratingYear'][clue2Val[0]] >= parseFloat(clue2Val[1])) {
clue2Check = true
}
}
else if (clue2Type === 'topPlacement') {
if (playerData[playerID]['topPlacement'] === undefined) {
clue2Check = false
}
else if (playerData[playerID]['topPlacement'] <= parseInt(clue2Val)) {
clue2Check = true
}
}
else {
if (playerData[playerID][clue2Type] === undefined) {
clue2Check = false
}
else if (playerData[playerID][clue2Type] >= parseFloat(clue2Val)) {
clue2Check = true
}
}
return clue1Check && clue2Check
}
function findAllPossiblePlayers(puzzle) {
possiblePlayers = [new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set()]
for (const [id, player] of Object.entries(playerData)) {
const playerID = parseInt(id)
for (let pos = 0; pos < 9; pos++) {
if (checkPlayerGrid(playerID, puzzle[PUZZLES_GRID[pos][0]], puzzle[PUZZLES_GRID[pos][1]])) {
possiblePlayers[pos].add(playerID)
}
}
}
}
function calculateUniqueness(board, possiblePlayers) {
let score = 0
for (let i = 0; i < 9; i++) {
if (board[i] !== undefined && board[i] !== null) {
for (let j = 0; j < possiblePlayers[i].length; j++) {
if (possiblePlayers[i][j].playerID === board[i]) {
if (possiblePlayers[i][j].percentage === undefined) {
score += 100
}
else {
score += 100 - parseInt(possiblePlayers[i][j].percentage * 100)
}
break
}
}
}
}
return score
}
/* Middleware */
async function checkPuzzle(req, res, next) {
if (puzzle === undefined) {
// need to load puzzle
const currTime = Math.floor(new Date().getTime() / 1000) - TIME_OFFSET
puzzleDate = parseInt(currTime / SECONDS_PER_DAY)
const puzzleResult = await db.findOne({ _id: 'puzzleList' })
const puzzleList = puzzleResult.puzzles
puzzle = puzzleList[puzzleDate]
findAllPossiblePlayers(puzzle)
const statsResult = await db.findOne({ _id: 'currentPuzzleStats' })
if (puzzleDate === statsResult.puzzleDate) {
// date on stats is correct, no need to reset
next()
}
else {
// need to reset stats as well
puzzleUpdating = true
const initPickedPlayers = [{}, {}, {}, {}, {}, {}, {}, {}, {}]
for (let i = 0; i < 9; i++) {
possiblePlayers[i].forEach(playerID => {
initPickedPlayers[i][playerID] = 0
})
}
const query = { _id: 'currentPuzzleStats' }
const update = { $set: {
puzzleDate: puzzleDate,
numberGames: 0,
scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
totalUniqueness: 0,
pickedPlayers: initPickedPlayers,
} }
const updateRes = await db.updateOne(query, update)
puzzleUpdating = false
next()
}
}
else {
const currTime = Math.floor(new Date().getTime() / 1000) - TIME_OFFSET
if (parseInt(currTime / SECONDS_PER_DAY) > puzzleDate) {
// need to have a new puzzle
/* get puzzle */
puzzleUpdating = true
puzzleDate = parseInt(currTime / SECONDS_PER_DAY)
const puzzleResult = await db.findOne({ _id: 'puzzleList' })
const puzzleList = puzzleResult.puzzles
puzzle = puzzleList[puzzleDate]
/* get possible players */
findAllPossiblePlayers(puzzle)
const initPickedPlayers = [{}, {}, {}, {}, {}, {}, {}, {}, {}]
for (let i = 0; i < 9; i++) {
possiblePlayers[i].forEach(playerID => {
initPickedPlayers[i][playerID] = 0
})
}
/* reset stats */
const query = { _id: 'currentPuzzleStats' }
const update = { $set: {
puzzleDate: puzzleDate,
numberGames: 0,
scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
totalUniqueness: 0,
pickedPlayers: initPickedPlayers,
} }
const updateRes = await db.updateOne(query, update)
puzzleUpdating = false
next()
}
else {
// current puzzle is fine, do nothing
next()
}
}
}
async function initPlayer(req, res, next) {
if (req.session.player === undefined) {
req.session.player = {
start: new Date(),
puzzle: puzzle,
guessesLeft: NUMBER_OF_GUESSES,
board: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined],
guesses: [[], [], [], [], [], [], [], [], []],
gameStatus: 0,
userScore: ['-', '-'],
}
req.session.userStats = {
finalGridAmount: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
}
next()
}
else {
if (JSON.stringify(req.session.player.puzzle) !== JSON.stringify(puzzle)) {
req.session.player = {
start: new Date(),
puzzle: puzzle,
guessesLeft: NUMBER_OF_GUESSES,
board: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined],
guesses: [[], [], [], [], [], [], [], [], []],
gameStatus: 0,
userScore: ['-', '-'],
}
next()
}
else {
next()
}
}
}
async function getPickedPlayersList() {
// read from db
while (puzzleUpdating) {
// wait until ready
await delay(500)
await getPickedPlayersList()
}
const pickedPlayersSet = [{}, {}, {}, {}, {}, {}, {}, {}, {}]
const pickedPlayersCount = [[], [], [], [], [], [], [], [], []]
const totalPicks = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for (let ind = 0; ind < 9; ind++) {
possiblePlayers[ind].forEach(playerID => {
pickedPlayersSet[ind][playerID] = {
playerID: playerID,
name: playerData[playerID].name,
fullName: playerData[playerID].fullName,
count: 0,
percentage: 0,
}
})
}
const query = { _id: 'currentPuzzleStats' }
const result = await db.findOne(query)
for (let ind = 0; ind < 9; ind++) {
for (const [playerID, count] of Object.entries(result.pickedPlayers[ind])) {
pickedPlayersSet[ind][playerID].count = count
totalPicks[ind] += count
}
}
for (let ind = 0; ind < 9; ind++) {
for (const [playerID, player] of Object.entries(pickedPlayersSet[ind])) {
pickedPlayersCount[ind].push(player)
}
}
for (let ind = 0; ind < 9; ind++) {
pickedPlayersCount[ind].sort((a, b) => b.count - a.count)
}
for (let ind = 0; ind < 9; ind++) {
for (const [playerID, player] of Object.entries(pickedPlayersCount[ind])) {
player.percentage = totalPicks[ind] === 0 ? 0 : player.count / totalPicks[ind]
player.totalPicks = totalPicks[ind]
}
}
return pickedPlayersCount
}
async function updateGlobalFinalScores(score, unique) {
const query = { _id: 'currentPuzzleStats' }
const update = { $inc: { } }
update.$inc[`scores.${score}`] = 1
update.$inc.numberGames = 1
update.$inc.totalUniqueness = unique
const updateRes = await db.updateOne(query, update)
}
async function getFinalScores() {
const query = { _id: 'currentPuzzleStats' }
const result = await db.findOne(query)
return [result.scores, result.numberGames]
}
async function getUniqueness() {
const query = { _id: 'currentPuzzleStats' }
const result = await db.findOne(query)
return result.numberGames === 0 ? 0 : parseInt(result.totalUniqueness / result.numberGames)
}
async function getStats(req, res, next) {
res.locals.pickedPlayersData = await getPickedPlayersList()
res.locals.finalScores = await getFinalScores()
res.locals.averageUniqueness = await getUniqueness()
next()
}
async function insertGuessHelper(req, res, next) {
try {
const ind = parseInt(req.body.index)
const guess = parseInt(req.body.guess)
if (req.session.player === undefined) {
console.log('insert guess fail, no player')
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
else if (JSON.stringify(req.session.player.puzzle) !== JSON.stringify(puzzle)) {
console.log('insert guess fail, puzzle incorrect', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
else if (req.session.player.guessesLeft <= 0) {
console.log('insert guess fail, no guesses left', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
else if (isNaN(ind) || ind < 0 || ind >= 9) {
console.log('insert guess fail, invalid index', ind)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.player.board === undefined) {
console.log('insert guess fail, no board', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.player.board[ind] !== undefined && req.session.player.board[ind] !== null) {
console.log(req.session.player.board[ind])
console.log('insert guess fail, index already guessed', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.player.guesses === undefined) {
console.log('insert guess fail, no guesses array', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (isNaN(guess) || playerData[guess] === undefined) {
console.log('insert guess fail, invalid player guessed', guess)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.player.guesses[ind].includes(guess) || req.session.player.board.includes(guess)) {
console.log('insert guess fail, already guessed', playerData[guess].name)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.userStats === undefined || req.session.userStats.finalGridAmount === undefined || req.session.userStats.finalGridAmount.length !== 10) {
console.log('insert guess fail, user stats error', req.session.userStats)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else {
// all good
req.session.player.guesses[ind].push(guess)
req.session.player.guessesLeft -= 1
if (possiblePlayers[ind].has(guess)) {
// correct guess
req.session.player.board[ind] = guess
res.locals.pickedPlayersData = await getPickedPlayersList()
for (let i = 0; i < res.locals.pickedPlayersData[ind].length; i++) {
if (res.locals.pickedPlayersData[ind][i].playerID === guess) {
res.locals.guessPercentage = (res.locals.pickedPlayersData[ind][i].count + 1) / (res.locals.pickedPlayersData[ind][i].totalPicks + 1)
break
}
}
}
if (req.session.player.guessesLeft <= 0) {
// game is over
/* add picks to db */
const query = { _id: 'currentPuzzleStats' }
const result = await db.findOne(query)
const update = { $inc: { } }
for (let i = 0; i < 9; i++) {
if (req.session.player.board[i] !== undefined && req.session.player.board[i] !== null) {
const player = req.session.player.board[i]
update.$inc[`pickedPlayers.${i}.${player}`] = 1
}
}
const resultDoc = await db.updateOne(query, update)
const score = 9 - req.session.player.board.filter(x => x === undefined || x === null).length
req.session.userStats.finalGridAmount[score] += 1
const pickedPlayersData = await getPickedPlayersList()
const uniqueScore = calculateUniqueness(req.session.player.board, pickedPlayersData)
await updateGlobalFinalScores(score, uniqueScore)
req.session.player.gameStatus = req.session.player.board.filter(x => x === undefined || x === null).length === 0 ? 1 : -1
req.session.player.userScore = [score, uniqueScore]
res.locals.guessReturn = {
gameStatus: req.session.player.board.filter(x => x === undefined || x === null).length === 0 ? 1 : -1, // gameStatus; 1 = win, -1 = lose, 0 = in progress
guessStatus: possiblePlayers[ind].has(guess) ? 1 : 0, // guess status; 1 = in board, 0 = not
guessesLeft: req.session.player.guessesLeft, // guesses left
guessPercentage: res.locals.guessPercentage, // percentage of players with this guess
userScore: [score, uniqueScore], // user score [score, uniqueness]
}
next()
}
else {
// continue game
res.locals.guessReturn = {
gameStatus: 0,
guessStatus: possiblePlayers[ind].has(guess) ? 1 : 0,
guessesLeft: req.session.player.guessesLeft,
guessPercentage: res.locals.guessPercentage,
}
next()
}
}
}
catch (err) {
console.log('insert guess fail, error', err)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
}
async function concedeHelper(req, res, next) {
try {
if (req.session.player === undefined) {
console.log('concede fail, no player')
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
else if (JSON.stringify(req.session.player.puzzle) !== JSON.stringify(puzzle)) {
console.log('concede fail, puzzle incorrect', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
gameStatus: 0,
}
next()
}
else if (req.session.player.board === undefined) {
console.log('concede fail, no board', req.session.player)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.userStats === undefined || req.session.userStats.finalGridAmount === undefined || req.session.userStats.finalGridAmount.length !== 10) {
console.log('concede fail, user stats error', req.session.userStats)
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: req.session.player.guessesLeft,
gameStatus: 0,
}
next()
}
else if (req.session.player.gameStatus !== 0) {
// game has ended, do nothing
console.log('concede fail, game ended', req.session.player)
next()
}
else {
req.session.player.guessesLeft = 0
req.session.player.gameStatus = -1
const query = { _id: 'currentPuzzleStats' }
const result = await db.findOne(query)
const update = { $inc: { } }
for (let i = 0; i < 9; i++) {
if (req.session.player.board[i] !== undefined && req.session.player.board[i] !== null) {
const player = req.session.player.board[i]
update.$inc[`pickedPlayers.${i}.${player}`] = 1
}
}
const resultDoc = await db.updateOne(query, update)
const score = 9 - req.session.player.board.filter(x => x === undefined || x === null).length
req.session.userStats.finalGridAmount[score] += 1
const pickedPlayersData = await getPickedPlayersList()
const uniqueScore = calculateUniqueness(req.session.player.board, pickedPlayersData)
await updateGlobalFinalScores(score, uniqueScore)
req.session.player.gameStatus = req.session.player.board.filter(x => x === undefined || x === null).length === 0 ? 1 : -1
req.session.player.userScore = [score, uniqueScore]
res.locals.guessReturn = {
gameStatus: -1,
guessesLeft: 0,
pickedPlayers: pickedPlayersData,
userScore: [score, uniqueScore],
}
next()
}
}
catch (err) {
console.log('concede fail, error', err)
next()
}
}
function checkPlayer(req, res, next) {
if (req.session.player === undefined) {
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
}
next()
}
else if (JSON.stringify(req.session.player.puzzle) !== JSON.stringify(puzzle)) {
res.locals.guessReturn = {
guessStatus: -1,
guessesLeft: 0,
}
next()
}
else {
next()
}
}
app.get('/', [checkPuzzle, initPlayer, getStats], (req, res) => {
// console.log('load')
req.session.update = Math.floor(Date.now() / 60000) // update cookie expiry every time user visits site
delete req.session.infinitePlayerLoading
delete req.session.infinitePlayer
req.session.player.boardPercentages = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
for (let ind = 0; ind < 9; ind++) {
if (req.session.player.board[ind] !== undefined && req.session.player.board[ind] !== null) {
// ind is filled with a player
for (let i = 0; i < res.locals.pickedPlayersData[ind].length; i++) {
if (res.locals.pickedPlayersData[ind][i].playerID === req.session.player.board[ind]) {
if (req.session.player.gameStatus !== 0) {
// game over
req.session.player.boardPercentages[ind] = res.locals.pickedPlayersData[ind][i].percentage
}
else {
// game not over, need to +1
req.session.player.boardPercentages[ind] = (res.locals.pickedPlayersData[ind][i].count + 1) / (res.locals.pickedPlayersData[ind][i].totalPicks + 1)
}
break
}
}
}
}
if (req.session.player.gameStatus !== 0) {
// game ended
req.session.player.userScore[1] = calculateUniqueness(req.session.player.board, res.locals.pickedPlayersData)
}
res.render('index', {
puzzle: puzzle,
players: playerList,
currGame: req.session.player,
lastUpdated: lastUpdated
})
})
app.get('/stats', [checkPuzzle, initPlayer, getStats], (req, res) => {
req.session.update = Math.floor(Date.now() / 60000) // update cookie expiry every time user visits site
delete req.session.infinitePlayerLoading
delete req.session.infinitePlayer
if (req.session.player.gameStatus !== 0) {
req.session.player.boardPercentages = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
for (let ind = 0; ind < 9; ind++) {
if (req.session.player.board[ind] !== undefined && req.session.player.board[ind] !== null) {
// ind is filled with a player
for (let i = 0; i < res.locals.pickedPlayersData[ind].length; i++) {
if (res.locals.pickedPlayersData[ind][i].playerID === req.session.player.board[ind]) {
req.session.player.boardPercentages[ind] = res.locals.pickedPlayersData[ind][i].percentage
break
}
}
}
}
}
const numberGames = res.locals.finalScores[0].reduce((a, b) => a + b, 0)
const scoreSum = res.locals.finalScores[0].reduce((a, b, ind) => a + b * ind, 0)
if (req.session.player.gameStatus !== 0) {
// game ended
req.session.player.userScore[1] = calculateUniqueness(req.session.player.board, res.locals.pickedPlayersData)
res.render('stats', {
puzzle: puzzle,
players: playerList,
currGame: req.session.player,
finalScores: res.locals.finalScores[0],
averageScore: (scoreSum / numberGames).toFixed(1),
numberGames: res.locals.finalScores[1],
pickedPlayers: res.locals.pickedPlayersData,
userOverallScores: req.session.userStats.finalGridAmount,
averageUniqueness: res.locals.averageUniqueness,
lastUpdated: lastUpdated
})
}
else {
res.render('stats', {
puzzle: puzzle,
players: playerList,
currGame: req.session.player,
finalScores: res.locals.finalScores[0],
averageScore: (scoreSum / numberGames).toFixed(1),
numberGames: res.locals.finalScores[1],
pickedPlayers: undefined,
userOverallScores: req.session.userStats.finalGridAmount,
averageUniqueness: res.locals.averageUniqueness,
lastUpdated: lastUpdated
})
}
})
app.post('/insertGuess', [checkPuzzle, checkPlayer, insertGuessHelper], (req, res) => {
res.send(res.locals.guessReturn)
})
app.post('/concede', [checkPuzzle, checkPlayer, concedeHelper], (req, res) => {
res.send(res.locals.guessReturn)
})
/* Infinite Mode */
let top10Teams = undefined
let top20Teams = undefined
let top30Teams = undefined
let allTeams = undefined
let top10TeamsInit = undefined
let top20TeamsInit = undefined
let top30TeamsInit = undefined
let allTeamsInit = undefined
const STATS = [
['country', undefined],
['age', [30, 35, 40]],
['rating2', [1.1, 1.2]],
['rating1', [1.1, 1.2]],
['maps', [1000, 2000, 3000]],
['rounds', [20000, 30000, 40000]],
['kills', [10000, 20000, 30000]],
['deaths', [10000, 20000, 30000]],
['ratingTop20', [1.1, 1.2]],
['ratingYear', [[2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022], [1.1, 1.2]]],
['clutchesTotal', [250, 500, 600]],
['majorsWon', [1, 2]],
['majorsPlayed', [1, 4, 8]],
['LANsWon', [1, 5, 10]],
['MVPs', [1, 3, 5, 10]],
['top20s', [1, 3, 5, 10]],
['top10s', [1, 3, 5]],
['topPlacement', [1, 5, 10, 20]]
]