-
Notifications
You must be signed in to change notification settings - Fork 0
/
5×100.js
1171 lines (1112 loc) · 45.3 KB
/
5×100.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
'use strict'
const fs = require('fs')
const cjson = require('compress-json')
const express = require('express')
const app = express()
const gname = '5×100'
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/client/${gname}.html`)
})
app.use(express.static(`${__dirname}/client`))
const config = require(`${__dirname}/client/config.js`)
const server = require('http').createServer(app)
const io = require('socket.io')(server)
const port = config.ServerPort(gname)
const unix = typeof port === 'string'
server.listen(port)
console.log(`server started on ${port}`)
if (unix)
server.on('listening', () => fs.chmodSync(port, 0o777))
const saveFile = `${gname}.json`
const games = cjson.decompress(JSON.parse(fs.readFileSync(saveFile, 'utf8')))
const randomLetter = () => String.fromCharCode(65 + Math.random() * 26)
function randomUnusedGameName() {
if (Object.keys(games).length === 26 * 26) {
console.log('all game names in use')
return 'Overflow'
}
let name
do { name = randomLetter() + randomLetter() } while (name in games)
return name
}
function saveGames() {
let toSave = {}
for (const [gameName, game] of Object.entries(games))
if (game.started) {
toSave[gameName] = {...game}
toSave[gameName].spectators = []
toSave[gameName].players = JSON.parse(JSON.stringify(
toSave[gameName].players, (k, v) => k === 'socketId' ? null : v))
}
fs.writeFileSync(saveFile,
JSON.stringify(cjson.compress(toSave)))
}
function updateGames(room) {
if (!room) room = 'lobby'
const data = []
for (const [gameName, game] of Object.entries(games))
data.push({ name: gameName,
players: game.players.map(player => (
{ name: player.name,
disconnected: !player.socketId,
victorious: player.victorious
}))
})
io.in(room).emit('updateGames', data)
}
function shuffleInPlace(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i)
const t = array[i]
array[i] = array[j]
array[j] = t
}
}
const Jack = 11
const Queen = 12
const King = 13
const Ace = 14
const LeftBower = 14.4
const RightBower = 14.8
const Joker = 15
const Spades = 1
const Clubs = 2
const Diamonds = 3
const Misere = 3.5
const Hearts = 4
const NoTrumps = 5
const TrumpSuit = 6
const JokerSuit = 7
const sameColour = (s1, s2) =>
s1 + s2 === 3 || s1 + s2 === 7
const contractValue = c =>
c.trumps === Misere ?
(c.n < 10 ? 250 : 500) :
(c.n - 6) * 100 + (c.trumps + 1) * 20
function calculateScore(contract, contractTricks, opponentTotal) {
const contractMade = contract.trumps === Misere ? contractTricks === 0 :
contractTricks >= contract.n
const opponentScore = contract.trumps === Misere ? 0 :
Math.min((10 - contractTricks) * 10, Math.max(460 - opponentTotal, 0))
const value = contractValue(contract)
const slam = contractTricks === 10 && value < 250
const contractScore = contractMade ? (slam ? 250 : value) : -value
return { made: contractMade, score: [contractScore, opponentScore], slam: slam }
}
function makeDeck() {
const deck = []
for (let suit = Spades; suit <= Clubs; suit++)
for (let rank = 5; rank <= Ace; rank++)
deck.push({ rank: rank, suit: suit })
for (let suit = Diamonds; suit <= Hearts; suit++)
for (let rank = 4; rank <= Ace; rank++)
deck.push({ rank: rank, suit: suit })
deck.push({ rank: Joker, suit: JokerSuit })
return deck
}
const clockwise = playerIndex => ++playerIndex === 4 ? 0 : playerIndex
const opposite = playerIndex => clockwise(clockwise(playerIndex))
function setEffective(trump) {
if (trump < NoTrumps && trump !== Misere) {
return function (c) {
if (c.rank === Jack && c.suit === trump) {
c.effectiveRank = RightBower
c.effectiveSuit = trump
}
else if (c.rank === Jack && sameColour(c.suit, trump)) {
c.effectiveRank = LeftBower
c.effectiveSuit = trump
}
else if (c.rank === Joker) {
c.effectiveRank = Joker
c.effectiveSuit = trump
}
else {
c.effectiveRank = c.rank
c.effectiveSuit = c.suit
}
if (c.effectiveSuit === trump) c.effectiveSuit = TrumpSuit
}
}
else {
return function (c) {
c.effectiveRank = c.rank
c.effectiveSuit = c.suit
}
}
}
const byEffective = (c1, c2) =>
c1.effectiveSuit === c2.effectiveSuit ?
c1.effectiveRank - c2.effectiveRank : c1.effectiveSuit - c2.effectiveSuit
function sortAndFormat(cards, trump) {
cards.forEach(setEffective(trump))
cards.sort(byEffective)
cards.forEach(c => c.formatted = formatCard(c, trump))
}
function deal(game) {
const deck = makeDeck()
shuffleInPlace(deck)
game.players.forEach(player => player.hand = [])
game.kitty = []
function dealRound(numCards) {
let dealTo = game.dealer
do {
dealTo = clockwise(dealTo)
let left = numCards
while (left--)
game.players[dealTo].hand.push(deck.pop())
} while (dealTo !== game.dealer)
game.kitty.push(deck.pop())
}
dealRound(3)
dealRound(4)
dealRound(3)
game.players.forEach(player => sortAndFormat(player.hand, NoTrumps))
sortAndFormat(game.kitty, NoTrumps)
}
const suitCls = suit =>
suit === Spades ? 'spades' :
suit === Clubs ? 'clubs' :
suit === Diamonds ? 'diamonds' :
suit === Hearts ? 'hearts' : null
const suitChr = suit =>
suit === Spades ? '♤' :
suit === Clubs ? '♧' :
suit === Diamonds ? '♢' :
suit === Hearts ? '♡' : ''
const trumpsChr = suit =>
suit === Spades ? '♠' :
suit === Clubs ? '♣' :
suit === Diamonds ? '♦' :
suit === Hearts ? '♥' :
suit === NoTrumps ? 'NT' : ''
function formatCard(c, trump) {
let chr
if (c.rank === Joker)
chr = '🃟'
else {
let codepoint = 0x1F000
codepoint +=
c.suit === Spades ? 0xA0 :
c.suit === Hearts ? 0xB0 :
c.suit === Diamonds ? 0xC0 :
c.suit === Clubs ? 0xD0 : 0
codepoint += c.rank === Ace ? 1 :
c.rank <= Jack ? c.rank : c.rank + 1
chr = String.fromCodePoint(codepoint)
}
const suit = c.effectiveSuit === TrumpSuit ? trump : c.effectiveSuit
return { chr: chr, cls: suitCls(suit) }
}
function reformatJoker(c, jsuit) {
c.formatted.cls = suitCls(jsuit)
c.formatted.chr = `🃏${suitChr(jsuit)}`
c.effectiveSuit = jsuit
}
function formatBid(b) {
if (b.pass)
b.formatted = 'Pass'
else if (b.trumps === Misere)
b.formatted = b.n < 10 ? 'Mis' : 'OMis'
else {
b.formatted = b.n.toString()
b.formatted += trumpsChr(b.trumps)
b.cls = suitCls(b.trumps)
if (!b.cls) delete b.cls
}
}
const bidSpan = b => b.cls ?
`<span class=${b.cls}>${b.formatted}</span>` : b.formatted
const cardSpan = c =>
c.chr.length > 2 ?
`<span class="${c.cls} joker">${c.chr.slice(0, -1)}<span>${c.chr[2]}</span></span>`
: c.cls ?
`<span class=${c.cls}>${c.chr}</span>`
: c.chr
const jokerSuitSpan = j =>
`<span class=${j.formatted.cls}>${trumpsChr(j.effectiveSuit)}</span>`
function validBids(lastBid) {
const bids = [{ pass: true }]
for (let n = 6; n <= 7; n++) {
if (lastBid && lastBid.n > n) continue
for (let trumps = Spades; trumps <= NoTrumps; trumps++) {
if (lastBid && lastBid.n === n && lastBid.trumps >= trumps) continue
bids.push({ n: n, trumps: trumps })
}
}
if (lastBid && lastBid.n === 7)
bids.push({ n: 7.5, trumps: Misere })
for (let n = 8; n < 10; n++) {
if (lastBid && lastBid.n > n) continue
for (let trumps = Spades; trumps <= NoTrumps; trumps++) {
if (lastBid && lastBid.n === n && lastBid.trumps >= trumps) continue
bids.push({ n: n, trumps: trumps })
}
}
for (let trumps = Spades; trumps <= NoTrumps; trumps++) {
if (lastBid && lastBid.n === 10 && lastBid.trumps >= trumps) continue
bids.push({ n: 10, trumps: trumps })
if (trumps === Diamonds) bids.push({ n: 10, trumps: Misere })
}
bids.forEach(formatBid)
return bids
}
function setRestrictJokers(player, trump, unledSuits) {
if ((trump === Misere || trump === NoTrumps) &&
player.hand.find(c => c.effectiveRank === Joker && c.effectiveSuit === JokerSuit))
player.restrictJokers = unledSuits.map(s => ({ suit: s, chr: suitChr(s), cls: suitCls(s) }))
}
function startRound(gameName) {
const game = games[gameName]
appendLog(gameName, `${game.players[game.dealer].name} deals.`)
deal(game)
game.bidding = true
delete game.lastBidder
game.whoseTurn = clockwise(game.dealer)
game.players[game.whoseTurn].current = true
game.players[game.whoseTurn].validBids = validBids()
game.players[game.whoseTurn].bidFilter = NoTrumps
io.in(gameName).emit('updatePlayers', game.players)
io.in(gameName).emit('updateKitty', { kitty: game.kitty })
io.in(gameName).emit('blameMsg', '')
}
function startPlaying(gameName) {
const game = games[gameName]
const contractor = game.players[game.lastBidder]
const trump = contractor.contract.trumps
if (trump === Misere) {
const partner = game.players[opposite(game.lastBidder)]
partner.dummy = true
if (contractor.contract.n === 10)
contractor.open = true
}
game.playing = true
game.players.forEach(player => player.tricks = [])
game.unledSuits = [Spades, Clubs, Diamonds, Hearts]
contractor.validPlays = true
setRestrictJokers(contractor, trump, game.unledSuits)
game.leader = game.lastBidder
game.trick = []
io.in(gameName).emit('updatePlayers', game.players)
}
function appendLog(gameName, entry) {
const game = games[gameName]
game.log.push(entry)
io.in(gameName).emit('appendLog', entry)
}
function restoreScore(room, teamNames, rounds, players) {
if (rounds.length) {
io.in(room).emit('initScore', teamNames)
const total = [0, 0]
for (let i = 0; i < rounds.length; i++) {
const round = rounds[i]
const team = round.contractorIndex % 2
const score = calculateScore(
round.contract, round.tricksMade, total[1 - team]).score
if (team) score.push(score.shift())
for (const i of [0, 1]) total[i] += score[i]
io.in(room).emit('appendScore', {
round: i+1,
contractor: players[round.contractorIndex].name,
contract: round.contract,
tricks: round.tricksMade,
kitty: round.kitty,
score: score,
total: total
})
}
}
else
io.in(room).emit('removeScore')
}
function checkEnd(gameName) {
const game = games[gameName]
for (const i of [0, 1]) {
if (game.total[i] >= 500 && game.lastBidder % 2 === i) {
appendLog(gameName, `${game.teamNames[i]} win!`)
for (let j = 0; j < 4; j++) {
if (j % 2 === i) game.players[j].victorious = true
}
game.ended = true
return
}
if (game.total[i] <= -500) {
appendLog(gameName, `${game.teamNames[i]} go out backwards!`)
for (let j = 0; j < 4; j++) {
if (j % 2 !== i) game.players[j].victorious = true
}
game.ended = true
return
}
}
}
const stateKeys = {
game: [
'players', 'teamNames', 'total',
'started', 'dealer',
'bidding', 'whoseTurn', 'lastBidder',
'selectKitty', 'kitty', 'origKitty', 'nominateJoker',
'playing', 'leader', 'trick', 'unledSuits',
'ended'
],
teamNames: true, total: true,
kitty: true, origKitty: true,
trick: true, unledSuits: true,
players: [
'current', 'open', 'dummy',
'validBids', 'bidFilter', 'lastBid', 'contract',
'selecting', 'nominating',
'validPlays', 'restrictJokers', 'hand', 'tricks',
'victorious'
],
validBids: true, lastBid: true, contract: true,
validPlays: true, restrictJokers: true, hand: true
}
function copy(keys, from, to, restore) {
for (const key of keys)
if (key in from) {
if (stateKeys[key] === true)
to[key] = JSON.parse(JSON.stringify(from[key]))
else if (key === 'players') {
if (!restore)
to.players = [{}, {}, {}, {}]
for (let i = 0; i < 4; i++)
copy(stateKeys.players, from.players[i], to.players[i], restore)
}
else if (stateKeys[key]) {
if (!restore || !(key in to))
to[key] = {}
copy(stateKeys[key], from[key], to[key], restore)
}
else if (key === 'tricks') {
const func = restore ?
(cards => ({ cards: JSON.parse(JSON.stringify(cards)), open: false })) :
(trick => JSON.parse(JSON.stringify(trick.cards)))
to.tricks = from.tricks.map(func)
}
else
to[key] = from[key]
}
else if (restore && key in to)
delete to[key]
}
function appendUndo(gameName) {
const game = games[gameName]
const entry = {}
copy(stateKeys.game, game, entry)
entry.logLength = game.log.length
entry.roundsLength = game.rounds.length
game.undoLog.push(entry)
io.in(gameName).emit('showUndo', true)
}
io.on('connection', socket => {
console.log(`new connection ${socket.id}`)
socket.emit('ensureLobby')
socket.join('lobby'); updateGames(socket.id)
socket.on('joinRequest', data => {
let game
let gameName = data.gameName
if (!gameName) gameName = randomUnusedGameName()
if (!(gameName in games)) {
console.log(`new game ${gameName}`)
game = { seats: [{}, {}, {}, {}],
players: [],
spectators: [] }
games[gameName] = game
}
else
game = games[gameName]
if (!data.playerName) {
socket.playerName = `Bauer${Math.floor(Math.random()*20)}`
console.log(`random name ${socket.playerName} for ${socket.id}`)
}
else {
socket.playerName = data.playerName
console.log(`name ${socket.playerName} supplied for ${socket.id}`)
}
if (data.spectate) {
if (game.spectators.every(spectator => spectator.name !== socket.playerName)) {
console.log(`${socket.playerName} joining ${gameName} as spectator`)
socket.gameName = gameName
socket.leave('lobby'); socket.emit('updateGames', [])
socket.join(gameName)
game.spectators.push({ socketId: socket.id, name: socket.playerName })
socket.emit('joinedGame',
{ gameName: gameName, playerName: socket.playerName, spectating: true })
io.in(gameName).emit('updateSpectators', game.spectators)
if (!game.started) {
socket.emit('updateUnseated', game.players)
socket.emit('updateSeats', game.seats)
}
else {
socket.emit('gameStarted')
socket.emit('updatePlayers', game.players)
socket.emit('updateKitty', { kitty: game.kitty })
if (game.trick)
socket.emit('updateTrick', { trick: game.trick, leader: game.leader })
socket.emit('appendLogs', game.log)
restoreScore(socket.id, game.teamNames, game.rounds, game.players)
}
}
else {
console.log(`${socket.playerName} barred from joining ${gameName} as duplicate spectator`)
socket.emit('errorMsg', `Game ${gameName} already contains spectator ${socket.playerName}.`)
}
}
else if (game.started) {
if (game.players.find(player => player.name === socket.playerName && !player.socketId)) {
if (socket.rooms.size === 2 && socket.rooms.has(socket.id) && socket.rooms.has('lobby')) {
console.log(`${socket.playerName} rejoining ${gameName}`)
socket.gameName = gameName
socket.leave('lobby'); socket.emit('updateGames', [])
socket.join(gameName)
const player = game.players.find(player => player.name === socket.playerName)
player.socketId = socket.id
socket.emit('joinedGame', { gameName: gameName, playerName: socket.playerName })
socket.emit('updateSpectators', game.spectators)
socket.emit('gameStarted')
io.in(gameName).emit('updatePlayers', game.players)
let kitty = { kitty: game.kitty }
if (player.contract && game.selectKitty) {
kitty.contractorName = player.name,
kitty.contractorIndex = game.lastBidder
}
socket.emit('updateKitty', kitty)
if (game.nominateJoker && player.nominating)
socket.emit('showJoker', true)
if (game.trick)
socket.emit('updateTrick', { trick: game.trick, leader: game.leader })
socket.emit('appendLogs', game.log)
restoreScore(socket.id, game.teamNames, game.rounds, game.players)
if (game.undoLog.length)
socket.emit('showUndo', true)
}
else {
console.log(`error: ${socket.playerName} rejoining ${gameName} while in ${rooms}`)
socket.emit('errorMsg', 'Error: somehow this connection is already used in another game.')
}
}
else {
console.log(`${socket.playerName} barred from joining ${gameName} as extra player`)
socket.emit('errorMsg', `Game ${gameName} has already started. Try spectating.`)
}
}
else {
if (game.players.every(player => player.name !== socket.playerName)) {
if (game.players.length < 4) {
console.log(`${socket.playerName} joining ${gameName}`)
socket.leave('lobby'); socket.emit('updateGames', [])
socket.join(gameName)
socket.gameName = gameName
game.players.push({ socketId: socket.id, name: socket.playerName })
socket.emit('joinedGame', { gameName: gameName, playerName: socket.playerName })
socket.emit('updateSpectators', game.spectators)
io.in(gameName).emit('updateUnseated', game.players)
io.in(gameName).emit('updateSeats', game.seats)
}
else {
console.log(`${socket.playerName} barred from joining ${gameName} which is full`)
socket.emit('errorMsg', `Game ${gameName} already has enough players. Try spectating.`)
}
}
else {
console.log(`${socket.playerName} barred from joining ${gameName} as duplicate player`)
socket.emit('errorMsg', `Game ${gameName} already contains player ${socket.playerName}.`)
}
}
updateGames()
})
function inGame(func) {
const gameName = socket.gameName
const game = games[gameName]
if (game) func(gameName, game)
else {
console.log(`${socket.playerName} failed to find game ${gameName}`)
socket.emit('errorMsg', `Game ${gameName} not found. Try reconnecting.`)
}
}
socket.on('undoRequest', () => inGame((gameName, game) => {
if (game.started && game.undoLog.length) {
const entry = game.undoLog.pop()
copy(stateKeys.game, entry, game, true)
io.in(gameName).emit('updatePlayers', game.players)
let kitty = { kitty: game.kitty }
if (game.selectKitty) {
kitty.contractorName = game.players[game.lastBidder].name,
kitty.contractorIndex = game.lastBidder
}
io.in(gameName).emit('updateKitty', kitty)
io.in(gameName).emit('showJoker', false)
if (game.nominateJoker) {
const player = game.players.find(p => p.nominating)
io.in(player.socketId).emit('showJoker', true)
}
if (game.trick)
io.in(gameName).emit('updateTrick', { trick: game.trick, leader: game.leader })
io.in(gameName).emit('removeLog', game.log.length - entry.logLength)
game.log.length = entry.logLength
game.rounds.length = entry.roundsLength
restoreScore(gameName, game.teamNames, game.rounds, game.players)
if (!game.undoLog.length)
io.in(gameName).emit('showUndo', false)
io.in(gameName).emit('errorMsg', `${socket.playerName} pressed Undo.`)
io.in(gameName).emit('blameMsg', '')
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried to undo nothing`)
socket.emit('errorMsg', 'Error: there is nothing to undo.')
}
}))
socket.on('sitHere', index => inGame((gameName, game) => {
if (!game.started) {
const seat = game.seats[index]
if (seat) {
if (!seat.player) {
const player = game.players.find(player => player.socketId === socket.id)
if (player) {
if (!player.seated) {
seat.player = player
player.seated = true
io.in(gameName).emit('updateUnseated', game.players)
io.in(gameName).emit('updateSeats', game.seats)
console.log(`${socket.playerName} in ${gameName} took their seat`)
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried to sit but is already seated`)
socket.emit('errorMsg', 'Error: you are already seated.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried to sit but is not a player`)
socket.emit('errorMsg', 'Error: a non-player cannot sit.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried sitting in an occupied seat`)
socket.emit('errorMsg', 'Error: trying to sit in an occupied seat.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried sitting at invalid index ${index}`)
socket.emit('errorMsg', 'Error: trying to sit at an invalid seat index.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried sitting when game already started`)
socket.emit('errorMsg', 'Error: cannot sit after the game has started.')
}
}))
socket.on('leaveSeat', () => inGame((gameName, game) => {
if (!game.started) {
const player = game.players.find(player => player.socketId === socket.id)
if (player) {
if (player.seated) {
const seat = game.seats.find(seat => seat.player && seat.player.name === player.name)
if (seat) {
delete seat.player
player.seated = false
io.in(gameName).emit('updateUnseated', game.players)
io.in(gameName).emit('updateSeats', game.seats)
console.log(`${socket.playerName} in ${gameName} left their seat`)
}
else {
console.log(`error: ${socket.playerName} in ${gameName} is tried to leave seat but no seat has them`)
socket.emit('errorMsg', 'Error: could not find you in any seat.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} is not seated but tried to leave their seat`)
socket.emit('errorMsg', 'Error: you are not seated so cannot leave your seat.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} is not a player but tried to leave a seat`)
socket.emit('errorMsg', 'Error: non-player trying to leave seat.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried leaving seat when game already started`)
socket.emit('errorMsg', 'Error: cannot leave seat after the game has started.')
}
}))
socket.on('startGame', () => inGame((gameName, game) => {
if (!game.started) {
if (game.players.length === 4 && game.seats.every(seat => seat.player)) {
console.log(`starting ${gameName}`)
game.started = true
game.undoLog = []
game.log = []
game.players = game.seats.map(seat => seat.player)
delete game.seats
game.players.forEach(player => delete player.seated)
game.teamNames = [`${game.players[0].name} & ${game.players[2].name}`,
`${game.players[1].name} & ${game.players[3].name}`]
game.total = [0, 0]
game.rounds = []
game.dealer = Math.floor(Math.random() * 4)
io.in(gameName).emit('gameStarted')
appendLog(gameName, 'The game begins!')
startRound(gameName)
updateGames()
}
else {
socket.emit('errorMsg', 'Error: 4 seated players required to start the game.')
}
}
else {
console.log(`${socket.playerName} attempted to start ${gameName} again`)
socket.emit('errorMsg', `Error: ${gameName} has already started.`)
}
}))
socket.on('filterRequest', index => inGame((gameName, game) => {
if (game.bidding) {
const current = game.players[game.whoseTurn]
if (current) {
if (current.name === socket.playerName && current.current && current.bidFilter) {
if (Number.isInteger(index) && 0 <= index && index < 5) {
current.bidFilter = index + 1
sortAndFormat(current.hand, current.bidFilter)
socket.emit('updatePlayers', game.players)
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried filtering an invalid index`)
socket.emit('errorMsg', 'Error: that is not a valid bid filter.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bid filter out of turn`)
socket.emit('errorMsg', 'Error: it is not your turn to bid filter.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bid filter but there is no current player`)
socket.emit('errorMsg', 'Error: could not find current player.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bid filter out of phase`)
socket.emit('errorMsg', 'Error: bid filtering is not currently possible.')
}
}))
socket.on('bidRequest', bid => inGame((gameName, game) => {
if (game.bidding) {
const current = game.players[game.whoseTurn]
if (current) {
if (current.name === socket.playerName && current.current) {
if (current.validBids && (bid.pass || current.validBids.find(b => b.n === bid.n && b.trumps === bid.trumps)) &&
current.bidFilter && (bid.pass || bid.trumps === current.bidFilter || bid.trumps === Misere && current.bidFilter === NoTrumps)) {
appendUndo(gameName)
delete current.validBids
delete current.bidFilter
delete current.current
current.lastBid = bid
if (!bid.pass) {
game.lastBidder = game.whoseTurn
appendLog(gameName, `${current.name} bids ${bidSpan(bid)}.`)
}
else {
sortAndFormat(current.hand, NoTrumps)
appendLog(gameName, `${current.name} passes.`)
}
let nextTurn = clockwise(game.whoseTurn)
while (game.players[nextTurn].lastBid &&
game.players[nextTurn].lastBid.pass &&
nextTurn !== game.whoseTurn)
nextTurn = clockwise(nextTurn)
const lastBidder = game.players[game.lastBidder]
const lastBid = lastBidder ? lastBidder.lastBid : null
if (nextTurn === game.whoseTurn && bid.pass) {
appendLog(gameName, 'Bidding ends with no contract. Redealing...')
game.players.forEach(player => { delete player.lastBid; delete player.bidFilter })
game.dealer = clockwise(game.dealer)
startRound(gameName)
}
else if (nextTurn === game.lastBidder) {
appendLog(gameName, `Bidding ends with ${lastBidder.name} contracting ${bidSpan(lastBid)}.`)
delete game.bidding
lastBidder.contract = lastBid
game.players.forEach(player => { delete player.lastBid; delete player.bidFilter })
game.selectKitty = true
game.whoseTurn = game.lastBidder
lastBidder.current = true
lastBidder.selecting = true
game.players.forEach(player => sortAndFormat(player.hand, lastBid.trumps))
sortAndFormat(game.kitty, lastBid.trumps)
game.origKitty = Array.from(game.kitty)
io.in(gameName).emit('updatePlayers', game.players)
io.in(gameName).emit('updateKitty',
{ kitty: game.kitty,
contractorName: lastBidder.name,
contractorIndex: game.lastBidder })
}
else {
game.whoseTurn = nextTurn
const next = game.players[game.whoseTurn]
next.current = true
next.validBids = validBids(lastBid)
const prevBid = next.lastBid
next.bidFilter = prevBid ? (prevBid.trumps === Misere ? NoTrumps : prevBid.trumps) : NoTrumps
io.in(gameName).emit('updatePlayers', game.players)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bidding an invalid bid`)
socket.emit('errorMsg', 'Error: that is not a valid bid.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bidding out of turn`)
socket.emit('errorMsg', 'Error: it is not your turn to bid.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bidding but there is no current player`)
socket.emit('errorMsg', 'Error: could not find current player.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried bidding out of phase`)
socket.emit('errorMsg', 'Error: bidding is not currently possible.')
}
}))
socket.on('kittyRequest', data => inGame((gameName, game) => {
if (game.selectKitty) {
const current = game.players[game.whoseTurn]
if (current) {
if (current.name === socket.playerName &&
current.current && current.selecting) {
if (current.contract) {
if (!data.done) {
const fromTo = data.from === 'hand' ?
[current.hand, game.kitty] : [game.kitty, current.hand]
if (Number.isInteger(data.index) &&
0 <= data.index && data.index < fromTo[0].length) {
const removed = fromTo[0].splice(data.index, 1)[0]
fromTo[1].push(removed)
fromTo[1].sort(byEffective)
io.in(gameName).emit('updatePlayers', game.players)
io.in(gameName).emit('updateKitty',
{ kitty: game.kitty,
contractorName: current.name,
contractorIndex: game.whoseTurn })
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried taking from ${data.from} with bad index ${data.index}`)
socket.emit('errorMsg', `Error: index ${data.index} for taking from ${data.from} is invalid.`)
}
}
else {
appendUndo(gameName)
appendLog(gameName, `${current.name} exchanges with the kitty.`)
delete game.selectKitty
delete current.selecting
io.in(gameName).emit('updateKitty', { kitty: game.kitty })
if ((current.contract.trumps === Misere || current.contract.trumps === NoTrumps) &&
current.hand.find(c => c.effectiveRank === Joker)) {
game.nominateJoker = true
current.nominating = true
socket.emit('showJoker', true)
}
else
startPlaying(gameName)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried taking from ${data.from} but has no contract`)
socket.emit('errorMsg', 'Error: you do not have the contract.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried taking from ${data.from} out of turn`)
socket.emit('errorMsg', `Error: it is not your turn to take from ${data.from}.`)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried taking from ${data.from} but there is no current player`)
socket.emit('errorMsg', 'Error: could not find current player.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried taking from ${data.from} out of phase`)
socket.emit('errorMsg', `Error: taking from ${data.from} is not currently possible.`)
}
}))
socket.on('jokerRequest', index => inGame((gameName, game) => {
if (game.nominateJoker) {
const current = game.players[game.whoseTurn]
if (current) {
if (current.name === socket.playerName && current.current && current.nominating) {
if (Number.isInteger(index) && 0 <= index && index < 5) {
const joker = current.hand.find(c => c.effectiveRank === Joker)
if (joker) {
if (index < 4) {
appendUndo(gameName)
reformatJoker(joker, index + 1)
current.hand.sort(byEffective)
appendLog(gameName, `${current.name} nominates joker suit ${jokerSuitSpan(joker)}.`)
}
delete game.nominateJoker
delete current.nominating
socket.emit('showJoker', false)
startPlaying(gameName)
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried nominating joker without it`)
socket.emit('errorMsg', `Error: you do not have the joker.`)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried nominating joker with invalid index`)
socket.emit('errorMsg', `Error: invalid index for nominating joker suit.`)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried nominating joker out of turn`)
socket.emit('errorMsg', `Error: it is not your turn to nominate the joker suit.`)
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried nominating joker but there is no current player`)
socket.emit('errorMsg', 'Error: could not find current player.')
}
}
else {
console.log(`error: ${socket.playerName} in ${gameName} tried nominating joker out of phase`)
socket.emit('errorMsg', `Error: nominating joker suit is not currently possible.`)
}
}))
socket.on('playRequest', data => inGame((gameName, game) => {
if (game.playing && game.trick) {
const current = game.players[game.whoseTurn]
if (current) {
if (current.name === socket.playerName && current.current) {
if (current.validPlays) {
if ((current.validPlays === true &&
Number.isInteger(data.index) && 0 <= data.index && data.index < current.hand.length ||
Array.isArray(current.validPlays) && current.validPlays.includes(data.index)) &&
(current.hand[data.index].effectiveRank !== Joker || !current.restrictJokers ||
current.restrictJokers.find(j => j.suit === data.jsuit))) {
appendUndo(gameName)
delete current.validPlays
delete current.restrictJokers
delete current.current
const played = current.hand.splice(data.index, 1)[0]
if (data.jsuit) reformatJoker(played, data.jsuit)
game.trick.push(played)
appendLog(gameName, `${current.name} plays ${cardSpan(played.formatted)}.`)
io.in(gameName).emit('updateTrick', { trick: game.trick, leader: game.leader })
io.in(gameName).emit('updatePlayers', game.players)
const contractor = game.players[game.lastBidder]
const trump = contractor.contract.trumps
const calling = game.trick[0].effectiveSuit
if (trump === Misere || trump === NoTrumps)
game.unledSuits = game.unledSuits.filter(s => s !== played.effectiveSuit)
game.whoseTurn = clockwise(game.whoseTurn)
if (game.players[game.whoseTurn].dummy) {
game.trick.push(null)
game.whoseTurn = clockwise(game.whoseTurn)
}
if (game.trick.length < 4) {
const next = game.players[game.whoseTurn]
next.current = true
if (next.hand.some(c => c.effectiveSuit === calling)) {
next.validPlays = []
next.hand.forEach((c, i) => { if (c.effectiveSuit === calling) { next.validPlays.push(i) } })
}
else if (trump === Misere) {
const jokerIndex = next.hand.findIndex(c =>
c.effectiveRank === Joker && c.effectiveSuit === JokerSuit)
next.validPlays = 0 <= jokerIndex ? [jokerIndex] : true
}
else
next.validPlays = true
io.in(gameName).emit('updatePlayers', game.players)
}
else {
let winningIndex = 0
for (let i = 1; i < 4; i++) {
const currentCard = game.trick[i]
const winningCard = game.trick[winningIndex]
if (currentCard &&
((currentCard.effectiveSuit === JokerSuit) ||
(currentCard.effectiveSuit === TrumpSuit &&
(winningCard.effectiveSuit !== TrumpSuit ||
winningCard.effectiveRank < currentCard.effectiveRank)) ||
(currentCard.effectiveSuit === calling &&
(winningCard.effectiveSuit !== calling && winningCard.effectiveSuit < TrumpSuit ||
winningCard.effectiveSuit === calling && winningCard.effectiveRank < currentCard.effectiveRank))))
winningIndex = i
}
winningIndex = (game.leader + winningIndex) % 4
const winner = game.players[winningIndex]
const winnerPartner = game.players[opposite(winningIndex)]
winner.tricks.push({ cards: game.trick.filter(c => c), open: false })
appendLog(gameName, `${winner.name} wins the trick.`)
delete game.whoseTurn
game.trick = []