This repository has been archived by the owner on Mar 5, 2023. It is now read-only.
forked from jogramming/cardsagainstdiscord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.go
1237 lines (1009 loc) · 27.7 KB
/
game.go
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
package cardsagainstdiscord
import (
"fmt"
"github.com/jonas747/discordgo"
"log"
"math/rand"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
)
type GameState int
/*
Game Loop: If a player has enough wins to win the game
pregame ------------------<|
| |
PreRoundDelay ------------<|
| |
PickingResponses |
| |
Picking winner |
|>----------------------^
*/
const (
GameStatePreGame GameState = 0 // Before the game starts
GameStatePreRoundDelay GameState = 1 // Countdown before a roundn starts
GameStatePickingResponses GameState = 2 // Players are picking responses for the prompt card
GameStatePickingWinner GameState = 3 // Cardzar is picking the winning response
GameStateEnded GameState = 4 // Game is over, someone won
)
const (
PreRoundDelayDuration = time.Second * 15
PickResponseDuration = time.Second * 60
PickWinnerDuration = time.Second * 90
GameExpireAfter = time.Second * 300
GameExpireAfterPregame = time.Minute * 30
BlankCard ResponseCard = "(write your own response)"
)
var (
CardSelectionEmojis = []string{
"🇦", // A
"🇧", // B
"🇨", // C
"🇩", // D
"🇪", // E
"🇫", // F
"🇬", // G
"🇭", // H
"🇮", // I
"🇯", // J
"🇰", // K
}
JoinEmoji = "➕"
LeaveEmoji = "➖"
PlayPauseEmoji = "⏯"
)
type Game struct {
sync.RWMutex `json:"-" msgpack:"-"`
// Never chaged
Manager *GameManager `json:"-" msgpack:"-"`
Session *discordgo.Session `json:"-" msgpack:"-"`
// The main channel this game resides in, never changes
MasterChannel int64
// The server the game resides in, never changes
GuildID int64
// The user that created this game
GameMaster int64
// The current cardzar
CurrentCardCzar int64
PlayerLimit int
WinLimit int
VoteMode bool
Packs []string
availablePrompts []*PromptCard
availableResponses []ResponseCard
Players []*Player
State GameState
StateEntered time.Time
// The time the most recent action was taken, if we go too long without a user action we expire the game
LastAction time.Time
CurrentPropmpt *PromptCard
LastMenuMessage int64
Responses []*PickedResonse
stopped bool
tickerRunning bool
stopch chan bool
}
type PickedResonse struct {
Player *Player
Selections []ResponseCard
}
func (g *Game) Created() error {
g.LastAction = time.Now()
embed := &discordgo.MessageEmbed{
Title: "Game created!",
Description: fmt.Sprintf("React with %s to join and %s to leave, the game master can start/stop the game with %s", JoinEmoji, LeaveEmoji, PlayPauseEmoji),
}
msg, err := g.Session.ChannelMessageSendEmbed(g.MasterChannel, embed)
if err != nil {
return err
}
g.LastMenuMessage = msg.ID
g.stopch = make(chan bool)
g.loadPackPrompts()
g.loadPackResponses()
go g.runTicker()
go g.addCommonMenuReactions(msg.ID)
g.tickerRunning = true
return nil
}
func (g *Game) loadPackResponses() {
for _, v := range g.Packs {
pack := Packs[v]
g.availableResponses = append(g.availableResponses, pack.Responses...)
}
}
func (g *Game) loadPackPrompts() {
for _, v := range g.Packs {
pack := Packs[v]
g.availablePrompts = append(g.availablePrompts, pack.Prompts...)
}
}
// AddPlayer attempts to add a player to the game, if it fails (hit the limit for example) then it returns false
func (g *Game) AddPlayer(id int64, username string) bool {
g.Lock()
defer g.Unlock()
return g.addPlayer(id, username)
}
func (g *Game) addPlayer(id int64, username string) bool {
// 500 is max capacity
if 500 <= len(g.Players) {
return false
}
numPlaying := 0
for _, v := range g.Players {
if v.InGame {
numPlaying++
}
}
if numPlaying >= g.PlayerLimit {
return false
}
msg := ""
// Create a userchannel and cache it for use later
existing := g.findPlayer(id)
if existing != nil {
if existing.Banned {
return false
}
existing.InGame = true
msg = "Came back!"
} else {
channel, err := g.Session.UserChannelCreate(id)
if err != nil {
return false
}
p := &Player{
ID: id,
Username: username,
Channel: channel.ID,
Cards: g.getRandomPlayerCards(8),
InGame: true,
}
g.Players = append(g.Players, p)
msg = "Joined the game!"
}
go g.sendAnnouncment(fmt.Sprintf("<@%d> %s! (%d/%d)", id, msg, numPlaying+1, g.PlayerLimit), false)
return true
}
func (g *Game) findPlayer(id int64) *Player {
for _, v := range g.Players {
if v.ID == id {
return v
}
}
return nil
}
func (g *Game) RemovePlayer(id int64) bool {
g.Lock()
defer g.Unlock()
return g.removePlayer(id)
}
func (g *Game) removePlayer(id int64) bool {
found := false
numPlaying := 0
for i, v := range g.Players {
if v.ID == id {
if !v.InGame {
return false
}
// Don't remember more than 200 players, if this limit is reached its more than likely abuse
if len(g.Players) > 200 {
// Above limit, remove them entirely
g.Players = append(g.Players[:i], g.Players[i+1:]...)
} else {
// Just mark them as not in game
v.InGame = false
}
found = true
continue
}
if v.InGame {
numPlaying++
}
}
if !found {
return false
}
go g.sendAnnouncment(fmt.Sprintf("<@%d> Left the game (%d/%d)", id, numPlaying, g.PlayerLimit), false)
if g.CurrentCardCzar == id && g.State != GameStatePreGame && g.State != GameStatePreRoundDelay {
g.nextRound()
}
if g.GameMaster == id && numPlaying > 0 {
for _, v := range g.Players {
if v.InGame {
g.GameMaster = v.ID
go g.sendAnnouncment(fmt.Sprintf("GameMaster left, assigned <@%d> as new game master.", v.ID), false)
break
}
}
}
return true
}
func (g *Game) setState(state GameState) {
g.State = state
g.StateEntered = time.Now()
}
func (g *Game) nextRound() {
g.setState(GameStatePreRoundDelay)
}
func (g *Game) getRandomResponseCard() ResponseCard {
if len(g.availableResponses) < 1 {
g.loadPackResponses() // re-shuffle basically, TODO: exclude current hands
}
i := rand.Intn(len(g.availableResponses))
card := g.availableResponses[i]
g.availableResponses = append(g.availableResponses[:i], g.availableResponses[i+1:]...)
// check whether a blank card was selected, return BlankCard if so
if string(card) == "%blank" { // This is the string that signifies a blank card
card = BlankCard
}
return card
}
func (g *Game) getRandomPlayerCards(num int) []ResponseCard {
result := make([]ResponseCard, 0, num)
if len(g.availableResponses) < 1 {
return result
}
for len(result) < num {
card := g.getRandomResponseCard()
result = append(result, card)
}
return result
}
func (g *Game) sendAnnouncment(msg string, allPlayers bool) {
embed := &discordgo.MessageEmbed{
Description: msg,
}
if allPlayers {
for _, v := range g.Players {
go func(channel int64) {
g.Session.ChannelMessageSendEmbed(channel, embed)
}(v.Channel)
}
}
g.Session.ChannelMessageSendEmbed(g.MasterChannel, embed)
}
func (g *Game) sendAnnouncmentMenu(msg string) {
embed := &discordgo.MessageEmbed{
Description: msg,
}
m, err := g.Session.ChannelMessageSendEmbed(g.MasterChannel, embed)
if err == nil {
g.LastMenuMessage = m.ID
go g.addCommonMenuReactions(m.ID)
}
}
func (g *Game) Stop() {
g.Lock()
g.stop()
g.Unlock()
}
func (g *Game) stop() {
if g.stopped {
return // Already stopped
}
g.stopped = true
close(g.stopch)
}
func (g *Game) runTicker() {
defer func() {
if r := recover(); r != nil {
stack := string(debug.Stack())
log.Println("CAH: cid: ", g.MasterChannel, " recovered from panic in running game!: ", r, "\n", stack)
go g.Session.ChannelMessageSend(g.MasterChannel, "The running game almost caused a crash! The game has been terminated as a result. Contact the bot owner.")
go g.Manager.RemoveGame(g.MasterChannel)
}
}()
ticker := time.NewTicker(time.Second)
for {
select {
case <-g.stopch:
return
case <-ticker.C:
g.Tick()
}
}
}
func (g *Game) Tick() {
g.Lock()
defer g.Unlock()
expireAfter := GameExpireAfter
if g.State == GameStatePreGame {
expireAfter = GameExpireAfterPregame
}
if time.Since(g.LastAction) > expireAfter || g.numUsersInGame() < 1 {
g.gameExpired()
return
}
switch g.State {
case GameStatePreGame:
return
case GameStatePreRoundDelay:
if time.Since(g.StateEntered) > PreRoundDelayDuration {
g.startRound()
return
}
case GameStatePickingResponses:
allPlayersDone := true
oneResponsePicked := false
for _, v := range g.Players {
if v.ID == g.CurrentCardCzar || !v.PlayingThisRound() {
continue
}
if !v.MadeSelections(g.CurrentPropmpt) {
allPlayersDone = false
if !v.sent15sWarning && time.Since(g.StateEntered) > (PickResponseDuration-(time.Second*15)) {
v.sent15sWarning = true
go g.Session.ChannelMessageSendEmbed(v.Channel, &discordgo.MessageEmbed{Description: "You have 15 seconds left"})
}
} else {
oneResponsePicked = true
}
}
if allPlayersDone || time.Since(g.StateEntered) >= PickResponseDuration {
if oneResponsePicked {
g.donePickingResponses()
} else {
// No one picked any cards...?
g.sendAnnouncment("No one picked any cards, going to next round", false)
g.nextRound()
}
}
case GameStatePickingWinner:
if !g.VoteMode {
cardCzarPlayer := g.findPlayer(g.CurrentCardCzar)
if cardCzarPlayer == nil {
return
}
if !cardCzarPlayer.sent15sWarning && time.Since(g.StateEntered) > (PickWinnerDuration-(time.Second*15)) {
cardCzarPlayer.sent15sWarning = true
go g.Session.ChannelMessageSendEmbed(g.MasterChannel, &discordgo.MessageEmbed{Description: "You have 15 seconds left to pick a winner"})
}
}
if time.Since(g.StateEntered) >= PickWinnerDuration {
for _, v := range g.Players {
if v.VotedFor != 0 {
g.allVoted()
break
}
}
g.pickWinnerExpired()
}
}
}
func (g *Game) numUsersInGame() int {
num := 0
for _, v := range g.Players {
if v.InGame {
num++
}
}
return num
}
func (g *Game) startRound() {
if g.numUsersInGame() < 2 {
g.setState(GameStatePreGame)
g.sendAnnouncment("Not enough players...", false)
return
}
// Remove previous selected cards from players decks
for _, v := range g.Responses {
for _, sel := range v.Selections {
for i, c := range v.Player.Cards {
if c == sel {
v.Player.Cards = append(v.Player.Cards[:i], v.Player.Cards[i+1:]...)
break
}
}
}
}
g.Responses = nil
for _, v := range g.Players {
v.SelectedCards = nil
v.sent15sWarning = false
v.VotedFor = 0
v.ReceivedVotes = 0
if v.InGame {
v.Playing = true
}
}
lastPick := 1
if g.CurrentPropmpt != nil {
lastPick = g.CurrentPropmpt.NumPick
}
// Pick random propmpt
g.CurrentPropmpt = g.randomPrompt()
// Give each player a random card (if they're below 10 cards)
g.giveEveryoneCards(lastPick)
if !g.VoteMode {
// Pick next cardzar
g.CurrentCardCzar = NextCardCzar(g.Players, g.CurrentCardCzar)
}
// Present the board
g.presentStartRound()
g.setState(GameStatePickingResponses)
}
func NextCardCzar(players []*Player, current int64) int64 {
var next int64
var lowest int64
for _, v := range players {
if v.ID == current || !v.PlayingThisRound() {
continue
}
if v.ID > current && (v.ID < next || next == 0) {
next = v.ID
}
if lowest == 0 || v.ID < lowest {
lowest = v.ID
}
}
if next == 0 {
next = lowest
}
return next
}
func (g *Game) randomPrompt() *PromptCard {
if len(g.availablePrompts) < 1 {
g.loadPackPrompts() // ran out of cards, just relaod the packs
}
i := rand.Intn(len(g.availablePrompts))
prompt := g.availablePrompts[i]
g.availablePrompts = append(g.availablePrompts[:i], g.availablePrompts[i+1:]...)
return prompt
}
func (g *Game) giveEveryoneCards(num int) {
for _, p := range g.Players {
if !p.PlayingThisRound() || len(p.Cards) >= 10 {
continue
}
if !g.VoteMode && p.ID == g.CurrentCardCzar {
continue
}
if num+len(p.Cards) > 10 {
num = 10 - len(p.Cards)
}
cards := g.getRandomPlayerCards(num)
p.Cards = append(p.Cards, cards...)
}
}
func (g *Game) presentStartRound() {
for _, player := range g.Players {
go func(p *Player) {
if !p.PlayingThisRound() {
return
}
p.PresentBoard(g.Session, g.CurrentPropmpt, g.CurrentCardCzar)
}(player)
}
instructions := fmt.Sprintf("Players: Check your dm for your cards and make your selections there, then return here, you have %d seconds", int(PickResponseDuration.Seconds()))
if g.VoteMode {
instructions += "\nAfter that you will all vote on the response"
} else {
instructions += "\nCardCzar: Wait until all players have picked card(s) then select the best one(s)"
}
fields := []*discordgo.MessageEmbedField{
&discordgo.MessageEmbedField{
Name: "Prompt",
Value: g.CurrentPropmpt.PlaceHolder(),
},
}
if !g.VoteMode {
fields = append(fields, &discordgo.MessageEmbedField{
Name: "CardCzar",
Value: fmt.Sprintf("<@%d>", g.CurrentCardCzar),
})
}
fields = append(fields, &discordgo.MessageEmbedField{
Name: "Instructions",
Value: instructions,
})
embed := &discordgo.MessageEmbed{
Title: "Next round started!",
Color: 7001855,
// Description: msg,
Fields: fields,
}
m, err := g.Session.ChannelMessageSendEmbed(g.MasterChannel, embed)
if err == nil {
g.LastMenuMessage = m.ID
go g.addCommonMenuReactions(m.ID)
}
}
func (g *Game) donePickingResponses() {
// Send a message to players that missed the round
for _, v := range g.Players {
if !v.PlayingThisRound() || (!g.VoteMode && v.ID == g.CurrentCardCzar) {
continue
}
if len(v.SelectedCards) < g.CurrentPropmpt.NumPick {
go g.Session.ChannelMessageSend(v.Channel, fmt.Sprintf("You didn't respond in time... winner is being picked in <#%d>", g.MasterChannel))
v.SelectedCards = nil
continue
}
selections := make([]ResponseCard, 0, len(v.SelectedCards))
for _, sel := range v.SelectedCards {
selections = append(selections, v.Cards[sel])
}
g.Responses = append(g.Responses, &PickedResonse{
Player: v,
Selections: selections,
})
}
// Shuffle them
perm := rand.Perm(len(g.Responses))
newResponses := make([]*PickedResonse, len(g.Responses))
for i, v := range perm {
newResponses[i] = g.Responses[v]
}
g.Responses = newResponses
// Shows all the picks in both dm's and main channel
g.setState(GameStatePickingWinner)
g.presentPickedResponseCards(false)
}
func (g *Game) presentPickedResponseCards(edit bool) {
desc := "Cards have been picked, "
if g.VoteMode {
desc += "you will now all vote on the best one, you cannot vote on your own selection."
} else {
desc += fmt.Sprintf("pick the best one(s) <@%d>!", g.CurrentCardCzar)
}
secondsLeft := int((PickWinnerDuration - time.Since(g.StateEntered)).Seconds())
desc += fmt.Sprintf(" You have `%d` seconds.", secondsLeft)
embed := &discordgo.MessageEmbed{
Title: "Pick the winner",
Description: desc,
Color: 5659830,
Fields: []*discordgo.MessageEmbedField{
&discordgo.MessageEmbedField{
Name: "Prompt",
Value: g.CurrentPropmpt.PlaceHolder(),
},
&discordgo.MessageEmbedField{
Name: "Candidates",
},
},
}
currentEmbedField := embed.Fields[1]
for i, v := range g.Responses {
text := ""
filledPrompt := g.CurrentPropmpt.WithCards(v.Selections)
if g.VoteMode {
text = fmt.Sprintf("%s: %s (`%d`) \n\n", CardSelectionEmojis[i], filledPrompt, v.Player.ReceivedVotes)
} else {
text = CardSelectionEmojis[i] + ": " + filledPrompt + "\n\n"
}
// Embed field values can be max 1024 in length, so make new fields as needed
if currentEmbedField.Value != "" && utf8.RuneCountInString(currentEmbedField.Value)+utf8.RuneCountInString(text) > 1000 {
newField := &discordgo.MessageEmbedField{
Name: "...",
Value: text,
}
embed.Fields = append(embed.Fields, newField)
currentEmbedField = newField
} else {
currentEmbedField.Value += text
}
}
if g.VoteMode {
remainingPlayersField := &discordgo.MessageEmbedField{
Name: "Waiting for...",
}
for _, v := range g.Players {
if v.PlayingThisRound() && v.VotedFor == 0 {
if remainingPlayersField.Value != "" {
remainingPlayersField.Value += ", "
}
remainingPlayersField.Value += "<@" + discordgo.StrID(v.ID) + ">"
}
}
if remainingPlayersField.Value != "" {
embed.Fields = append(embed.Fields, remainingPlayersField)
}
}
if edit {
g.Session.ChannelMessageEditEmbed(g.MasterChannel, g.LastMenuMessage, embed)
return
}
msg, err := g.Session.ChannelMessageSendEmbed(g.MasterChannel, embed)
if err != nil {
return
}
numOptions := len(g.Responses)
go func() {
for i := 0; i < numOptions; i++ {
g.Session.MessageReactionAdd(g.MasterChannel, msg.ID, CardSelectionEmojis[i])
}
g.addCommonMenuReactions(msg.ID)
}()
g.LastMenuMessage = msg.ID
}
func (g *Game) pickWinnerExpired() {
var content string
if g.VoteMode {
content = fmt.Sprintf("no one voted for anyone in %d seconds, skipping round...", int(PickWinnerDuration.Seconds()))
} else {
content = fmt.Sprintf("<@%d> didn't pick a winner in %d seconds, skipping round...", g.CurrentCardCzar, int(PickWinnerDuration.Seconds()))
}
msg, err := g.Session.ChannelMessageSend(g.MasterChannel, content)
if err == nil {
go g.addCommonMenuReactions(msg.ID)
}
g.setState(GameStatePreRoundDelay)
}
func (g *Game) gameExpired() {
g.Session.ChannelMessageSend(g.MasterChannel, "CAH Game expired, too long without any actions or no players.")
go g.Manager.RemoveGame(g.MasterChannel)
g.stop()
}
func (g *Game) addCommonMenuReactions(mID int64) {
g.Session.MessageReactionAdd(g.MasterChannel, mID, JoinEmoji)
g.Session.MessageReactionAdd(g.MasterChannel, mID, LeaveEmoji)
g.Session.MessageReactionAdd(g.MasterChannel, mID, PlayPauseEmoji)
}
func (g *Game) HandleRectionAdd(ra *discordgo.MessageReactionAdd) {
g.Lock()
defer g.Unlock()
if g.State == GameStateEnded {
return
}
player := g.findPlayer(ra.UserID)
if ra.MessageID == g.LastMenuMessage {
switch ra.Emoji.Name {
case JoinEmoji:
if player != nil && player.InGame {
return
}
go func() {
username := ""
if player == nil {
member, err := g.Session.GuildMember(g.GuildID, ra.UserID)
if err != nil || member.User.Bot {
return
}
username = member.User.Username
} else {
username = player.Username
}
if err := g.Manager.PlayerTryJoinGame(g.MasterChannel, ra.UserID, username); err == nil {
g.Lock()
g.LastAction = time.Now()
g.Unlock()
}
}()
return
case LeaveEmoji:
go g.Manager.PlayerTryLeaveGame(ra.UserID)
g.LastAction = time.Now()
return
case PlayPauseEmoji:
g.LastAction = time.Now()
if g.State == GameStatePreGame && g.GameMaster == ra.UserID {
g.setState(GameStatePreRoundDelay)
go g.sendAnnouncment(fmt.Sprintf("Starting in %d seconds", int(PreRoundDelayDuration.Seconds())), false)
} else if g.GameMaster == ra.UserID {
for _, v := range g.Players {
v.SelectedCards = nil
}
g.Responses = nil
g.setState(GameStatePreGame)
go g.sendAnnouncmentMenu(fmt.Sprintf("Paused, react with %s to continue, the game can be paused for max 30 minutes before it expires.", PlayPauseEmoji))
}
return
default:
}
}
// From here on out only players can take actions
if player == nil {
return
}
switch g.State {
case GameStatePickingResponses:
if ra.MessageID != player.LastReactionMenu {
return
}
g.LastAction = time.Now()
g.playerPickedResponseReaction(player, ra)
case GameStatePickingWinner:
if ra.MessageID != g.LastMenuMessage || (player.ID != g.CurrentCardCzar && !g.VoteMode) {
return
}
emojiIndex := -1
for i, v := range CardSelectionEmojis {
if v == ra.Emoji.Name {
emojiIndex = i
break
}
}
if emojiIndex == -1 || emojiIndex >= len(g.Responses) {
return
}
if g.VoteMode {
targetPlayer := g.Responses[emojiIndex].Player
if targetPlayer.ID != player.ID && player.VotedFor == 0 {
player.VotedFor = targetPlayer.ID
targetPlayer.ReceivedVotes++
}
g.LastAction = time.Now()
g.presentPickedResponseCards(true)
for _, v := range g.Players {
if v.PlayingThisRound() {
if v.VotedFor == 0 {
return
}
}
}
// Game is done
g.allVoted()
} else {
winner := g.Responses[emojiIndex]
winner.Player.Wins++
g.presentWinners([]*PickedResonse{winner})
if g.Players[0].Wins >= g.WinLimit {
go g.Manager.RemoveGame(g.MasterChannel)
g.setState(GameStateEnded)
} else {
g.setState(GameStatePreRoundDelay)
g.LastAction = time.Now()
}
}
}
}
func (g *Game) HandleMessageCreate(msg *discordgo.MessageCreate) {
g.Lock()
defer g.Unlock()
var player *Player
for _, v := range g.Players {
if v.ID == msg.Author.ID {
player = v
break
}
}
if player == nil || !player.FilingBlankCard {
return
}
for _, v := range player.SelectedCards {
card := player.Cards[v]
if card == BlankCard {
player.Cards[v] = ResponseCard(FilterEveryoneMentions(msg.ContentWithMentionsReplaced()))
msg := "Selected **" + msg.ContentWithMentionsReplaced() + "**, "
if len(player.SelectedCards) < g.CurrentPropmpt.NumPick {
msg += fmt.Sprintf("select %d more card(s)", g.CurrentPropmpt.NumPick-len(player.SelectedCards))
} else {
msg += fmt.Sprintf("go to <#%d> and wait for the other players to finish their selections, the winner will be picked there", g.MasterChannel)
}
go g.Session.ChannelMessageSendEmbed(player.Channel, &discordgo.MessageEmbed{
Description: msg,
})
break
}
}
player.FilingBlankCard = false
}
const zeroWidthSpace = ""
var (
mentionReplacer = strings.NewReplacer("@here", "@"+zeroWidthSpace+"here", "@everyone", "@"+zeroWidthSpace+"everyone")
)
func FilterEveryoneMentions(s string) string {
s = mentionReplacer.Replace(s)
return s
}
func (g *Game) allVoted() {
winners := make([]*PickedResonse, 0)
// Find the top votes
winningVotes := 0
for _, resp := range g.Responses {
if resp.Player.ReceivedVotes > winningVotes {
winningVotes = resp.Player.ReceivedVotes
}
}
for _, resp := range g.Responses {
if resp.Player.ReceivedVotes == winningVotes {
winners = append(winners, resp)
resp.Player.Wins++
}
}
g.presentWinners(winners)
if g.Players[0].Wins >= g.WinLimit {