/
flipfreighters.game.php
2185 lines (1855 loc) · 92.4 KB
/
flipfreighters.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>
* FlipFreighters implementation : © joesimpson <1324811+joesimpson@users.noreply.github.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.
* -----
*
* flipfreighters.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' );
const JOKER_TYPE = 5;
const JOKER_VALUE = 6; // USE CARD_VALUE_MAX in order to have the maximum value when using overtime hours tokens
const NB_CARDS_BY_WEEK = 15;// BY ROUND
const NB_CARDS_BY_TURN = 3;
const NB_ROUNDS = 3;
const DECK_LOCATION_WEEK_1 = "WEEK_1";
const DECK_LOCATION_WEEK_2 = "WEEK_2";
const DECK_LOCATION_WEEK_3 = "WEEK_3";
//For cards we flip over the table :
const DECK_LOCATION_DAY = "DAY";
//For cards discard after playing :
const DECK_LOCATION_DISCARD_AFTER_DAY = "discard_day";
//For cards we put back in the box and don't play with at all : (we could use discard, but is less missleading)
const DECK_LOCATION_BOX = "discard_game_box";
const STATE_LOAD_INITIAL = 0;
const STATE_LOAD_TO_CONFIRM = 1;
const STATE_LOAD_CONFIRMED = 2;
const STATE_MOVE_TO_CONFIRM = 1;
const STATE_MOVE_CONFIRMED = 2;
const STATE_MOVE_DELIVERED_TO_CONFIRM = 3;
const STATE_MOVE_DELIVERED_CONFIRMED = 4;
const SCORE_BY_REMAINING_OVERTIME = 2;
const SCORE_TYPE_NUMBER_OF_GOODS_X5 = 1;
const SCORE_TYPE_NUMBER_OF_GOODS_3_TO_30 = 2;
const SCORE_TYPE_SUM_GOODS_X1 = 3;
const SCORE_TYPE_SUM_GOODS_X2 = 4;
// TRUCK VALUES Types :
const CARGO_TYPE_DIFFERENT_VALUES = 1;
const CARGO_TYPE_SAME_VALUES = 2;
const CARGO_TYPE_REVERSE_ORDERED_VALUES = 3;
const CARGO_TYPE_ORDERED_VALUES = 4;
const CARGO_TYPE_ALL_VALUES = 5;
//CARGO SUIT TYPE :
const CARGO_SUIT_ALL = 0;
const CARGO_SUIT_SPADE = 1;
const CARGO_SUIT_HEART = 2;
const CARGO_SUIT_CLUB = 3;
const CARGO_SUIT_DIAMOND = 4;
const CARD_VALUE_MIN = 1;
const CARD_VALUE_MAX = 6;
// Number of values "duplicates" in the deck
const CARD_VALUE_NUMBER = 2;
// Number of joker "duplicates" in the deck
const JOKER_NUMBER = 4;
const NB_OVERTIME_TOKENS = 5;
const MAX_LOAD = 11;//CARD_VALUE_MAX + NB_OVERTIME_TOKENS
const GAME_PREF_DISPLAY_ALL = 101;
const GAME_PREF_DISPLAY_ALL_NO = 1;
const GAME_PREF_DISPLAY_ALL_YES = 2;
class FlipFreighters 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(
"round_number" => 10,
"turn_number" => 11,
// ...
"ffg_variant_overtime_hours" => 100,
"ffg_variant_show_discard" => 101,
// ...
) );
$this->cards = self::getNew( "module.common.deck" );
$this->cards->init( "card" );
}
protected function getGameName( )
{
// Used for translations and stuff. Please do not modify.
return "flipfreighters";
}
/*
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, player_score) VALUES ";
$values = array();
$initScore = NB_OVERTIME_TOKENS * SCORE_BY_REMAINING_OVERTIME;
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'] )."', $initScore)";
}
$sql .= implode( ',', $values );
self::DbQuery( $sql );
self::reattributeColorsBasedOnPreferences( $players, $gameinfos['player_colors'] );
self::reloadPlayersBasicInfos();
/************ Start the game initialization *****/
// Init global values with their initial values
self::setGameStateInitialValue( 'round_number', 0 );
self::setGameStateInitialValue( 'turn_number', 0 );
// Init game statistics
// (note: statistics used in this file must be defined in your stats.inc.php file)
self::initStat( 'table', 'stat_spades_drawn', 0 ); // Init a table statistics
self::initStat( 'table', 'stat_hearts_drawn', 0 );
self::initStat( 'table', 'stat_clubs_drawn', 0 );
self::initStat( 'table', 'stat_diamonds_drawn', 0 );
self::initStat( 'table', 'stat_jokers_drawn', 0 );
self::initStat( 'player', 'score_week1', 0 ); // Init a player statistics (for all players)
self::initStat( 'player', 'score_week2', 0 );
self::initStat( 'player', 'score_week3', 0 );
self::initStat( 'player', 'stat_score', 0 );
self::initStat( 'player', 'unused_overtime', NB_OVERTIME_TOKENS );
self::initStat( 'player', 'stat_load_overtime', 0 );
self::initStat( 'player', 'stat_move_overtime', 0 );
//self::initStat( 'player', 'stat_suit_overtime', 0 );
self::initStat( 'player', 'stat_player_loading', 0 );
self::initStat( 'player', 'stat_player_moving', 0 );
self::initStat( 'player', 'stat_total_goods', 0 );
self::initStat( 'player', 'stat_total_distance', 0 );
self::initStat( 'player', 'stat_delivered_trucks', 0 );
// setup the initial game situation here
$this->initDeck();
// Activate first player (which is in general a good idea :) )
$this->activeNextPlayer();
/************ End of the game initialization *****/
}
/*
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, player_score_aux score_aux FROM player ";
$result['players'] = self::getCollectionFromDb( $sql );
// Gather all information about current game situation (visible by player $current_player_id).
$result['version'] = intval($this->gamestate->table_globals[300]);//GAMESTATE_GAMEVERSION
$round_number = self::getGameStateValue( 'round_number');
$result['round_number'] = $round_number;
$result['turn_number'] = self::getGameStateValue( 'turn_number');
$result['dayCards'] = $this->getCurrentDayCards();
$result['overtimeSuitVariant'] = $this->isActivatedOvertimeSuitVariant();
$result['showDiscardVariant'] = $this->isActivatedShowDiscardVariant();
$result['discard_pile'] = $result['showDiscardVariant'] ? $this->getDiscardPile() : null;
$result['material'] = array(
'card_types' => $this->card_types,
'trucks_types' => $this->trucks_types,
'tooltips' => $this->ffg_tooltips,
);
$result['nextPlayerTable'] = self::getNextPlayerTable();
$result['prevPlayerTable'] = self::getPrevPlayerTable();
$result['constants'] = array(
'JOKER_TYPE' => JOKER_TYPE,
'JOKER_VALUE' => JOKER_VALUE,
'JOKER_NUMBER' => JOKER_NUMBER,
'NB_ROUNDS' => NB_ROUNDS,
'NB_TURNS' => (NB_CARDS_BY_WEEK/NB_CARDS_BY_TURN),
'CARD_VALUE_MAX' => CARD_VALUE_MAX,
'CARD_VALUE_NUMBER' => CARD_VALUE_NUMBER,
'MAX_LOAD' => MAX_LOAD,
'SCORE_BY_REMAINING_OVERTIME' => SCORE_BY_REMAINING_OVERTIME,
'STATE_LOAD_TO_CONFIRM' => STATE_LOAD_TO_CONFIRM,
'STATE_LOAD_CONFIRMED' => STATE_LOAD_CONFIRMED,
'STATE_MOVE_TO_CONFIRM' => STATE_MOVE_TO_CONFIRM,
'STATE_MOVE_DELIVERED_TO_CONFIRM' => STATE_MOVE_DELIVERED_TO_CONFIRM,
'STATE_MOVE_DELIVERED_CONFIRMED' => STATE_MOVE_DELIVERED_CONFIRMED,
'CARGO_TYPE_ALL_VALUES' => CARGO_TYPE_ALL_VALUES,
'DECK_LOCATION_DISCARD_AFTER_DAY' => DECK_LOCATION_DISCARD_AFTER_DAY,
'GAME_PREF_DISPLAY_ALL' => GAME_PREF_DISPLAY_ALL,
'GAME_PREF_DISPLAY_ALL_NO' => GAME_PREF_DISPLAY_ALL_NO,
'GAME_PREF_UI_GROUP' => [100, 101, 102, 103, 105, 106, 119, 120, ],
);
//SOME STATS are directly displayed during the game, let's add them in the players array, as if it was in the player table:
foreach($result['players'] as $player){
$player_id = $player["id"];
for($k=1; $k <= NB_ROUNDS;$k++){
$result['players'][$player_id]["score_week".$k] = self::getStat( "score_week".$k, $player_id );
}
$availableOvertime = $this->getPlayerAvailableOvertimeHours($player_id);
if($player_id == $current_player_id){
$availableOvertimePrivate = $this->getPlayerAvailableOvertimeHoursPrivateState($player_id);
$result['players'][$player_id]['score'] += ($availableOvertimePrivate - $availableOvertime) * SCORE_BY_REMAINING_OVERTIME ;
$availableOvertime = $availableOvertimePrivate;
}
$result['players'][$player_id]['availableOvertime'] = $availableOvertime;
if($player_id == $current_player_id) {
//retrieve current player unconfirmed deliveries, in order to send them only their temporary "player_score" (as we do in UI : updating score when we deliver )
$listUnconfirmedTurnActions = $this->listUnconfirmedTurnActions()["trucks_positions"];
if(array_key_exists($current_player_id, $listUnconfirmedTurnActions )){
$actions = $listUnconfirmedTurnActions[$current_player_id];
foreach($actions as $action){
$tmpScore = $action["truckScore"];
if($tmpScore > 0){
$result['players'][$player_id]['score'] += $tmpScore ;
$result['players'][$player_id]['score_aux'] += 1;
$result['players'][$player_id]['score_week'.$round_number] += $tmpScore ;
}
}
}
}
}
//Get private info : player's use of cards
for($k=0; $k<count($result['dayCards']); $k++){
$dayCard = $result['dayCards'][$k];
$cardUsedPower = $this->getCardUsedPowerForMoves($current_player_id, $dayCard["id"]);
$result['dayCards'][$k]['usedPower'] = $cardUsedPower;
}
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()
{
$round = self::getGameStateValue( 'round_number'); // FROM 1 to 3
$turn = self::getGameStateValue( 'turn_number'); // FROM 1 to 5, reset to 1 at each turn
$maxTurnsByRound = NB_CARDS_BY_WEEK/NB_CARDS_BY_TURN;//5
$maxTurns = NB_ROUNDS * $maxTurnsByRound;//15
$progression = ( ($round -1) * $maxTurnsByRound + $turn-1 ) / $maxTurns *100;// FROM 0 TO 14/15 (93%)
return $progression;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
/*
In this space, you can put any utility methods useful for your game logic
*/
function getCurrentPlayerIdPublic()
{
return self::getCurrentPlayerId();
}
function isCurrentPlayerId($player_id)
{
return self::getCurrentPlayerId() == $player_id;
}
function isCurrentSpectator() {
return self::isSpectator();
}
/**
Check Server version to compare with client version : throw an error in case it 's not the same
From https://en.doc.boardgamearena.com/BGA_Studio_Cookbook#Force_players_to_refresh_after_new_deploy
*/
public function checkVersion(int $clientVersion): void
{
if ($clientVersion != intval($this->gamestate->table_globals[300])) {
// Simplest way is to throw a "visible" exception
// It's ugly but comes with a "click here" link to refresh
//throw new BgaVisibleSystemException(self::_("A new version of this game is now available. Please reload the page (F5)."));
// For something prettier, throw a "user" exception and handle in JS
throw new BgaUserException('!!!checkVersion');
}
}
/**
Init the deck component with 52 cards:
+ 2->6 + Ace of each suit (color)
+ 2 Joker
x2 physical decks
*/
function initDeck()
{
// Create cards
$cards = array();
foreach( $this->card_types as $color_id => $color ) // spade, heart, club, diamond
{
for( $value=CARD_VALUE_MIN; $value<=CARD_VALUE_MAX; $value++ ) // A,2, 3, 4,5,6
{
$cards[] = array( 'type' => $color_id, 'type_arg' => $value, 'nbr' => CARD_VALUE_NUMBER);
}
}
//We don't have any need to distinguish jokers :
$cards[] = array( 'type' => JOKER_TYPE, 'type_arg' => JOKER_VALUE, 'nbr' => JOKER_NUMBER);
$this->cards->createCards( $cards, 'deck' );
$this->cards->shuffle( 'deck' );
// then deal out three piles with 15 cards each :
$this->cards->pickCardsForLocation( NB_CARDS_BY_WEEK, 'deck', DECK_LOCATION_WEEK_1,0, true );
$this->cards->pickCardsForLocation( NB_CARDS_BY_WEEK, 'deck', DECK_LOCATION_WEEK_2,0, true );
$this->cards->pickCardsForLocation( NB_CARDS_BY_WEEK, 'deck', DECK_LOCATION_WEEK_3,0, true );
//The extra 7 cards may be removed from the table
$this->cards->moveAllCardsInLocation( 'deck', DECK_LOCATION_BOX );
}
function isActivatedOvertimeSuitVariant()
{
$variant_overtime_hours = self::getGameStateValue( 'ffg_variant_overtime_hours' );
switch($variant_overtime_hours){
case 1: return FALSE;
case 2: return TRUE;
default: return FALSE;
}
}
function isActivatedShowDiscardVariant()
{
$variant_show_discard = self::getGameStateValue( 'ffg_variant_show_discard' );
switch($variant_show_discard){
case 1: return TRUE;
case 2: return FALSE;
default: return TRUE;
}
}
function getCurrentWeekLocation()
{
$round = self::getGameStateValue( 'round_number');
switch($round){
default:
case 1: return DECK_LOCATION_WEEK_1;
case 2: return DECK_LOCATION_WEEK_2;
case 3: return DECK_LOCATION_WEEK_3;
}
}
/**
Return current turn (day) cards ordered by card id
*/
function getCurrentDayCards()
{
$dayCards = $this->cards->getCardsInLocation( DECK_LOCATION_DAY,null,'card_id' );
return $dayCards;
}
function getDiscardPile()
{
$cards = $this->cards->getCardsInLocation( DECK_LOCATION_DISCARD_AFTER_DAY,null,'card_type_arg' );
return $cards;
}
/**
Return true if $card_suit is present in $containers_suit_filter (Either array, or a single value), => this would means this suit is allowed
false otherwise
*/
function isInSuitFilter($card_suit,$containers_suit_filter ,$cargo_index){
if($card_suit == JOKER_TYPE) return true;
if(is_array($containers_suit_filter)){
//suit corresponding to container position
return $containers_suit_filter[$cargo_index] == $card_suit;
}
else if(CARGO_SUIT_ALL == $containers_suit_filter ){
return true;
}
else {
return $containers_suit_filter == $card_suit;
}
}
/**
Return the suit to load in this truck container place IF it is FIXED to 1 SUIT
null if it is free of choice
*/
function getTruckCargoSuit($truck_cargo){
$truck_id = $truck_cargo['truck_id'];
$truck_material = $this->trucks_types[$truck_id];
$cargo_index = $truck_cargo['cargo_index'];
$containers_suit_filter = $truck_material['containers_suit_filter'];
if(CARGO_SUIT_ALL != $containers_suit_filter){
foreach( $this->card_types as $suit_id => $suit ){
if($this->isInSuitFilter($suit_id,$containers_suit_filter ,$cargo_index)){
return $suit_id;
}
}
}
return null;
}
/**
return true if at least one of the cargos is loaded with a number < $card_value
*/
function hasInferiorValueLoaded($cargos, $card_value, $readPrivateInfos = true){
foreach( $cargos as $cargo )
{
if(!$readPrivateInfos && $cargo['state'] == STATE_LOAD_TO_CONFIRM){
continue;
}
if(isset ($cargo['amount'] ) && $cargo['amount'] < $card_value){
return true;
}
}
return false;
}
/**
return true if at least one of the cargos is loaded with a number > $card_value
*/
function hasSuperiorValueLoaded($cargos, $card_value, $readPrivateInfos = true){
foreach( $cargos as $cargo )
{
if(!$readPrivateInfos && $cargo['state'] == STATE_LOAD_TO_CONFIRM){
continue;
}
if(isset ($cargo['amount'] ) && $cargo['amount'] > $card_value){
return true;
}
}
return false;
}
/**
return true if at least one of the cargos is loaded with a number != $card_value
*/
function hasOtherValueLoaded($cargos, $card_value){
if($this->hasInferiorValueLoaded($cargos, $card_value)){
return true;
}
if($this->hasSuperiorValueLoaded($cargos, $card_value)){
return true;
}
return false;
}
/**
return true if at least one of the cargos is loaded with a number == $card_value
*/
function hasSameValueLoaded($cargos, $card_value){
foreach( $cargos as $cargo )
{
if(isset ($cargo['amount'] ) && $cargo['amount'] == $card_value){
return true;
}
}
return false;
}
function cardAlreadyUsed($player_id,$card,$trucks_cargos, $multiMoveAmount = 0){
$card_id = $card["id"];
self::trace("cardAlreadyUsed($player_id,$card_id,$multiMoveAmount)...");
//self::dump("cardAlreadyUsed($player_id,$card_id)...",$trucks_cargos);
//LOOK FOR at least 1 cargo :
foreach( $trucks_cargos as $truck_id => $cargos )
{
foreach( $cargos as $cargo )
{
if(isset ($cargo['card_id'] ) && $cargo['card_id'] == $card_id){
return true;
}
}
}
//look for positions card_id, but not in the array of last confirmed and last not confirmed_pos : look at all positions of this player
$power = $this->getCardUsedPowerForMoves($player_id, $card_id);
self::trace("cardAlreadyUsed($player_id,$card_id)... used power =$power");
$card_value = $card["type_arg"];
if($power >= $card_value && $power >= $multiMoveAmount ) {
//NO remaining moves for this card
return true;
}
return false;
}
/**
Return all possibles cargo positions for this card according to its color and value, and according to already loaded trucks from player board
Example : input : "5 of Hearts"
output array(
truck1_2,
truck2_2,
truck3_5,
truck4_2,
truck5_1,truck5_2,truck5_3,truck5_4,truck5_5,truck5_6,
truck6_1,truck6_2,truck6_3,truck6_4,
)
*/
function getPossibleLoadsWithCard($card,$playerBoard)
{
$possibles = array();
$player_id = $playerBoard['player_id'];
$trucks_cargos = $playerBoard['trucks_cargos'];
$trucks_positions = $playerBoard['trucks_positions'];
//IF CARD ALREADY USED => KO
if( $this->cardAlreadyUsed($player_id,$card, $trucks_cargos)) return $possibles;
//IF CARD ALREADY USED for a move => KO
$cardUsedPower = $this->getCardUsedPowerForMoves($player_id, $card["id"]);
if($cardUsedPower >0) return $possibles;
//Loop over each container
foreach( $trucks_cargos as $truck_id => $cargos )
{
$truck = $trucks_positions[$truck_id];
foreach( $cargos as $container_id => $container )
{
if($this->isPossibleLoadWithCard($card,$container,$truck,$cargos, false) == false ) {
continue;
}
$possibles[] = $container_id;
}
}
return $possibles;
}
/**
Return true if LOAD truck $container with card $card is possible according to current truck position and loaded cargos
if $strictValue is TRUE, then look only for the value of the card, else look for all Joker possible values
*/
function isPossibleLoadWithCard($card,$container,$truck,$cargos, $strictValue)
{
//IF Container is not empty KO
if( array_key_exists('amount',$container) && $container['amount']>0 ) {
return false;
}
$currentTruckPosition = $this->getCurrentTruckPositionInDatas($truck);
if( $currentTruckPosition >0 ) {//if truck MOVED
return false;
}
$truck_id = $container['truck_id'];
$material = $this->trucks_types[$truck_id];
$containers = $material['containers'];
$containers_suit_filter = $material['containers_suit_filter'];
$cargo_value_filter = $material['cargo_value_filter'];
$card_suit = $card['type'];
$card_value = $card['type_arg'];
$cargo_index = $container['cargo_index']; //From 0
$isJoker = ($card_suit == JOKER_TYPE);
if(CARGO_TYPE_ORDERED_VALUES == $cargo_value_filter ){ // Truck 1-6
$target_value = $containers[$cargo_index];
if(!$strictValue && $isJoker){//COnsider that joker is THAT VALUE, or it won't be playable
$card_value = $target_value;
}
if($this->hasInferiorValueLoaded($cargos, $card_value)){
//GAME RULE : You may skip numbers but you may never fill in numbers that were skipped.
return false;
}
}
if(CARGO_TYPE_REVERSE_ORDERED_VALUES == $cargo_value_filter ){ // Truck 6-1
$target_value = $containers[$cargo_index];
if(!$strictValue && $isJoker){//COnsider that joker is THAT VALUE, or it won't be playable
$card_value = $target_value;
}
if($this->hasSuperiorValueLoaded($cargos, $card_value)){
//GAME RULE : You may skip numbers but you may never fill in numbers that were skipped.
return false;
}
}
if(!$strictValue && $isJoker){//AFTER previous checks, a joker is always possible
return true;
}
if( ! $this->isInSuitFilter($card_suit,$containers_suit_filter,$cargo_index )){
return false;
}
if(CARGO_TYPE_ORDERED_VALUES == $cargo_value_filter ){ // Truck 1-6
if($card_value != $containers[$cargo_index]){
// Example : playing any "5" is possible in the 5th cargo (index 4)
return false;
}
}
if(CARGO_TYPE_REVERSE_ORDERED_VALUES == $cargo_value_filter ) {// Truck 6-1
if( $card_value != $containers[$cargo_index]){
// Example : playing any "6" is possible in the first cargo (index 0)
return false;
}
}
if(CARGO_TYPE_SAME_VALUES == $cargo_value_filter ){
//GAME RULE : ALL THE SAME NUMBERS
if($this->hasOtherValueLoaded($cargos, $card_value)){
return false;
}
}
if(CARGO_TYPE_DIFFERENT_VALUES == $cargo_value_filter ){
//GAME RULE : ALL DIFFERENT NUMBERS
if($this->hasSameValueLoaded($cargos, $card_value)){
return false;
}
}
return true;
}
/**
return TRUE if it is not possible to LOAD in this container because of truck rules
*/
function isImpossibleLoad($container, $cargos, $readPrivateInfos = true)
{
//IF Container is not empty don't bother
if( array_key_exists('amount',$container) && $container['amount']>0 ) {
return false;
}
$truck_id = $container['truck_id'];
$material = $this->trucks_types[$truck_id];
$containers = $material['containers'];
$containers_suit_filter = $material['containers_suit_filter'];
$cargo_value_filter = $material['cargo_value_filter'];
$cargo_index = $container['cargo_index']; //From 0
$target_value = $containers[$cargo_index];
if(CARGO_TYPE_ORDERED_VALUES == $cargo_value_filter ){ // Truck 1-6
if($this->hasInferiorValueLoaded($cargos, $target_value, $readPrivateInfos)){
//GAME RULE : You may skip numbers but you may never fill in numbers that were skipped.
return true;
}
}
else if(CARGO_TYPE_REVERSE_ORDERED_VALUES == $cargo_value_filter ){ // Truck 6-1
if($this->hasSuperiorValueLoaded($cargos, $target_value, $readPrivateInfos)){
//GAME RULE : You may skip numbers but you may never fill in numbers that were skipped.
return true;
}
}
return false;
}
/**
return the list of containers where it is not possible to LOAD because of truck rules
*/
function getImpossibleLoads($trucks_cargos, $readPrivateInfos = true){
$impossibles = array();
//Loop over each container
foreach( $trucks_cargos as $truck_id => $cargos )
{
foreach( $cargos as $container_id => $container )
{
$isImpossible = $this->isImpossibleLoad($container,$cargos, $readPrivateInfos);
if( $isImpossible) $impossibles[] = $container_id;
}
}
return $impossibles;
}
function getPossibleMovesWithCard($card,$playerBoard)
{
$possibles = array();
$player_id = $playerBoard['player_id'];
$trucks_positions = $playerBoard['trucks_positions'];
$trucks_cargos = $playerBoard['trucks_cargos'];
//IF CARD ALREADY USED => KO
if( $this->cardAlreadyUsed($player_id,$card,$trucks_cargos)) return $possibles;
$cardUsedPower = $this->getCardUsedPowerForMoves($player_id, $card["id"]);
$cardMovePower = $card["type_arg"];
foreach( $trucks_positions as $truck_position ){
$truck_id = $truck_position['truck_id'];
$material = $this->trucks_types[$truck_id];
$truck_max_position = end($material['path_size']);
$truck_cargos = $trucks_cargos[$truck_id];
$currentTruckPosition = $this->getCurrentTruckPositionInDatas($truck_position);
$truckState = $this->getCurrentTruckStateInDatas($truck_position);
for ($k =$currentTruckPosition+1 ; $k<= min($currentTruckPosition + $cardMovePower,$truck_max_position); $k++ ) {
$position_id = $truck_id."_".$k;
if($this->isPossibleMoveWithCard($card,$currentTruckPosition,$truckState,$truck_cargos,$truck_id,$k,$cardMovePower,$cardUsedPower) == false ) {
continue;
}
$possibles[] = $position_id;
}
}
return $possibles;
}
/**
Return true if Move truck $truck_id with card $card to position $target_pos is possible according to current truck position and loaded cargos
*/
function isPossibleMoveWithCard($card,$currentTruckPosition,$truckState,$truck_cargos,$truck_id,$target_pos,$cardMovePower,$cardUsedPower)
{
$card_id = $card['id'];
$countCargoValues = $this->countCargoValues($truck_cargos);
if($countCargoValues <1){
//TRUCK Cannot move before being loaded
self::trace("isPossibleMoveWithCard($card_id) : KO Cannot move before being loaded (with $countCargoValues) ");
return false;
}
if($truckState ==STATE_MOVE_DELIVERED_CONFIRMED || $truckState ==STATE_MOVE_DELIVERED_TO_CONFIRM ){
//You cannot move a delivered truck
self::trace("isPossibleMoveWithCard($card_id) : KO You cannot move a delivered truck (with state $truckState) ");
return false;
}
$moveSize = $target_pos - $currentTruckPosition;
if($cardMovePower - $cardUsedPower < $moveSize ) {
//NOT enough power to do this move
self::trace("isPossibleMoveWithCard($card_id) : KO NOT enough power to do this move (cardMovePower $cardMovePower, cardUsedPower=$cardUsedPower, moveSize=$moveSize) ");
return false;
}
return true;
}
function getPlayerBoard($player_id){
$trucks_cargos = $this->getTruckCargos($player_id);
$trucks_positions = $this->getDoubleKeyCollectionFromDB( $this->getSQLSelectTruckPositions($player_id));
if( ! isset($trucks_positions ) || ! array_key_exists($player_id, $trucks_positions )){
//ONLY BEFORE THE FIRST MOVE of the game for this player
$trucks_positions = array();
} else {
$trucks_positions = $trucks_positions [$player_id];
}
//self::dump("getPlayerBoard($player_id) trucks_positions BEFORE ",$trucks_positions);
$trucks_scores = array();
//LOOP ON EACH TRUCK to add trucks which are not selected by this player yet
foreach ($this->trucks_types as $truck_type_id => $truck_type){
if( ! array_key_exists($truck_type_id, $trucks_positions ) ){
$trucks_positions[$truck_type_id] = array (
"player_id" => $player_id,
"truck_id" => $truck_type_id,
"confirmed_state" => null,
"confirmed_position" => null,
"not_confirmed_state" => null,
"not_confirmed_position" => null,
);
}
$trucks_scores[$truck_type_id] = $this->computeScore($player_id,$truck_type_id, $trucks_cargos[$truck_type_id], $trucks_positions[$truck_type_id] );
}
//self::dump("getPlayerBoard($player_id) trucks_positions AFTER ",$trucks_positions);
return array(
"player_id" => $player_id,
"trucks_cargos" => $trucks_cargos,
"trucks_positions" => $trucks_positions,
"trucks_scores" => $trucks_scores,
);
}
function getSQLSelectTruckCargos($player_id,$truck_id,$cargo_id,$state,$card_id){
$sql = "SELECT SUBSTRING(cargo_key FROM 1 FOR 6) truck_id, cargo_key id,cargo_amount amount, cargo_state state,cargo_card_id card_id, cargo_overtime_used overtime, SUBSTRING(cargo_key FROM 8 FOR 2) cargo_index, cargo_player_id player_id
FROM freighter_cargo ";
if(isset($player_id) ){
$sql .= "WHERE cargo_player_id ='$player_id' ";
}
if(isset($truck_id) ){
$sql = "SELECT * FROM ( ".$sql.") c WHERE truck_id ='$truck_id' ";
} else if(isset($cargo_id) ){
$sql = "SELECT * FROM ( ".$sql.") c WHERE id ='$cargo_id' ";
} else if(isset($state) ){
$sql = "SELECT * FROM ( ".$sql.") c WHERE state =$state ";
} else if(isset($card_id) ){
$sql = "SELECT * FROM ( ".$sql.") c WHERE card_id =$card_id ";
}
return $sql;
}
function getTruckCargos($player_id,$truck_id = null){
$sql = $this->getSQLSelectTruckCargos($player_id,$truck_id,null,null,null);
$trucks_cargos = $this->getDoubleKeyCollectionFromDB( $sql);
//LOOP ON EACH TRUCK to add trucks which are not selected by this player yet
foreach ($this->trucks_types as $truck_type_id => $truck_type){
if($truck_id !=null && $truck_id != $truck_type_id) continue;
if( ! array_key_exists($truck_type_id, $trucks_cargos ) ){
$trucks_cargos[$truck_type_id] = array ();
}
//LOOP ON EACH CARGOS to add cargos which are not selected by this player yet
foreach( $truck_type['containers'] as $container_id => $container ){
$cargo_key = $truck_type_id."_".$container_id;
if( ! array_key_exists($cargo_key, $trucks_cargos[$truck_type_id] ) ){
$trucks_cargos[$truck_type_id][$cargo_key] = $this->getEmptyTruckCargo($player_id,$truck_type_id, $container_id);
}
}
}
return $trucks_cargos;
}
function getTruckContainer($player_id,$cargo_id){
$sql = $this->getSQLSelectTruckCargos($player_id,null,$cargo_id,null,null);
$datas = $this->getObjectFromDB($sql);
//self::dump("getTruckContainer($player_id,$cargo_id)", $datas);
if( $datas == null){
//Cargo is not inserted yet...
$cargoTruckIdAndCargoIndex = explode("_", $cargo_id);
$truck_type_id = $cargoTruckIdAndCargoIndex[0];
$cargo_index = $cargoTruckIdAndCargoIndex[1];
$truckMaterial = $this->trucks_types[$truck_type_id];
if( isset($truckMaterial ) ){//IF truck is defined
$truckMaterialCargos = $truckMaterial['containers'];
if( array_key_exists($cargo_index,$truckMaterialCargos ) ){//IF truck cargo is defined
$datas = $this->getEmptyTruckCargo($player_id,$truck_type_id, $cargo_index);
}
}
}
return $datas;
}
function getExistingTruckCargosByState($state){
$sql = $this->getSQLSelectTruckCargos(null,null,null,$state,null);
$trucks_cargos = $this->getObjectListFromDB( $sql);
return $trucks_cargos;
}
function getExistingTruckCargoByCard($player_id,$card_id){
$sql = $this->getSQLSelectTruckCargos($player_id,null,null,null,$card_id);
$truck_cargo = $this->getObjectFromDB( $sql);
return $truck_cargo;
}
function getEmptyTruckCargo($player_id,$truck_id, $cargo_index){
$cargo_key = $truck_id."_".$cargo_index;
return array (
"truck_id" => $truck_id,
"id" => $cargo_key,
"amount" => null,
"state" => STATE_LOAD_INITIAL,
"card_id" => null,
"overtime" => 0,
"cargo_index" => $cargo_index,
);
}
function getSQLSelectTruckPositions($player_id, $not_confirmed_states = null){
// This request seems complicated but it is not, it is long because we want a "FULL JOIN" equivalent in mySql + because we want to aggregate datas directly
$stateToConfirm1 = STATE_MOVE_TO_CONFIRM;
$stateToConfirm2 = STATE_MOVE_DELIVERED_TO_CONFIRM;
$stateConfirmed1 = STATE_MOVE_CONFIRMED;
$stateConfirmed2 = STATE_MOVE_DELIVERED_CONFIRMED;
$sql = " SELECT a.fmove_player_id player_id, a.fmove_truck_id truck_id, a.confirmed_state,a.confirmed_position, b.not_confirmed_state,b.not_confirmed_position
FROM (
SELECT fmove_player_id, fmove_truck_id, MAX(fmove_state) 'confirmed_state', MAX(fmove_position_to) 'confirmed_position' FROM `freighter_move`
WHERE fmove_state in ($stateConfirmed1, $stateConfirmed2)
GROUP by 1,2
) a
left JOIN (
SELECT fmove_player_id, fmove_truck_id, MAX(fmove_state) 'not_confirmed_state', MAX(fmove_position_to) 'not_confirmed_position' FROM `freighter_move`
WHERE fmove_state in ($stateToConfirm1, $stateToConfirm2)
GROUP by 1,2
) b
on a.fmove_player_id = b.fmove_player_id AND a.fmove_truck_id = b.fmove_truck_id
UNION
SELECT b.fmove_player_id player_id, b.fmove_truck_id truck_id, a.confirmed_state,a.confirmed_position, b.not_confirmed_state,b.not_confirmed_position
FROM (
SELECT fmove_player_id, fmove_truck_id, MAX(fmove_state) 'confirmed_state', MAX(fmove_position_to) 'confirmed_position' FROM `freighter_move`
WHERE fmove_state in ($stateConfirmed1, $stateConfirmed2)
GROUP by 1,2
) a
right JOIN (
SELECT fmove_player_id, fmove_truck_id, MAX(fmove_state) 'not_confirmed_state', MAX(fmove_position_to) 'not_confirmed_position' FROM `freighter_move`
WHERE fmove_state in ($stateToConfirm1, $stateToConfirm2)
GROUP by 1,2
) b
on a.fmove_player_id = b.fmove_player_id AND a.fmove_truck_id = b.fmove_truck_id
ORDER BY 1,2
";
if(isset($player_id) ){
$sql = "SELECT * FROM ( ".$sql.") c WHERE player_id ='$player_id' ";
} else if(isset($not_confirmed_states) ){
$not_confirmed_statesSql = implode( ',', $not_confirmed_states );
$sql = "SELECT * FROM ( ".$sql.") c WHERE not_confirmed_state in ($not_confirmed_statesSql ) ";
}
return $sql;
}
/**
Return truck state and positions
*/
function getTruckPositions($truckId,$player_id){
self::trace("getTruckPositions($truckId,$player_id)...");
$sql = $this->getSQLSelectTruckPositions($player_id);
$sql = $sql." AND truck_id ='$truckId' ";
return $this->getObjectFromDB($sql);
}
/**
Return current truck position according to positions
*/
function getCurrentTruckPosition($truckId,$player_id){
self::trace("getCurrentTruckPosition($truckId,$player_id)...");
$res = $this->getTruckPositions($truckId,$player_id);
return $this->getCurrentTruckPositionInDatas($res);
}
function getCurrentTruckPositionInDatas($truck_datas){
$position = 0;
if(! isset($truck_datas)){
return 0;
}
$confirmed_pos = $truck_datas['confirmed_position'] ;
$not_confirmed_pos = $truck_datas['not_confirmed_position'];
if( isset($confirmed_pos)){
$position = $confirmed_pos;
}
if( isset($not_confirmed_pos)){//WILL BE GREATER than the confirmed one
$position = $not_confirmed_pos;
}
return $position;
}
/**
Return current truck state according to positions
*/
function getCurrentTruckState($truckId,$player_id){