-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.go
863 lines (708 loc) · 26 KB
/
engine.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
package main
import (
"fmt"
"go.uber.org/zap"
"math/rand"
"os"
"os/exec"
"strconv"
)
//Source for rules: https://www.ultraboardgames.com/ticket-to-ride/game-rules.php
type Engine struct {
playerList []Player // a list of Player objects, used to simulate the game
activePlayer int // the current Player whose turn it is
trainCardHands [][]int //the engine keeps track of who has what cards: TrainCard[i][j]=the ith player has how many of the j'th color of card
destinationTicketHands [][]DestinationTicket //which player has what destinationTickets: used for scoring purposes
numTrains []int //how many trains the i'th player has left: the game will end when this is 0 for any player
destinationNames []string //the list of destination names
stringColors []string //the names of colors
trackList []Track //the main game board:an array of Tracks, each track is a single edge
trackStatus []int //stores the current status of each track: which player owns it, or -1 for unoccupied
faceUpTrainCards []int //the cards currently face up on the table, indexed by color
pileOfTrainCards []GameColor //the facedown stack of train cards
discardPileOfTrainCards []GameColor
pileOfDestinationTickets []DestinationTicket //the facedown stack of destination tickets
gameConstants GameConstants
adjacencyList [][]int
OptimizerMode bool
falseMoveCount int
}
func (e *Engine) initializePileOfTrainCards(toExclude []int) {
e.pileOfTrainCards = nil //clear the pile
//put all the cards into the pile
for _, c := range listOfGameColors {
if c == Rainbow {
for i := 0; i < e.gameConstants.NumRainbowCards-toExclude[c]; i++ {
e.pileOfTrainCards = append(e.pileOfTrainCards, c)
}
} else {
for i := 0; i < e.gameConstants.NumColorCards-toExclude[c]; i++ {
e.pileOfTrainCards = append(e.pileOfTrainCards, c)
}
}
}
//shuffle the deck
rand.Shuffle(len(e.pileOfTrainCards), func(i, j int) {
e.pileOfTrainCards[i], e.pileOfTrainCards[j] = e.pileOfTrainCards[j], e.pileOfTrainCards[i]
})
}
func (e *Engine) drawTopTrainCard() GameColor {
if len(e.pileOfTrainCards) == 0 {
////let's figure out what we need to exclude
//
//toExclude := make([]int, e.gameConstants.NumGameColors)
//for j := 0; j < e.gameConstants.NumGameColors; j++ {
// //first, exclude cards that are face up on the table
// toExclude[j] += e.faceUpTrainCards[j]
// for i := range e.playerList {
// //exclude cards that are in players' hands
// toExclude[j] += e.trainCardHands[i][j]
// }
//}
//
//e.initializePileOfTrainCards(toExclude)
if len(e.discardPileOfTrainCards) == 0 {
// if it's still zero, then all cards are in players' hands, we cannot draw any more
panic("Not Enough Cards in The Deck")
} else {
e.pileOfTrainCards = e.discardPileOfTrainCards
e.discardPileOfTrainCards = nil
rand.Shuffle(len(e.pileOfTrainCards), func(i, j int) {
e.pileOfTrainCards[i],e.pileOfTrainCards[j]=e.pileOfTrainCards[j],e.pileOfTrainCards[i]
})
}
}
index := len(e.pileOfTrainCards) - 1 // Get the index of the top most element.
element := (e.pileOfTrainCards)[index] // Index into the slice and obtain the element.
e.pileOfTrainCards = (e.pileOfTrainCards)[:index] // Remove it from the stack by slicing it off.
return element
}
func (e *Engine) logGiveCardToPlayer(p int, c GameColor, toHideColorWhenInforming bool) {
if *toLog {
zap.L().Info("Engine: Giving a card of Color "+stringColors[c]+" to player "+strconv.Itoa(p),
zap.String("EVENT", "GIVING_TRAIN_CARD"),
zap.String("COLOR", stringColors[c]),
zap.Int("PLAYER", p),
)
}
if *toUseVisualizer {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Giving a card of Color "+stringColors[c]+" to player "+strconv.Itoa(p))
}
}
func (e *Engine) giveCardToPlayer(p int, c GameColor, toHideColorWhenInforming bool) {
e.logGiveCardToPlayer(p,c,toHideColorWhenInforming)
//update the engine's copy
e.trainCardHands[p][c]++
//give the player his card
e.playerList[p].giveTrainCard(c)
//tell everybody else what happened
for _, pl := range e.playerList {
if toHideColorWhenInforming {
pl.informCardPickup(p, Other)
} else {
pl.informCardPickup(p, c)
}
}
}
func (e *Engine) logGiveDestinationTicketToPlayer(p int, ticket DestinationTicket){
if *toLog {
zap.L().Info("Engine: Giving a destination ticket from "+e.destinationNames[ticket.d1]+" to "+e.destinationNames[ticket.d2]+" of score "+strconv.Itoa(ticket.points)+" to player "+strconv.Itoa(p),
zap.String("EVENT", "GIVING_DESTINATION_TICKET"),
zap.String("DEST_1", e.destinationNames[ticket.d1]),
zap.String("DEST_2", e.destinationNames[ticket.d2]),
zap.Int("SCORE", ticket.points),
zap.Int("PLAYER", p),
)
}
if *toUseVisualizer {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Giving a destination ticket from "+e.destinationNames[ticket.d1]+" to "+e.destinationNames[ticket.d2]+" of score "+strconv.Itoa(ticket.points)+" to player "+strconv.Itoa(p))
}
}
func (e *Engine) giveDestinationTicketToPlayer(p int, ticket DestinationTicket) {
e.logGiveDestinationTicketToPlayer(p, ticket)
//update the engine's copy
e.destinationTicketHands[p] = append(e.destinationTicketHands[p], ticket)
//give the player his card
e.playerList[p].giveDestinationTicket(ticket)
//tell everybody else what happened
for _, pl := range e.playerList {
pl.informDestinationTicketPickup(p)
}
}
func (e *Engine) initializeDestinationTicketPile() {
//assign
e.pileOfDestinationTickets = listOfDestinationTickets
// shuffle
rand.Shuffle(len(e.pileOfDestinationTickets), func(i, j int) {
e.pileOfDestinationTickets[i], e.pileOfDestinationTickets[j] = e.pileOfDestinationTickets[j], e.pileOfDestinationTickets[i]
})
}
func (e *Engine) drawTopDestinationTicket() (DestinationTicket, bool) {
if len(e.pileOfDestinationTickets) == 0 {
return DestinationTicket{}, false
}
index := len(e.pileOfDestinationTickets) - 1 // Get the index of the top most element.
element := (e.pileOfDestinationTickets)[index] // Index into the slice and obtain the element.
e.pileOfDestinationTickets = (e.pileOfDestinationTickets)[:index] // Remove it from the stack by slicing it off.
return element, true
}
func (e *Engine) populateAdjacencyList() {
e.adjacencyList = make([][]int, e.gameConstants.NumDestinations)
for i := 0; i < e.gameConstants.NumDestinations; i++ {
e.adjacencyList[i] = make([]int, 0)
}
for i, edge := range e.trackList {
e.adjacencyList[edge.d1] = append(e.adjacencyList[edge.d1], i)
e.adjacencyList[edge.d2] = append(e.adjacencyList[edge.d2], i)
}
}
func (e *Engine) initializeGame(playerList []Player, constants GameConstants) {
//TODO: some of these things refer to global variables, ideally we don't want that, everything can be a parameter
//e.OptimizerMode = false
e.falseMoveCount = 0
e.playerList = playerList
e.activePlayer = 0
e.destinationNames=destinationNames
e.stringColors=stringColors
e.gameConstants = constants
e.gameConstants.NumPlayers = len(e.playerList)
e.trackList = listOfTracks
e.gameConstants.NumTracks = len(e.trackList)
e.trackStatus = make([]int, len(e.trackList))
for i := range e.trackStatus {
e.trackStatus[i] = -1
}
//populate adjacency List
e.populateAdjacencyList()
//set numTrains
e.numTrains = make([]int, len(e.playerList))
for i := range e.playerList {
e.numTrains[i] = e.gameConstants.NumStartingTrains
}
//ADDING RETURN FOR DEBUGGING PURPOSES
for i, p := range e.playerList {
p.initialize(i, e.trackList,e.adjacencyList, e.gameConstants)
// initialize each player
}
e.faceUpTrainCards = make([]int, e.gameConstants.NumGameColors)
e.trainCardHands = make([][]int, e.gameConstants.NumPlayers)
for i,_ := range e.playerList {
e.trainCardHands[i] = make([]int, e.gameConstants.NumGameColors)
}
// set up the pile of traincards (face up cards are initially all 0)
e.initializePileOfTrainCards(e.faceUpTrainCards)
e.destinationTicketHands = make([][]DestinationTicket, e.gameConstants.NumPlayers)
for i := range e.playerList {
//give each player the initial train cards, don't announce card color
for j := 0; j < e.gameConstants.NumInitialTrainCardsDealt; j++ {
e.giveCardToPlayer(i, e.drawTopTrainCard(), true)
}
}
// set up the pile of destination tickets
e.initializeDestinationTicketPile()
// give each player destination tickets
for i := range e.playerList {
//give each player the initial destination tickets
e.runDestinationTokenCollectionPhase(i, e.gameConstants.NumInitialDestinationTicketsOffered, e.gameConstants.NumInitialDestinationTicketsPicked)
}
}
func (e *Engine) runCollectionPhase() bool {
if e.OptimizerMode {
// want to avoid panics in optimizer mode, so we don't let the player draw if the pile is empty
if len(e.pileOfTrainCards) == 0 && len(e.discardPileOfTrainCards) == 0{
return false
}
}
//fmt.Println(e.pileOfTrainCards)
//fmt.Println(e.discardPileOfTrainCards)
//fmt.Println(e.OptimizerMode)
whichColor := e.playerList[e.activePlayer].askPickup(2, e.faceUpTrainCards)
if whichColor != Other {
// he wants a faceup card
if e.faceUpTrainCards[whichColor] <= 0 {
// he cannot pick that card
panic("The player picked a missing color")
}
e.giveCardToPlayer(e.activePlayer, whichColor, false)
e.faceUpTrainCards[whichColor]--
e.faceUpTrainCards[e.drawTopTrainCard()]++
if whichColor == Rainbow {
// picking a rainbow color costs 2, so you're done
return true
}
} else {
// asking for a random card from the deck
e.giveCardToPlayer(e.activePlayer, e.drawTopTrainCard(), true)
}
if e.OptimizerMode {
// want to avoid panics in optimizer mode, so we don't let the player draw if the pile is empty
if len(e.pileOfTrainCards) == 0 && len(e.discardPileOfTrainCards) == 0 {
return false
}
}
//zap.S().Info(e.pileOfTrainCards)
//zap.S().Info(e.discardPileOfTrainCards)
//fmt.Println(e.pileOfTrainCards)
//fmt.Println(e.discardPileOfTrainCards)
whichColor = e.playerList[e.activePlayer].askPickup(1, e.faceUpTrainCards)
if whichColor == Rainbow {
panic("The player picked a rainbow on his second turn")
}
if whichColor != Other {
// he wants a faceup card
if e.faceUpTrainCards[whichColor] <= 0 {
// he cannot pick that card
panic("The player picked a missing color")
}
e.giveCardToPlayer(e.activePlayer, whichColor, false)
e.faceUpTrainCards[whichColor]--
e.faceUpTrainCards[e.drawTopTrainCard()]++
} else {
// asking for a random card from the deck
e.giveCardToPlayer(e.activePlayer, e.drawTopTrainCard(), true)
}
return true
}
func (e *Engine) logTrackLay(whichTrack int, whichColor GameColor, howManyColored, howManyRainbows int) {
if *toLog {
zap.L().Info("Engine: Player "+strconv.Itoa(e.activePlayer)+" has laid down a track from "+e.destinationNames[e.trackList[whichTrack].d1]+" to "+e.destinationNames[e.trackList[whichTrack].d2]+" costing "+strconv.Itoa(howManyColored)+" train cards of color "+e.stringColors[whichColor]+" and "+strconv.Itoa(howManyRainbows)+" rainbow Cards.",
zap.String("EVENT", "LAYING_TRACK"),
zap.String("DEST_1", e.destinationNames[e.trackList[whichTrack].d1]),
zap.String("DEST_2", e.destinationNames[e.trackList[whichTrack].d2]),
zap.String("PRIMARY_COLOR", e.stringColors[whichColor]),
zap.Int("NUM_PRIMARY", howManyColored),
zap.Int("NUM_RAINBOW", howManyRainbows),
zap.Int("PLAYER", e.activePlayer),
)
}
if *toUseVisualizer {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Player "+strconv.Itoa(e.activePlayer)+" has laid down a track from "+e.destinationNames[e.trackList[whichTrack].d1]+" to "+e.destinationNames[e.trackList[whichTrack].d2]+" costing "+strconv.Itoa(howManyColored)+" train cards of color "+e.stringColors[whichColor]+" and "+strconv.Itoa(howManyRainbows)+" rainbow Cards.")
}
}
func (e *Engine) runTrackLayingPhase() bool {
whichTrack, whichColor := e.playerList[e.activePlayer].askTrackLay()
if e.trackStatus[whichTrack] != -1 {
panic("The player tried to place over an occupied track")
}
if whichColor == Rainbow {
panic("The player is trying to play rainbow: if you want to use only rainbows, select any other color by default, like red")
}
if e.trackList[whichTrack].c != whichColor && e.trackList[whichTrack].c != Other {
panic("The player is trying to play with the wrong color for the track")
}
if e.trackList[whichTrack].length > e.numTrains[e.activePlayer] {
panic("The player does not have enough trains to play this move")
}
if e.trackList[whichTrack].length > e.trainCardHands[e.activePlayer][whichColor]+e.trainCardHands[e.activePlayer][Rainbow] {
panic("The player does not have color cards to play this move")
}
// If we made it this far, I think we're good: do the move
// mark the track as occupied
e.trackStatus[whichTrack] = e.activePlayer
howManyColored, howManyRainbows := 0,0
// remove the cards
if e.trainCardHands[e.activePlayer][whichColor] >= e.trackList[whichTrack].length {
howManyColored = e.trackList[whichTrack].length
howManyRainbows = 0
} else {
// gotta use up them rainbows
howManyColored = e.trainCardHands[e.activePlayer][whichColor]
howManyRainbows = e.trackList[whichTrack].length - e.trainCardHands[e.activePlayer][whichColor]
}
e.trainCardHands[e.activePlayer][whichColor] -= howManyColored
e.trainCardHands[e.activePlayer][Rainbow] -= howManyRainbows
for i:=0;i<howManyColored;i++ {
e.discardPileOfTrainCards = append(e.discardPileOfTrainCards, whichColor)
}
for i:=0;i<howManyRainbows;i++ {
e.discardPileOfTrainCards = append(e.discardPileOfTrainCards, Rainbow)
}
//remove the trains
e.numTrains[e.activePlayer] -= e.trackList[whichTrack].length
//tell all other players about the trackLay
for _,player := range e.playerList {
player.informTrackLay(e.activePlayer, whichTrack)
}
e.logTrackLay(whichTrack, whichColor, howManyColored, howManyRainbows)
return e.numTrains[e.activePlayer] == 0
}
func (e *Engine) runDestinationTokenCollectionPhase(playerNumber, numToOffer, numToAccept int) {
//create a slice to offer
offerSlice := make([]DestinationTicket, 0)
for j := 0; j < numToOffer; j++ {
ticket, ok := e.drawTopDestinationTicket()
if !ok {
panic("Not Enough Destination Tickets To Deal This Many To Each Player")
}
offerSlice = append(offerSlice, ticket)
}
// offer the slice
acceptedList := e.playerList[playerNumber].offerDestinationTickets(offerSlice, numToAccept)
if len(acceptedList) < numToAccept {
panic("The player didn't pick enough destination tickets")
}
alreadySeenAccepted := make([]int, 0) //used to prevent skirting the rules by printing duplicates
for _, accepted := range acceptedList {
if accepted < 0 || accepted >= len(offerSlice) || itemExists(alreadySeenAccepted, accepted) {
panic("The player gave invalid indices in selecting destination tickets")
}
alreadySeenAccepted = append(alreadySeenAccepted, accepted)
}
for i, offered := range offerSlice {
if itemExists(acceptedList, i) {
//this is one of the destination cards he wants to pick
e.giveDestinationTicketToPlayer(playerNumber, offered)
} else {
//this is one of the ones he wants to not pick
e.putDestinationTicketBackInPile(offered)
}
}
}
func (e *Engine) putDestinationTicketBackInPile(ticket DestinationTicket) {
e.pileOfDestinationTickets = append([]DestinationTicket{ticket}, e.pileOfDestinationTickets...)
}
func (e *Engine) logPlayerTurn() {
if *toLog {
zap.L().Info("Engine: It is the turn of player"+strconv.Itoa(e.activePlayer),
zap.String("EVENT", "TURN_START"),
zap.Int("PLAYER", e.activePlayer),
)
}
if *toUseVisualizer {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: It is the turn of player"+strconv.Itoa(e.activePlayer))
}
}
func (e *Engine) logPlayerDecision(whichMove int) {
if *toLog {
if whichMove == 0 {
zap.L().Info("Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to pick up cards",
zap.String("EVENT", "DECIDE_PICK_UP_CARDS"),
zap.Int("PLAYER", e.activePlayer),
)
} else if whichMove == 1 {
zap.L().Info("Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to lay tracks",
zap.String("EVENT", "DECIDE_LAY_TRACK"),
zap.Int("PLAYER", e.activePlayer),
)
} else if whichMove==2 {
zap.L().Info("Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to pick up destination tickets",
zap.String("EVENT", "DECIDE_PICK_UP_DESTINATION_TICKET"),
zap.Int("PLAYER", e.activePlayer),
)
}
}
if *toUseVisualizer {
if whichMove == 0 {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to pick up cards")
} else if whichMove == 1 {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to lay tracks")
} else if whichMove==2 {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: Player "+strconv.Itoa(e.activePlayer)+" has decided to pick up destination tickets")
}
}
}
func (e *Engine) runSingleTurn() bool {
e.logPlayerTurn()
//end condition: since this turn is starting with a player with less than two trains, he must have reached here on the previous move
if e.numTrains[e.activePlayer] <= 2 {
return true
}
//first, inform the player of the game state
e.playerList[e.activePlayer].informStatus(e.trackStatus, e.faceUpTrainCards)
whichMove := e.playerList[e.activePlayer].askMove()
//first, ask the guy whose turn it is what he wants to d
e.logPlayerDecision(whichMove)
if whichMove == 0 {
// let him pick up cards
if !e.runCollectionPhase(){
e.falseMoveCount++
} else {
e.falseMoveCount = 0
}
} else if whichMove == 1 {
//ask them to put down some tracks
e.falseMoveCount=0
e.runTrackLayingPhase()
} else if whichMove == 2 {
//finally ask them to decide and pick some destination tokens
e.falseMoveCount=0
e.runDestinationTokenCollectionPhase(e.activePlayer, e.gameConstants.NumDestinationTicketsOffered, e.gameConstants.NumDestinationTicketsPicked)
} else {
panic("Invalid move choice")
}
if e.falseMoveCount == e.gameConstants.NumPlayers+1 {
//everybody keeps asking to pick up cards!
return true
}
//next player
e.activePlayer++
e.activePlayer %= e.gameConstants.NumPlayers
return false
}
func (e *Engine) determinePlayerScore(playerNumber int) int {
score := 0
// add all the scores for paths
for i, status := range e.trackStatus {
if status == playerNumber {
score += e.gameConstants.routeLengthScores[e.trackList[i].length]
}
}
// add or subtract the score for each destination ticket
for _, ticket := range e.destinationTicketHands[playerNumber] {
if e.isConnected(ticket.d1, ticket.d2, playerNumber) {
score += ticket.points
} else {
score -= ticket.points
}
}
return score
}
func (e *Engine) dfs(src, dst Destination, playerNumber int, seen []bool) bool {
if src == dst {
return true
}
seen[src] = true
var otherDestination Destination
for _, edgeIndex := range e.adjacencyList[src] {
if e.trackStatus[edgeIndex] != playerNumber {
continue
}
otherDestination = e.getOtherDestination(src, e.trackList[edgeIndex])
if seen[otherDestination] {
continue
}
if e.dfs(otherDestination, dst, playerNumber, seen) {
return true
}
}
return false
}
func (e *Engine) isConnected(d1, d2 Destination, playerNumber int) bool {
seen := make([]bool, e.gameConstants.NumDestinations)
return e.dfs(d1, d2, playerNumber, seen)
}
func (e *Engine) getOtherDestination(d Destination, t Track) Destination {
if d == t.d1 {
return t.d2
} else if d == t.d2 {
return t.d1
} else {
panic("This isn't the right edge")
}
}
func (e *Engine) computeLongestPathRecursive(x Destination, currLen int, adjList [][]int, seenEdge []bool, toUpdate *int) {
if currLen > (*toUpdate) {
*toUpdate = currLen
}
for _, edgeIndex := range adjList[x] {
if !seenEdge[edgeIndex] {
seenEdge[edgeIndex] = true
e.computeLongestPathRecursive(e.getOtherDestination(x, e.trackList[edgeIndex]), currLen+e.trackList[edgeIndex].length, adjList, seenEdge, toUpdate)
seenEdge[edgeIndex] = false
}
}
}
func (e *Engine) determineLongestPathForPlayer(playerNumber int) int {
// There are two ways I thought of doing this and I'm not sure which is better
// Way #1: iterate over all subsets of edges, and see if you can get a set of edges which induces a subgraph which is connected and eulerean
// The check for eulerean is simple, the check for connectedness is dfs
// Way #2: from all starting points, repeatedly try all edges, update ans=max(ans,currPathLen)
// I'm not even sure if way #2 is correct
// First, create a playerAdjList, which selects from adjList only those which belong to the player
playerAdjList := make([][]int, e.gameConstants.NumDestinations)
for i, adj := range e.adjacencyList {
for _, edge := range adj {
if e.trackStatus[edge] == playerNumber {
playerAdjList[i] = append(playerAdjList[i], edge)
}
}
}
seenEdge := make([]bool, e.gameConstants.NumTracks)
ans := 0
// now, from each starting point, run the recursive computer
for i := 0; i < e.gameConstants.NumDestinations; i++ {
e.computeLongestPathRecursive(Destination(i), 0, playerAdjList, seenEdge, &ans)
}
return ans
}
func (e *Engine) getLongestPathPlayers() []int {
longestPathers := make([]int, 0)
currLongestPathLength := 0
for i := range e.playerList {
sc := e.determineLongestPathForPlayer(i)
//fmt.Println("Player", i, " Path Length ",sc)
if sc > currLongestPathLength {
currLongestPathLength = sc
longestPathers = nil
longestPathers = append(longestPathers, i)
} else if sc == currLongestPathLength {
longestPathers = append(longestPathers, i)
}
}
return longestPathers
}
func (e *Engine) logPlayerScore(i,sc int) {
fmt.Println("Player", i, "scored", sc)
if *toLog {
zap.L().Info("Engine: The score of player "+strconv.Itoa(i)+" is "+strconv.Itoa(sc),
zap.String("EVENT", "SCORE_COMPUTE"),
zap.Int("PLAYER", i),
zap.Int("SCORE", sc),
)
}
if *toUseVisualizer {
server.BroadcastToNamespace("/", "ENGINE_UPDATE", "Engine: The score of player "+strconv.Itoa(i)+" is "+strconv.Itoa(sc))
}
}
func (e *Engine) determineWinners() []int {
winners := make([]int, 0)
currBestScore := -1000000
//figure out which player(s) have longest paths
longestPathPlayers := e.getLongestPathPlayers()
for i := range e.playerList {
sc := e.determinePlayerScore(i)
if itemExists(longestPathPlayers, i) {
sc += e.gameConstants.LongestPathScore
}
e.logPlayerScore(i, sc)
if sc > currBestScore {
currBestScore = sc
winners = nil
winners = append(winners, i)
} else if sc == currBestScore {
winners = append(winners, i)
}
}
if len(winners) == 0 {
panic("WTF")
}
return winners
}
func (e *Engine) updateGraphVizString(vizString *string) bool {
newString := e.getGraphVizString()
if newString != *vizString {
*vizString = newString
return true
}
return false
}
func (e *Engine) doGraphStuff(vizString *string) {
if toGenerateGraphs {
if e.updateGraphVizString(vizString) {
if *toLog && !*consoleView {
zap.L().Info("Logging Graph",
zap.String("EVENT", "GRAPH"),
zap.String("GRAPH", *vizString),
)
}
if *toUseVisualizer {
// write graph to file
e.writeGraphToFile("visualizer/graph_pics/graph", *vizString)
// generate png
cmd := exec.Command("neato", "visualizer/graph_pics/graph", "-Tpng")
out,err := cmd.CombinedOutput()
if err != nil {
zap.S().Fatal(err)
}
//fmt.Println(out)
file, err := os.Create("visualizer/graph_pics/graph.png")
if err != nil {
panic("failed creating file")
}
defer file.Close()
_, err = file.Write(out)
if err != nil {
panic("failed writing to file")
}
server.BroadcastToNamespace("/", "GRAPH_UPDATE")
//time.Sleep(200*time.Millisecond)
}
}
}
}
func (e *Engine) runGame(playerList []Player, constants GameConstants) []int {
//initialize
e.initializeGame(playerList, constants)
gameOver := false
graphVizString := ""
e.doGraphStuff(&graphVizString)
moveNumber := 0
//run turns until the game is over
for !gameOver {
moveNumber++
gameOver = e.runSingleTurn()
//log the graph
e.doGraphStuff(&graphVizString)
}
//determine the Winner
return e.determineWinners()
}
func (e *Engine) writeGraphToFile(filename string, vizString string) {
file, err := os.Create(filename)
if err != nil {
panic("failed creating file")
}
defer file.Close()
_, err = file.WriteString(vizString)
if err != nil {
panic("failed writing to file")
}
}
func (e *Engine) getGraphVizString() string {
//for graphviz testing purposes
//for i:=0;i<10;i++ {
// e.trackStatus[i]=1
//}
//for i:=10;i<20;i++ {
// e.trackStatus[i]=2
//}
graphString := "Graph G {\n"
graphString += "\toverlap=true\n"
graphString += "\tmode=KK\n"
//graphString += "\tfontsize=30.0\n"
graphString += " splines=spline"
for dest,pos := range mapPositions {
graphString += "\t"
graphString += dest
graphString += " [ pos=\""
graphString += pos
graphString += "!\" ];"
graphString += "\n"
}
for _,dest := range e.destinationNames {
graphString += "\t"
graphString += dest
graphString += " [ fontsize=17 ]"
graphString += "\n"
}
for i, track := range e.trackList {
graphString += "\t"
graphString += e.destinationNames[track.d1]
graphString += " -- "
graphString += e.destinationNames[track.d2]
graphString += " [ len=" + strconv.Itoa(track.length) + ","
graphString += " label=\"" + strconv.Itoa(track.idx) + " " + strconv.Itoa(track.length) + "\","
graphString += " fontsize= 20,"
if e.trackStatus[i] == -1 {
// the track is empty
graphString += "style=dotted,penwidth=3.0,color="
if track.c == Rainbow {
graphString += "red:green:yellow:blue:orange:purple"
} else {
graphString += e.stringColors[track.c]
}
} else {
//there is a player on the track
graphString += "style=bold,penwidth=7.0,color="
if e.trackStatus[i] == int(Rainbow) {
graphString += "red:green:yellow:blue:orange:purple"
} else {
graphString += e.stringColors[e.trackStatus[i]]
}
}
//graphString += ",penwidth=4.0"
graphString += "];\n"
}
graphString += "}"
return graphString
}