-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrickoftherails.game.php
1591 lines (1418 loc) · 63.5 KB
/
trickoftherails.game.php
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
<?php
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* TrickOfTheRails implementation : @ David Edelstein <davidedelstein@gmail.com>
*
* This code has been produced on the BGA studio platform for use on http://boardgamearena.com.
* See http://en.boardgamearena.com/#!doc/Studio for more information.
* -----
*
* trickoftherails.game.php
*
* This is the main file for your game logic.
*
* In this PHP file, you are going to defines the rules of the game.
*
*/
require_once( APP_GAMEMODULE_PATH.'module/table/table.game.php' );
define('LASTROW', 6);
define('RESERVATION', 9);
define('EXCHANGE', 11);
define('RAILROAD_STATION', 12);
define('TRICKLANE', "tricklane");
define('AUTOPICK', 102);
define('STRVAR_RR', '${rr}');
define('STRVAR_CV', '${card_value}');
define('STRVAR_COMP', '${company_name}');
class TrickOfTheRails extends Table
{
function __construct( )
{
// Your global variables labels:
// Here, you can assign labels to global variables you are using for this game.
// You can use any number of global variables with IDs between 10 and 99.
// If your game has options (variants), you also have to associate here a label to
// the corresponding ID in gameoptions.inc.php.
// Note: afterwards, you can get/set the global variables with getGameStateValue/setGameStateInitialValue/setGameStateValue
parent::__construct();
self::initGameStateLabels( array(
'handSize' => 5,// number of cards and tricklane cards dealt
'currentTrickIndex' => 10, // index of next card to take in trick lane. Can't be turn # because of paired Loc6/∞
'trickRR' => 20,// company of current trick
'leadCard' => 21, // for keeping track of the lead card that was played for each hand
'wonLastTrick' => 30, // player id who won last trick
"trickLaneOption" => 100, // if expert option set
"teamsOption" => 101, // if partners variant set
) );
// all the cards in one deck, which can keep track of where everything is
$this->cards = self::getNew("module.common.deck");
$this->cards->init("CARDS");
}
protected function getGameName( )
{
// Used for translations and stuff. Please do not modify.
return "trickoftherails";
}
/*
setupNewGame:
This method is called only once, when a new game is launched.
In this method, you must setup the game according to the game rules, so that
the game is ready to be played.
*/
protected function setupNewGame( $players, $options = array() )
{
// Set the colors of the players with HTML color code
// The default below is red/green/blue/orange/brown
// The number of colors defined here must correspond to the maximum number of players allowed for the gams
$gameinfos = self::getGameinfos();
$default_colors = $gameinfos['player_colors'];
// Create players
// Note: if you added some extra field on "player" table in the database (dbmodel.sql), you can initialize it there.
$sql = "INSERT INTO player (player_id, player_color, player_canal, player_name, player_avatar) VALUES ";
$values = array();
foreach( $players as $player_id => $player )
{
$color = array_shift( $default_colors );
$values[] = "('".$player_id."','$color','".$player['player_canal']."','".addslashes( $player['player_name'] )."','".addslashes( $player['player_avatar'] )."')";
self::initStat('player', 'tricks_won', 0, $player_id);
foreach ($this->railroads as $rr) {
self::initStat('player', $rr['railway'].'_shares', 0, $player_id);
self::initStat('player', $rr['railway'].'_profits', 0, $player_id);
}
// get autopick pref
$autopick = $this->player_preferences[$player_id][AUTOPICK] ?? 1;
self::DbQuery("UPDATE player SET player_autopick=$autopick WHERE player_id=$player_id");
}
$sql .= implode( $values, ',' );
self::DbQuery( $sql );
self::reattributeColorsBasedOnPreferences( $players, $gameinfos['player_colors'] );
self::reloadPlayersBasicInfos();
/************ Start the game initialization *****/
/**** Stats */
self::initStat('table', 'turns_number', 0);
foreach ($this->railroads as $rr) {
self::initStat('table', $rr['railway'].'_length', 0);
self::initStat('table', $rr['railway'].'_share_value', 0);
self::initStat('table', $rr['railway'].'_cards', 0);
}
// Init global values with their initial values
// Set current trick color to zero (= no trick color)
self::setGameStateInitialValue( 'trickRR', 0 );
self::setGameStateInitialValue( 'leadCard', 0 );
self::setGameStateInitialValue( 'wonLastTrick', 0 );
// starts at -1, will become 0 with first new trick
self::setGameStateInitialValue( 'currentTrickIndex', -1 );
$players_nbr = count( $players );
switch ($players_nbr) {
case 3:
$handsize = 15;
break;
case 4:
$handsize = 11;
break;
case 5:
$handsize = 9;
break;
default:
// WTF happened?
throw new BgaVisibleSystemException("Invalid player count: $players_nbr");// NOI18N
}
self::setGameStateInitialValue( 'handSize', $handsize );
// Create the Railroad cards deck
$railroad_cards = $this->createRailroadCards();
$this->setupRailroadDeck($railroad_cards);
// Create the trick deck, which varies by number of players
$trick_cards = $this->createTrickCards();
$this->setupTrickLane($players_nbr, $trick_cards);
// Activate first player
self::activeNextPlayer();
if ($this->isTeamsVariant()) {
// sanity check
if ($players_nbr != 4) {
throw new BgaVisibleSystemException("Invalid player count for Teams variant: $players_nbr");// NOI18N
}
$this->createTeams();
}
/************ End of the game initialization *****/
}
/**
* Set up the 2-player teams
*/
protected function createTeams() {
$players = self::loadPlayersBasicInfos();
foreach ($players as $player) {
$team = $player['player_no'] % 2 == 0 ? 2 : 1;
self::DbQuery( "UPDATE player SET team=$team WHERE player_id=".$player['player_id'] );
}
}
/**
* Create the array of Railroad cards.
*/
protected function createRailroadCards() {
// Create cards
$railroad_cards = array();
foreach ( $this->railroads as $rr_id => $railroad ) {
// Railroad rows
// also stick Station cards here, though we'll immediately move them
for ($value = 1; $value <= 12; $value++) {
if ($value != EXCHANGE) {
$railroad_cards[] = array ('type' => $rr_id, 'type_arg' => $value, 'nbr' => 1);
}
}
}
return $railroad_cards;
}
/**
* Setup the Railroad Deck. Deal cards to each player, and remaining to the Railways.
*/
protected function setupRailroadDeck($railroad_cards) {
$this->cards->createCards( $railroad_cards, 'deck' );
// before shuffling main rr deck, remove Stations and put them in railway lines
foreach ( $this->railroads as $rr_id => $railroad ) {
// a one-element assocative array...
$stations = $this->cards->getCardsOfType($rr_id, RAILROAD_STATION);
$station = current($stations);
// Locomotive will be location 0
// set station at location 1
$this->cards->moveCard($station['id'], $railroad['railway'], 1);
}
// now shuffle
$this->cards->shuffle('deck');
// Deal cards to each player
$players = self::loadPlayersBasicInfos();
$handsize = self::getGameStateValue('handSize');
foreach ( $players as $player_id => $player ) {
$rrcards = $this->cards->pickCards($handsize, 'deck', $player_id);
}
// deal out remaining cards to appropriate railway line
foreach ($this->cards->getCardsInLocation( 'deck') as $rrcard) {
$railway = $this->railroads[$rrcard['type']]['railway'];
$pos = 1+$this->cards->countCardInLocation($railway);
$this->cards->moveCard($rrcard['id'], $railway, $pos);
}
}
/**
* Create the trick deck.
*/
protected function createTrickCards() {
$trick_cards = array();
for ($ix = 1; $ix <= 5; $ix++) {
// locomotives
$trick_cards[] = array('type' => LASTROW, 'type_arg' => $ix, 'nbr' => 1);
// exchange cards
$trick_cards[] = array('type' => $ix, 'type_arg' => EXCHANGE, 'nbr' => 1);
}
$trick_cards[] = array('type' => LASTROW, 'type_arg' => RESERVATION, 'nbr' => 3);
for ($col = 6; $col <= 8; $col++) {
$trick_cards[] = array('type' => LASTROW, 'type_arg' => $col, 'nbr' => 1);
}
return $trick_cards;
}
/**
* Start at location 0:
* 3 players:
* E C E C E C E 3 E 4 R 5 R 6/∞ R
* 4 players:
* E C E 3 E 4 E 5 E 6/∞ R
* 5 players
* E 3 E 4 E 5 E 6/∞ E
*/
protected function setupTrickLane($players_nbr, $trick_cards) {
// create trick deck
$this->cards->createCards($trick_cards, 'trickdeck');
// for basic
$loco_start_pos = array( 3 => 7, 4 => 3, 5 => 1);
$first_loco_card = $loco_start_pos[$players_nbr];
$cities = array(6,7,8);
shuffle($cities);
// for expert variant only
$expert_shuffle = array(1,2,3,4,6,7,8);
shuffle($expert_shuffle);
// randomize the Exchange cards
$exchange_rand = range(1,5);
shuffle($exchange_rand);
$reservation_slots = array(10, 12, 14);
$reservation_cards = $this->cards->getCardsOfType(LASTROW, RESERVATION);
// not counting ∞
$lanelength = self::getGameStateValue('handSize');
$offset = 0;
for ($loc = 0; $loc < $lanelength; $loc++) {
if (in_array($loc, $reservation_slots)) {
$rsrv_card = array_pop($reservation_cards);
$this->cards->moveCard($rsrv_card['id'], TRICKLANE, $loc+$offset);
} else if ($loc % 2 == 0) {
// exchange card
$ex = array_pop($exchange_rand);
$ex_card = current($this->cards->getCardsOfType($ex, EXCHANGE));
$this->cards->moveCard($ex_card['id'], TRICKLANE, $loc+$offset);
} else {
if ($loc < $first_loco_card && !$this->isExpertVariant()) {
// it's a city
$city = array_pop($cities);
$city_card = current($this->cards->getCardsOfType(LASTROW, $city));
$this->cards->moveCard($city_card['id'], TRICKLANE, $loc+$offset);
} else {
if ($this->isExpertVariant()) {
// loco or city
$loco = array_pop($expert_shuffle);
$loco_card = current($this->cards->getCardsOfType(LASTROW, $loco));
$this->cards->moveCard($loco_card['id'], TRICKLANE, $loc+$offset);
} else {
// it's a locomotive
$loco = (($loc-$first_loco_card)/2)+1;
$loco_card = current($this->cards->getCardsOfType(LASTROW, $loco));
$this->cards->moveCard($loco_card['id'], TRICKLANE, $loc+$offset);
}
if ($loco == 4) {
// this is the loco [6], so the [∞] goes after it
$offset = 1;
$loco_unl = current($this->cards->getCardsOfType(LASTROW, 5));
$this->cards->moveCard($loco_unl['id'], TRICKLANE, $loc+$offset);
}
}
}
}
}
/*
getAllDatas:
Gather all informations about current game situation (visible by the current player).
The method is called each time the game interface is displayed to a player, ie:
_ when the game starts
_ when a player refreshes the game page (F5)
*/
protected function getAllDatas()
{
$result = array();
$current_player_id = self::getCurrentPlayerId(); // !! We must only return informations visible by this player !!
// Get information about players
// Note: you can retrieve some extra field you added for "player" table in "dbmodel.sql" if you need it.
$sql = "SELECT player_id id, player_score score FROM player ";
$result['players'] = self::getCollectionFromDb( $sql );
// Cards in player hand
$result['hand'] = $this->cards->getCardsInLocation( 'hand', $current_player_id );
// all shares, including discards
$result['shares'] = array_merge($this->cards->getCardsInLocation('shares'), $this->getDiscardedShares());
// Cards played onto the table
$result['currenttrick'] = $this->cards->getCardsInLocation( 'currenttrick');
$result['lead'] = self::getGameStateValue('leadCard');
$result['trick'] = self::getGameStateValue('trickRR');
// Cards in tricklane
$result['tricklanecards'] = $this->cards->getCardsInLocation( 'tricklane' );
foreach ( $this->railroads as $rr_id => $railroad ) {
$result[$railroad['railway'].'_cards'] = $this->cards->getCardsInLocation( $railroad['railway'] );
}
// get knowledge of who played what card
// returns player_id => card_id associative DB
$cards_sql = "SELECT player_id, card_id FROM TRICK_ROW";
$result['cards_played'] = self::getCollectionFromDb($cards_sql, true);
$result['expert'] = $this->isExpertVariant();
// null if not teams variant
$result['teams'] = $this->getTeams();
$current_share_val = array();
$this->scoreRailways();
foreach ($this->railroads as $rr => $rw) {
$current_share_val[$rr] = self::getStat($rw['railway']."_share_value");
}
$result['current_share_values'] = $current_share_val;
$result['turn'] = self::getStat('turns_number');
$result['game_length'] = self::getGameStateValue('handSize');
$result['round'] = self::getStat('turns_number') % 2 == 0 ? "operating" : "stock";
$result['reservation_cards'] = $this->countReservationCards();
// $result['autopick'] = $this->player_preferences;
return $result;
}
/*
getGameProgression:
Compute and return the current game progression.
The number returned must be an integer beween 0 (=the game just started) and
100 (= the game is finished or almost finished).
This method is called each time we are in a game state with the "updateGameProgression" property set to true
(see states.inc.php)
*/
function getGameProgression() {
$initialTricks = self::getGameStateValue('handSize');
$tricksLeft = $initialTricks - self::getStat('turns_number');
return 100*($initialTricks-$tricksLeft)/$initialTricks;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
/**
* Is this the Expert variant?
*/
public function isExpertVariant() {
return $this->getGameStateValue('trickLaneOption') == 2;
}
/**
* Is this the teams option?
*/
public function isTeamsVariant() {
return $this->getGameStateValue('teamsOption') == 2;
}
/**
* Returns associative array of teams if this is teams variant, otherwise returns null
*/
public function getTeams() {
if ($this->isTeamsVariant()) {
return $this->getCollectionFromDB("SELECT player_id, team from player", true);
} else {
return null;
}
}
/**
* Does this player_id have a card in hand of current trick color?
* Return true if yes, false if no.
*/
function hasCurrentTrick($player_id) {
$cards_in_hand = $this->cards->getCardsInLocation( 'hand', $player_id );
$trick_rr = self::getGameStateValue( 'trickRR' );
foreach ($cards_in_hand as $card) {
if ($card['type'] == $trick_rr) {
return true;
}
}
return false;
}
/**
* Does the player have exactly one card of the trick suit?
*/
function trickCardsInHand($player_id) {
$trick_rr = self::getGameStateValue( 'trickRR' );
$cards_in_hand = $this->cards->getCardsInLocation( 'hand', $player_id );
$trickcards = array();
foreach ($cards_in_hand as $card) {
if ($card['type'] == $trick_rr) {
$trickcards[] = $card;
}
}
return $trickcards;
}
/**
* Is this the last turn?
*/
function isLastTurn() {
return self::getGameStateValue('handSize') == self::getStat('turns_number');
}
/**
* Check whether this player has only one card and autopick pref is set.
* Returns 1 card if conditions are met for autopick, otherwise null
*/
function getAutoPick($player_id) {
$card = null;
$pref = self::getUniqueValueFromDB("SELECT player_autopick pref FROM player WHERE player_id=$player_id");
if ($this->isLastTurn() && ($pref == 1 || $pref == 2)) {
$cards_in_hand = $this->cards->getCardsInLocation( 'hand', $player_id );
if (count($cards_in_hand) != 1) {
throw new BgaVisibleSystemException('player $player_id has more than one card on last turn'); // NOI18N
}
$card = array_pop($cards_in_hand);
} else if ($pref == 2) {
$cards = $this->trickCardsInHand($player_id);
if (count($cards) == 1) {
$card = $cards[0];
}
}
return $card;
}
/**
* Return the card_id of the most recent card played to the trickrow by the current active player.
*/
function getActivePlayersCard() {
$mycard = self::getUniqueValueFromDB("
SELECT card_id
FROM TRICK_ROW
WHERE player_id=".self::getActivePlayerId());
return $mycard;
}
/**
* **** Should no longer be needed as the UI checks if a card is already there, but in case of client-side shenanigans. ****
*
* Checks whether a locomotive has already been placed here.
* Given a ${rr}_railway" location.
* Returns true if there is no locomotive already there, false otherwise.
*/
function checkLocomotiveSlot( $railway ) {
$sql = self::getUniqueValueFromDB("
SELECT *
FROM CARDS
WHERE card_location ='".$railway."' AND card_location_arg = 0
");
return ($sql == null);
}
/**
* Returns true if this is a Reservation card
*/
function isReservationCard($card) {
return $card['type'] == LASTROW && $card['type_arg'] == RESERVATION;
}
/**
* How many Reservation Cards are left in the Trick Lane?
*/
function countReservationCards() {
$ct = 0;
foreach ($this->cards->getCardsInLocation('tricklane') as $c) {
if ($this->isReservationCard($c)) {
$ct++;
}
}
return $ct;
}
/**
* Convenience function, gets all discarded shares, not including Reservation cards.
*/
function getDiscardedShares() {
$discarded = array();
foreach ($this->cards->getCardsInLocation('discard') as $d) {
if (!$this->isReservationCard($d)) {
$discarded[] = $d;
}
}
return $discarded;
}
/**
* Score the values of all railways. Puts them in the stats.
* Returns a 2-element array of {$locomotive, {path}} arrays with locomotive as element 0
*/
function scoreRailways() {
$paths = array();
foreach ($this->railroads as $rr => $rw) {
$path = array();
$railway = $rw['railway'];
$railwaycards = self::getNonEmptyCollectionFromDB("
SELECT card_location_arg location_arg, card_type type, card_type_arg type_arg, card_id id
FROM CARDS
WHERE card_location = '".$railway."'
");
ksort($railwaycards);
$share_value = 0;
$scored_cards = 0;
// in Expert variant, some railways may have no locomotives
$locomotive = self::getUniqueValueFromDB("
SELECT card_type type, card_type_arg type_arg, card_id id
from CARDS
WHERE card_location = '".$railway."' AND card_location_arg = 0
");
if ($locomotive != NULL) {
$locomotive = $railwaycards[0];
// number of hops - 0 for the ∞ loco
$loco_dist = 0;
if ($locomotive['type_arg'] < 5) {
$loco_dist = $locomotive['type_arg']+2;
}
// number of cards in the railway, not counting locomotive
$num_rw_cards = count($railwaycards);
$rw_len = $num_rw_cards-1;
self::setStat($rw_len, $railway."_cards");
$profit = 0;
$route_start = 0;
$scored_cards = 0;
$path[] = $locomotive;
if ($loco_dist == 0 || $loco_dist >= $rw_len) {
// every card is scored
$scored_cards = $rw_len;
// count all the card values
$profit = $this->scoreStations($railwaycards, 1, $rw_len);
$route_start = 1;
array_push($path, array_slice($railwaycards, 1, $rw_len));
} else {
$scored_cards = $loco_dist;
// start with first loco distance, then successively add next and discard previous
// to find longest route
$route_start = 1;
$route_end = $loco_dist;
// get first route
$profit = $this->scoreStations($railwaycards, 1, $loco_dist);
$maxprofit = $profit;
// successively move ahead one and use the new route if it's the most profitable
for ($j = 2; ($j+$loco_dist) <= $num_rw_cards; $j++ ) {
// subtract value of last card
$prev_card = $railwaycards[$j-1];
// add value of next card
$next_card = $railwaycards[$j+$loco_dist-1];
$newprofit = $profit - $this->stationValue($prev_card) + $this->stationValue($next_card);
// is this a more profitable route?
if ($newprofit > $maxprofit) {
$maxprofit = $newprofit;
$route_start = $j;
}
$profit = $newprofit;
}
// now we should have the most profitable slice
$profit = $maxprofit;
array_push($path, array_slice($railwaycards, $route_start, $loco_dist));
}
// subtract value of locomotive
$loco_pen = $this->stationValue($locomotive);
$share_value = $profit + $loco_pen;
$share_value = max(0, $share_value);
}
self::setStat($share_value, $railway."_share_value");
self::setStat($scored_cards, $railway."_length");
$paths[] = $path;
}
return $paths;
}
function getScoreForRailway($rr) {
$this->scoreRailways();
$rw = $this->railroads[$rr];
return self::getStat($rw['railway']."_share_value");
}
/**
* Given a sequence of rr cards in order, score from first to last, inclusive
*/
function scoreStations($railwaycards, $first, $last) {
$profit = 0;
for ($i = $first; $i <= $last; $i++) {
$next_card = $railwaycards[$i];
$profit += $this->stationValue($next_card);
}
return $profit;
}
/**
* Given card values (row, column) that start from 1, get the station value of that card
* from our 0-indexed double array.
*/
function stationValue($card) {
$x = $card['type'];
$y = $card['type_arg'];
return $this->station_values[$x-1][$y-1];
}
//////////////////////////////////////////////////////////////////////////////
//////////// Player actions
////////////
/*
Each time a player is doing some game action, one of the methods below is called.
(note: each method below must match an input method in trickoftherails.action.php)
*/
/**
* When players change player prefs.
*/
function changePreference($pref, $value) {
if ($pref == AUTOPICK) {
$player_id = self::getCurrentPlayerId();
self::DbQuery("UPDATE player SET player_autopick=$value WHERE player_id=$player_id");
self::notifyPlayer( $player_id, "preferenceChanged", "", array() );
}
}
/**
* When someone plays a card to a trick.
* Now just a wrapper for state transitions.
*/
function playCard( $card_id ) {
self::checkAction( 'playCard' );
$this->doCardPlay($card_id);
// Next player
$this->gamestate->nextState();
}
/**
* Functionality extracted from the playCard action function.
*/
function doCardPlay($card_id) {
$player_id = self::getActivePlayerId();
$card_played = $this->cards->getCard($card_id);
$railroad = $card_played['type'];
$company = $this->railroads[$railroad]['name'];
$trick_rr = self::getGameStateValue( 'trickRR' );
// am I the first to play this trick?
$islead = ($trick_rr == 0);
if ($islead) {
// I'm the lead
self::setGameStateValue( 'trickRR', $railroad);
self::setGameStateValue( 'leadCard', $card_played['id']);
} else {
if ($railroad != $trick_rr) {
// do I have a card of that color in my hand?
if ($this->hasCurrentTrick($player_id)) {
$compname = $this->railroads[$trick_rr]['nametr'];
throw new BgaUserException( self::_( "You must play a $compname card" ));
}
}
}
// assign incrementing weights to ensure they stay in order
$wt = $this->cards->countCardsInLocation( 'currenttrick' );
$this->cards->insertCard( $card_id, 'currenttrick', $wt );
// update our trick table
self::DbQuery("INSERT INTO TRICK_ROW (player_id, card_id) VALUES (".$player_id.",".$card_id.")");
// Notify all players about the card played
// ${rr} and ${card_value} at the end are substituted on the client-side with js hacks
self::notifyAllPlayers('cardPlayed', ($islead ? clienttranslate('${player_name} leads the trick with ${company} ${card_value_label}') : clienttranslate('${player_name} plays ${company} ${card_value_label}')).STRVAR_RR.STRVAR_CV.STRVAR_COMP, array (
'i18n' => array('company'),
'card_id' => $card_id,
'player_name' => self::getActivePlayerName(),
'player_id' => self::getActivePlayerId(),
'card_value' => $card_played ['type_arg'],
'card_value_label' => $this->values_label [$card_played ['type_arg']],
'rr' => $railroad,
'company_name' => $company,
'company' => $company));
}
/**
* Player chooses a place to play Locomotive
*/
function placeLocomotive( $rr ) {
self::checkAction( 'placeLocomotive' );
$loconum = $this->doLocomotivePlacement($rr);
// by default, everyone adds station
$nextState = "addStation";
// if we just placed Locomotive [6], the ∞ loco is automatically placed in the remaining empty slot
if ($loconum == 4) {
// unless we're expert variant, in which case we manually place it
if ($this->isExpertVariant()) {
// we get to also place the ∞ loco
// need to increment trick index to ∞ card
self::incGameStateValue('currentTrickIndex', 1);
$nextState = "addUnlLocomotive";
} else {
// get the railways that already have locomotives
$placedRRs = self::getCollectionFromDB("
SELECT card_location railway FROM CARDS
WHERE card_location_arg = 0 and card_type = 6 AND card_type_arg <= 5
", true);
$ri = 0;
foreach ($this->railroads as $rri => $rw) {
$lastrr = $rw['railway'];
if (!array_key_exists($lastrr, $placedRRs)) {
$ri = $rri;
break;
}
}
if ($ri == 0) {
throw new BgaVisibleSystemException("No railway with empty locomotive slot found!");// NOI18N
}
// need to increment trick index to ∞ card
self::incGameStateValue('currentTrickIndex', 1);
$this->doLocomotivePlacement($ri);
}
}
// all players add their cards to railway (or in Expert, may be adding ∞ loco)
$this->gamestate->nextState($nextState);
}
/**
* Actual Locomotive card placement on specified Railway.
* Return the type_arg (loco card#) of the locomotive placed, so we know if it's the next-to-last one
*/
function doLocomotivePlacement( $rr ) {
$lococard = current($this->cards->getCardsInLocation('tricklane', self::getGameStateValue('currentTrickIndex')));
$locomotive = $this->trick_type[$lococard['type_arg']]['name'];
$railway = $this->railroads[$rr]['railway'];
// Should no longer be necessary as the js interface checks?
// Keep it in case someone tries something shady with JS
if (!$this->checkLocomotiveSlot($railway)) {
throw new BgaUserException( self::_( "You must choose a railway that does not already have a locomotive." ));
}
// place it on location 0
$this->cards->moveCard($lococard['id'], $railway, 0);
// Notify all players about Locomotive placement
self::notifyAllPlayers('locomotivePlaced', clienttranslate('${player_name} places Locomotive ${locomotive} on the ${company} railway').STRVAR_RR, array (
'i18n' => array ('company'),
'player_id' => self::getActivePlayerId(),
'player_name' => self::getActivePlayerName(),
'card_id' => $lococard['id'],
'locomotive' => $locomotive,
'loc_num' => $lococard['type_arg'],
'rr' => $rr,
'share_value' => $this->getScoreForRailway($rr),
'company' => $this->railroads[$rr]['name']));
return $lococard['type_arg'];
}
/**
* pass true for start of railray, false for end
*/
function addRailwayCard( $is_start ) {
self::checkAction( 'addRailwayCard' );
// get the card I played to play area
$mycard_id = $this->getActivePlayersCard();
// card we're going to insert in front or back
$railwaycard = $this->cards->getCard($mycard_id);
$rr = $railwaycard['type'];
$railway = $this->railroads[$rr]['railway'];
$company = $this->railroads[$rr]['name'];
$card_value = $railwaycard['type_arg'];
if ($is_start) {
$this->cards->insertCard($railwaycard['id'], $railway, 1);
} else {
$this->cards->insertCardOnExtremePosition( $railwaycard['id'], $railway, true );
}
// Notify all players about Locomotive placement
self::notifyAllPlayers('railwayCardAdded', clienttranslate('${player_name} adds ${card_value_label} to ${endpoint} of the ${company} railway').STRVAR_RR.STRVAR_CV, array (
'i18n' => array ('endpoint', 'company'),
'player_id' => self::getActivePlayerId(),
'player_name' => self::getActivePlayerName(),
'card_id' => $mycard_id,
'card_value' => $card_value,
'card_value_label' => $this->values_label[$card_value],
'rr' => $rr,
'share_value' => $this->getScoreForRailway($rr),
'company' => $company,
'endpoint' => $is_start ? clienttranslate('start') : clienttranslate('end'),
// need a numeric here that doesn't get bollixed by translation <<>>
'weight' => $is_start ? -1 : 1,
'railway' => $railway));
// Next player
$this->gamestate->nextState();
}
/**
* Passed the railway to add it to, and whether at start or end of line.
*/
function placeCity( $railway, $is_start ) {
self::checkAction( 'placeCity' );
$citycard = current($this->cards->getCardsInLocation('tricklane', self::getGameStateValue('currentTrickIndex')));
if ($is_start) {
$this->cards->insertCard($citycard['id'], $railway, 1);
} else {
$this->cards->insertCardOnExtremePosition( $citycard['id'], $railway, true );
}
$rr = -1;
// which rr# is this?
foreach ($this->railroads as $rri => $rw) {
if ($rw['railway'] == $railway) {
$rr = $rri;
break;
}
}
// should not happen! something went wrong in zombie mode
if ($rr == -1) {
throw new BgaVisibleSystemException( "No railway found for $railway during ".self::getActivePlayerName()." turn" );// NOI18N
}
// Notify all players about City placement
// ${rr} at the end is substituted by js on the client-side
self::notifyAllPlayers('cityAdded', clienttranslate('${player_name} adds ${city} to ${endpoint} of the ${company} railway').STRVAR_RR, array (
'i18n' => array ('city', 'endpoint', 'company'),
'player_id' => self::getActivePlayerId(),
'player_name' => self::getActivePlayerName(),
'card_id' => $citycard['id'],
'city' => $this->trick_type[$citycard['type_arg']]['name'],
'city_type' => $citycard['type_arg'],
'rr' => $rr,
'share_value' => $this->getScoreForRailway($rr),
'company' => $this->railroads[$rr]['name'],
'endpoint' => $is_start ? clienttranslate("start") : clienttranslate("end"),
'weight' => $is_start ? -1 : 1,
'railway' => $railway));
// go to placing trick cards played
$this->gamestate->nextState();
}
//////////////////////////////////////////////////////////////////////////////
//////////// Game state arguments
////////////
function argPlayCards() {
$company = "";
$rr = self::getGameStateValue( 'trickRR' );
$action = "";
$round_type = self::getStat('turns_number') % 2 == 0 ? clienttranslate("Operating Round") : clienttranslate("Stock Round");
if ($rr == 0) {
$action = 'lead';
} else if ($this->hasCurrentTrick(self::getActivePlayerId())) {
$company = $this->railroads[$rr]['name'];
$action = 'play';
} else {
$company = $this->railroads[$rr]['name'];
$action = 'playany';
}
return array(
"i18n" => array('round_type', 'company'),
'round_type' => $round_type,
'action' => $action,
'rr' => $rr,
'company' => $company,
);
}
function argPlaceLocomotive() {
$lococard = current($this->cards->getCardsInLocation('tricklane', self::getGameStateValue('currentTrickIndex')));
$locomotive = $this->trick_type[$lococard['type_arg']]['name'];
return array(
'locomotive' => $locomotive,
);
}
function argPlaceCity() {
$citycard = current($this->cards->getCardsInLocation('tricklane', self::getGameStateValue('currentTrickIndex')));
$city = $this->trick_type[$citycard['type_arg']]['name'];
return array(
"i18n" => array( 'city'),
'city' => $city
);
}
function argAddRailway() {
$mycard_id = $this->getActivePlayersCard();
$rrcard = $this->cards->getCard($mycard_id);
return array(
"i18n" => array( 'rr', 'card_value_label', 'company'),
'rr' => $rrcard['type'],
'card_value' => $rrcard['type_arg'],
'card_value_label' => $this->values_label[$rrcard['type_arg']],
'company' => $this->railroads[$rrcard['type']]['name']
);
}
//////////////////////////////////////////////////////////////////////////////
//////////// Game state actions
////////////
/*
Here, you can create methods defined as "game state actions" (see "action" property in states.inc.php).
The action method of state X is called everytime the current game state is set to X.
*/
/**
* Start a new trick.
*/
function stNewTrick() {
// clear previous tricks played
self::DbQuery("DELETE FROM TRICK_ROW");
// reset trick
self::setGameStateValue( 'trickRR', 0 );
self::setGameStateValue( 'leadCard', 0 );
// initial stats
self::incStat(1, 'turns_number');
self::incGameStateValue('currentTrickIndex', 1);
// who leads the new trick?
$nextState = "nextPlayer";
$leadPlayer = self::getGameStateValue( 'wonLastTrick' );
if ($leadPlayer != 0) {
$this->gamestate->changeActivePlayer( $leadPlayer );
$card = $this->getAutoPick($leadPlayer);
if ($card != null) {
$nextState = "autoPick";
}
}
$this->gamestate->nextState( $nextState );
}
/**
* Next card played in trick.
*/
function stNextPlayer() {