forked from elaskavaia/bga-eminentdomain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheminentdomain.game.php
3691 lines (3467 loc) · 152 KB
/
eminentdomain.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 <[email protected]> & Emmanuel Colin <[email protected]>
* EminentDomain implementation : © Alena Laskavaia <[email protected]>
*
* 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.
* -----
*
* eminentdomain.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.
*
*/
use EminentDomain\Setup;
require_once(APP_GAMEMODULE_PATH . 'module/table/table.game.php');
require_once('modules/EuroGame.php');
require_once('modules/php/EminentDomain/index.php');
define("CARD_STATE_PERMANENT_TAPPED", 0);
define("CARD_STATE_PERMANENT", 1);
define("CARD_STATE_PARTIAL_ACTION", 11);
define("CARD_STATE_TURN_LASTING", 10);
define("CARD_STATE_USED_CARD", 12);
define("CARD_STATE_PLANET_USED_AS_REQ", 13);
define("RESOURCE_STATE_COLONIZE_BOOST", 14);
define("RESOURCE_STATE_BLOCKER", 1);
define("RESOURCE_STATE_PRODUCE", 2);
define("PLANET_SETTLED", 1);
define("PLANET_UNSETTLED", 0);
define("CARD_STATE_FACEUP", 1);
define("CARD_STATE_FACEDOWN", 0);
define("RESOURCE_STATE_MARKER", 10);
define("CARD_RULE_TRIGGERED", 0);
define("CARD_RULE_ACTIVATABLE", 100);
define("CARD_RULE_ACTION", 200);
define("CARD_RULE_ACTION_PART2", 210);
define("CARD_RULE_ROLE", 300);
define("CARD_RULE_ROLE_LEADER", 310);
define("CARD_RULE_SPECIAL", 400);
class eminentdomain extends EuroGame
{
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(
// game global vars starts at 10
"action_played" => 11, // set to 1 if activate player played an action
"leader" => 12, // set to the leader id
"followers" => 13, // mask of which of players executed follow/descent
"followers_waiting" => 14, // mask of which of players are waiting
"active_follower" => 15, // follower who must follow/descent
"role" => 20, // current role number (index of role_icons array in material), -1 if not played
"end_of_game" => 21, // end of game has been triggered
"progression" => 22, // progression
"logistics_at_end" => 23, // logistics extra turn played
"extra_turn_at_end" => 24, //
"boost_rem" => 26, // how much of boost remains after role (used specific cards such as Scientific Method)
"actions_allowed" => 27, //
"role_phases_allowed" => 28, //
"role_phases_played" => 29, //
"discard_played" => 30, //
"follow_played" => 31, //
"scenarios" => 32, //
// variants
"learning_variant" => 100, //
"extended_variant" => 101, //
"scenarios_variant" => 102, //
"extra_turn_variant" => 103, //
"escalation_variant" => 104, //
"scenario_selection" => 105, //
));
$this->tokens->autoreshuffle_custom = array('supply_planets' => 'discard_planets');
$this->tokens->autoreshuffle = true;
$gameinfos = self::getGameinfos();
$default_colors = $gameinfos['player_colors'];
foreach ($default_colors as $color) {
$this->tokens->autoreshuffle_custom["deck_$color"] = "discard_$color";
}
}
protected function getGameName()
{
// Used for translations and stuff. Please do not modify.
return "eminentdomain";
}
function isEscalationVariant()
{
return $this->getGameStateValue('escalation_variant') == 2;
}
function isScenarioVariant()
{
return $this->getGameStateValue('scenarios_variant') == 2;
}
function isScenarioSelection()
{
return $this->getGameStateValue('scenario_selection') == 2;
}
/*
* 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())
{
/**
* ********** Start the game initialization ****
*/
try {
$this->initPlayers($players);
$this->activeNextPlayer(); // just in case so its not 0
$this->initStats();
// Setup the initial game situation here
$this->initTables();
$this->setGameStateValue('end_of_game', 0);
$this->setGameStateValue('logistics_at_end', 0);
$this->setGameStateValue('extra_turn_at_end', 0);
} catch (Exception $e) {
// logging does not actually work in game init :(
$this->error("Fatal error while creating game");
$this->dump('err', $e);
}
}
function debug_initTables()
{
$this->tokens->deleteAll();
$this->initTables();
$newGameDatas = $this->getAllTableDatas();
self::notifyPlayer($this->getActivePlayerId(), 'resetInterfaceWithAllDatas', '', $newGameDatas);
$this->debugConsole("ok");
}
function debug_getTokens($type, $location = null, $state = null, $order_by = null)
{
return $this->tokens->getTokensOfTypeInLocation($type, $location, $state, $order_by);
}
function debug_a()
{
// random code that I need to execute
for ($i = 13; $i <= 16; $i++) {
$this->dbSetTokenLocation("card_role_colonize_$i", "cols");
}
}
function initTables()
{
$num = $this->getPlayersNumber();
$learning_variant = $this->getGameStateValue('learning_variant') == 2;
$extended_variant = $this->getGameStateValue('extended_variant') == 2 && $num == 3;
$escalation_variant = $this->isEscalationVariant();
// setup from expansion rules
$setupnums = Setup::BuildDecks($num, $extended_variant);
$maxvp = Setup::GetMaxVP($num);
$this->tokens->createTokensPack("vp_w_{INDEX}", "stock_vp", $maxvp);
$this->tokens->createTokensPack("card_role_survey_{INDEX}", "supply_survey", $setupnums[0]);
$this->tokens->createTokensPack("card_role_warfare_{INDEX}", "supply_warfare", $setupnums[1]);
$this->tokens->createTokensPack("card_role_colonize_{INDEX}", "supply_colonize", $setupnums[2]);
$this->tokens->createTokensPack("card_role_produce_{INDEX}", "supply_produce", $setupnums[3]);
if (!$learning_variant) {
$this->tokens->createTokensPack("card_role_research_{INDEX}", "supply_research", $setupnums[4]);
}
$this->tokens->createTokensPack("card_planet_0_{INDEX}", "starting_worlds", 6);
$this->tokens->shuffle("starting_worlds");
if ($escalation_variant) {
$this->tokens->createTokensPack('card_fleet_b_{INDEX}', "dev_null", $num);
$this->tokens->createTokensPack('card_fleet_i_{INDEX}', "supply_fleet", $num);
}
// TECH
if (!$learning_variant) {
foreach ($this->token_types as $key => $info) {
if (startsWith($key, "card_tech")) {
$planettype = $info['p'][0];
$location = "supply_tech_$planettype";
$create = true;
if (isset($info['exp'])) {
$create = false;
if ($this->isEscalationVariant() && $info['exp'] == 'E')
$create = true;
}
if ($create)
$this->tokens->createToken($key, $location);
}
}
}
// FIGHERS AND RESOURCES
$this->tokens->createTokensPack('fighter_F_{INDEX}', "stock_fighter", 20 + 10 + 5, 0);
if ($escalation_variant) {
$this->tokens->createTokensPack('fighter_D_{INDEX}', "stock_fighter", 3, 0);
$this->tokens->createTokensPack('fighter_B_{INDEX}', "stock_fighter", 1, 0);
}
$this->tokens->createTokensPack('resource_w_{INDEX}', "stock_resource", 6, 0);
$this->tokens->createTokensPack('resource_f_{INDEX}', "stock_resource", 6, 0);
$this->tokens->createTokensPack('resource_i_{INDEX}', "stock_resource", 6, 0);
$this->tokens->createTokensPack('resource_s_{INDEX}', "stock_resource", 6, 0);
// Populate all game components
$this->tokens->createTokensPack("card_planet_1_{INDEX}", "supply_planets", 9);
$this->tokens->createTokensPack("card_planet_2_{INDEX}", "supply_planets", 9);
$this->tokens->createTokensPack("card_planet_3_{INDEX}", "supply_planets", 9);
if ($escalation_variant) {
$this->tokens->createTokensPack("card_planet_E_{INDEX}", "supply_planets", 15, 1);
}
$this->tokens->shuffle("supply_planets");
if ($learning_variant) {
$this->tokens->moveToken("card_planet_1_1", "dev_null");
$this->tokens->moveToken("card_planet_1_2", "dev_null");
$this->tokens->moveToken("card_planet_1_3", "dev_null");
}
// SCENARIOS
$this->scenarioProcess();
$scenario_tokens = [];
foreach ($this->token_types as $id => $info) {
$rowtype = $info['type'];
if (startsWith($rowtype, 'scenario')) {
$requiredExpansion = $info['expR'] ?? 'B';
if (
$requiredExpansion == 'B' || // basic
($requiredExpansion == 'E' && $escalation_variant)
) {
$scenario_tokens[] = ['key' => $id];
}
}
}
$this->tokens->createTokens($scenario_tokens, "scenarios", 0);
}
private function setupPlayers()
{
$players = $this->loadPlayersBasicInfos();
$learning_variant = $this->getGameStateValue('learning_variant') == 2;
$scenarios_variant = $this->isScenarioVariant();
$escalation_variant = $this->isEscalationVariant();
$standard_setup = [2, 1, 2, 2, 2, 1, '', ''];
$poli = 1;
$scenarios_setup = [];
foreach ($players as $player_id => $player_info) {
$color = $player_info['player_color'];
$no = $player_info['player_no'];
if ($escalation_variant) {
$this->tokens->moveToken("card_fleet_b_$no", "tableau_$color", 1);
}
if ($scenarios_variant) {
$sc = $this->tokens->getTokenOfTypeInLocation('scenario', "tableau_$color");
$key = $sc['key'];
$scenarios_setup[$player_id] = $this->token_types[$key]['setup'];
} else {
$scenarios_setup[$player_id] = $standard_setup;
}
$setup = $scenarios_setup[$player_id];
$this->tokens->pickTokensForLocation($setup[0], "supply_survey", "deck_${color}", 0);
$this->tokens->pickTokensForLocation($setup[1], "supply_warfare", "deck_${color}", 0);
$this->tokens->pickTokensForLocation($setup[2], "supply_colonize", "deck_${color}", 0);
$this->tokens->pickTokensForLocation($setup[3], "supply_produce", "deck_${color}", 0);
if (!$learning_variant)
$this->tokens->pickTokensForLocation($setup[4], "supply_research", "deck_${color}", 0);
// politics
$pol = $setup[5];
for ($i = 0; $i < $pol; $i++) {
$this->tokens->createToken("card_role_politics_${poli}", "deck_${color}", 0);
$poli++;
}
// staring tech
for ($i = 7; $i < count($setup); $i++) {
$tech = $setup[$i];
if ($tech) {
if ($tech == 'fighter_B') {
$info = $this->tokens->getTokenOfTypeInLocation('fighter_B', 'stock_fighter');
$this->tokens->moveToken($info['key'], "tableau_$color");
continue;
}
if ($tech == 'card_fleet_i') {
$this->tokens->moveToken("card_fleet_b_${no}", "dev_null", 0);
$this->tokens->moveToken("card_fleet_i_${no}", "tableau_${color}", 1);
continue;
}
if ($this->isPermanentTech($tech)) {
$this->tokens->moveToken($tech, "tableau_$color", 1);
$flip = $this->getRulesFor($tech, 'flip');
if ($flip)
$this->tokens->moveToken($flip, "dev_null", 0);
else
$this->error("No flip card for $tech " . ($this->getTokenName($tech)) . ".");
} else {
$this->tokens->moveToken($tech, "deck_${color}", 0);
}
}
}
$this->tokens->shuffle("deck_${color}");
$this->tokens->pickTokensForLocation(5, "deck_${color}", "hand_${color}");
// starting planet
$desi_planet = $setup[6];
if ($desi_planet) { // if special planet
$info = $this->tokens->getTokenInfo($desi_planet);
if ($info)
$this->tokens->moveToken($desi_planet, "tableau_${color}", 0);
else
$this->tokens->createToken($desi_planet, "tableau_${color}", 0);
}
}
// we have to do that after the special planet are assigned
foreach ($players as $player_id => $player_info) {
$color = $player_info['player_color'];
$setup = $scenarios_setup[$player_id];
$desi_planet = $setup[6];
if (!$desi_planet) { // if not special planet
$this->tokens->pickTokensForLocation(1, "starting_worlds", "tableau_${color}", 0);
}
}
// move to dev_null to remove from the game
$this->tokens->moveAllTokensInLocation("starting_worlds", "dev_null");
$this->tokens->moveAllTokensInLocation("scenarios", "dev_null");
}
/*
* 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 = parent::getAllDatas();
$result['materials'] = $this->materials;
$players = $this->loadPlayersBasicInfos();
$learning_variant = $this->getGameStateValue('learning_variant') == 2;
$extended_variant = $this->getGameStateValue('extended_variant') == 2 && count($players) == 3;
$extra_turn = $this->getGameStateValue('extra_turn_variant') == 2;
$result['variants'] = array(
'learning_variant_on' => $learning_variant,
'extended_variant_on' => $extended_variant, 'extra_turn_variant_on' => $extra_turn
);
$top_planet = $this->tokens->getTokenOnTop('supply_planets');
if ($top_planet) {
$top_planet['state'] = 0;
$result['tokens'][$top_planet['key']] = $top_planet;
}
$current = $this->getCurrentPlayerId();
$icons = $this->materials['role_icons'];
foreach ($players as $player_id => $player_info) {
$color = $player_info['player_color'];
$ii = $this->arg_iconsInfo($color, $icons);
foreach ($icons as $icon) {
$value = $ii["perm_boost_num"][$icon];
$this->setCounter($result['counters'], "iconperm_${icon}_${color}_counter", $value);
}
$score = count($this->tokens->getTokensOfTypeInLocation('vp', "tableau_$color"));
$this->setCounter($result['counters'], "vp_${color}_counter", $score);
if ($current == $player_id)
$result['server_prefs'] = $this->dbGetAllServerPrefs($player_id);
}
$triggered = $this->getGameStateValue('end_of_game');
$result['end_of_game'] = $triggered == 1;
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()
{
$this->isEndOfGameTriggered(); // that computes it
$prog = $this->getGameStateValue('progression');
return $prog;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
// Material utilities
function getRulesFor($token_id, $field = 'a')
{
$key = $token_id;
while ($key) {
//$this->warn("searching for $key|");
if (array_key_exists($key, $this->token_types)) {
if (array_key_exists($field, $this->token_types[$key])) {
return $this->token_types[$key][$field];
}
return '';
}
$key1 = getPartsPrefix($key, -1);
if ($key1 == $key)
break;
$key = $key1;
}
$this->systemAssertTrue("bad card $token_id for rule $field", false);
return '';
}
/**
* Get id of the token by its 'hid' or name
*
* @param string $hid
* - human readable id or name of the token
* @return string - id of the token found or null if not found
*/
function mtGet($hid)
{
if (!$hid)
return $hid;
if (isset($this->token_types[$hid]))
return $hid;
foreach ($this->token_types as $id => $info) {
if (isset($info['hid']) && $info['hid'] == $hid) {
return $id;
}
}
foreach ($this->token_types as $id => $info) {
if (isset($info['name']) && strcasecmp($info['name'], $hid) == 0) {
return $id;
}
}
$this->warn("error: cannot find $hid key\n");
return null;
}
/**
* Find a token of type $typePrefix which has field $field set to value $value, except a specific token $exceptId
* Return array of results of $all is set to true and first id otherwise
*
* @param string $typePrefix
* - type prefix (can be full id too)
* @param string $field
* - field
* @param string $value
* - exact match with ===
* @param string|null $exceptId
* - except one specific element (usefull to exclude itself)
* @param boolean $all
* - when true return fall results in array
* @return string|string[] - return array of ids or single id
*/
function mtFind($typePrefix, $field, $value, $exceptId = null, $all = true)
{
$res = [];
foreach ($this->token_types as $id => $info) {
if ($exceptId && $exceptId == $id)
continue;
$rowtype = $info['type'];
if ($typePrefix && startsWith($rowtype, $typePrefix)) {
if (isset($info[$field])) {
if (is_array($info[$field])) {
if (in_array($value, $info[$field], true)) {
if (!$all)
return $id;
$res[] = $id;
}
} else {
if ($value === $info[$field]) {
if (!$all)
return $id;
$res[] = $id;
}
}
}
}
}
return $res;
}
function mtCollectWithField($field, $callback)
{
$res = [];
foreach ($this->token_types as $id => $info) {
if (isset($info[$field])) {
if (is_array($info[$field])) {
foreach ($info[$field] as $trig) {
if ($callback($trig, $id)) {
$res[] = $id;
}
}
} else {
$trig = $info[$field];
if ($callback($trig, $id)) {
$res[] = $id;
}
}
}
}
return $res;
}
function mtTriggering($event)
{
$field = 'trig';
$callback = function ($v) use ($event) {
return $this->mtMatchEvent($v, $event);
};
return $this->mtCollectWithField($field, $callback);
}
/**
* Triggered action syntax:
*
* <trigger_rule> ::= <trigger> ':' <outcome>
* <trigger> ::= <event_type> '-' <role>
*
* <event> ::= <trigger>
*
* @param string $declared
* - the rule, for example [fl]-R:X - means follow or lead R (research) it triggers X (whatever X means)
* @param string $event-
* what actually happen, i.e. f-T - following trade
* @param array $splits
* @return boolean
*/
function mtMatchEvent($trigger_rule, $event, &$splits = [])
{
if (!$event)
$event = ".-.";
$woot = explode(":", $trigger_rule, 2);
$trig = $woot[0];
$out = '';
if (count($woot) > 1)
$out = $woot[1];
$event_split = explode("-", $event, 2);
$trig_split = explode("-", $trig, 2);
$trig_type = array_value_get($trig_split, 0, '.');
$trig_role = array_value_get($trig_split, 1, '.');
$event_type = array_value_get($event_split, 0, '.');
$event_role = array_value_get($event_split, 1, 'x');
$splits['rule_type'] = $trig_type;
$splits['rule_role'] = $trig_role;
$splits['event_type'] = $event_type;
$splits['event_role'] = $event_role;
$splits['out'] = $out;
$type_match = ($event_type === '.' || $trig_type === $event_type || preg_match("/^${trig_type}$/", $event_type) === 1);
$role_match = ($event_role === '.' || $trig_role === $event_role || preg_match("/^${trig_role}$/", $event_role) === 1);
$splits['match_type'] = $type_match;
$splits['match_role'] = $role_match;
if ($type_match && $role_match)
return true;
//$this->debugConsole("res",$splits);
return false;
}
function mtTriggerInfo($card, $event)
{
$triginfo = [];
$info = $this->getRulesFor($card, 'trig');
foreach ($info as $i => $trig) {
$split = [];
if ($this->mtMatchEvent($trig, $event, $split)) {
$triginfo = ['card' => $card, 'num' => $i, 'event' => $event, 'rules' => $split['out']];
break;
}
}
return $triginfo;
}
function mtGetFightCost($planet, $field = 'w')
{
if ($field == 'wi') // attack with primary weapon
$fight = "B";
else
$fight = trim($this->getRulesFor($planet, $field));
if (strlen($fight) == 2) {
$mcost = $fight[0];
$ftype = $fight[1];
} else {
$mcost = $fight;
$ftype = 'F'; // ship type
}
if ($mcost === 'D' || $mcost === 'B') {
$ftype = $mcost;
$mcost = 1;
} else {
$mcost = (int) $mcost; // military cost
}
$ship = $this->materials['icons'][$ftype]; // ship name
return ['cost' => $mcost, 'ship_type' => $ftype, 'ship_name' => $ship, 'rule' => str_repeat($ftype, $mcost)];
}
function mtIconCount($card, $icon)
{
$cur_icons = $this->getRulesFor($card, 'i');
$count = substr_count($cur_icons, $icon);
return $count;
}
/**
* massage material inc scenarios, it looks up token id by name/hid and add conflicting scenarious array
* its should have been there but I cannot really define functions
* in materil file.
*/
function scenarioProcess()
{
foreach ($this->token_types as $id => &$info) {
$rowtype = $info['type'];
if (startsWith($rowtype, 'scenario')) {
for ($i = 6; $i <= 9; $i++) { // Starting world + up to 2 starting techs (this is why we can't have Double Time scenario)
if (!isset($info['setup'][$i]))
continue;
$v = $info['setup'][$i];
if ($v == 'random') {
$info['setup'][$i] = ''; // a '' world is random
} else {
$v = $this->mtGet($v);
$info['setup'][$i] = $v; // get the ID from the world/tech name
}
}
}
}
foreach ($this->token_types as $id => &$info) {
$rowtype = $info['type'];
if (startsWith($rowtype, 'scenario')) {
$info['conflict'] = [];
for ($i = 6; $i <= 9; $i++) { // Starting world + up to 2 starting techs
if (!isset($info['setup'][$i]))
continue;
$v = $info['setup'][$i];
if (!$v || $v == 'random')
continue;
$foundarr = $this->mtFind('scenario', 'setup', $v, $id, true);
$info['conflict'] = array_unique(array_merge($info['conflict'], $foundarr));
if (isset($this->token_types[$v]['flip'])) {
$flip = $this->token_types[$v]['flip'];
$foundarr = $this->mtFind('scenario', 'setup', $flip, $id, true);
//echo "FLIP $id: $i $v $flip ;\n";
$info['conflict'] = array_unique(array_merge($info['conflict'], $foundarr));
}
}
}
}
}
// End of Material utilities
function iconReplacement(&$jokers, $icons, $event, $rules)
{
$split = [];
if ($this->mtMatchEvent($rules, $event, $split)) {
$rolematch = $split['rule_role'];
foreach ($icons as $icon) {
if (preg_match("/$rolematch/", $icon)) {
$jokers[$icon] .= $split['out'];
}
}
}
//$this->debugConsole("irep",[$jokers, $icons, $event, $rules]);
}
function isReadyToBeSettled($planet, $perm_boost)
{
$colonies = $this->getRulesFor($planet, 'c');
$this->systemAssertTrue("bad planet $planet", $colonies);
$tokens = $this->tokens->getTokensInLocation($planet);
$icons = $this->getIconCount('C', $tokens, '*');
if ($icons + $perm_boost >= $colonies)
return true;
return false;
}
function isPermanentTech($tech)
{
$side = $this->getRulesFor($tech, 'side');
if ($side == '1' || $side == '2')
return true;
// old way
$action = $this->getRulesFor($tech, 'a');
if ($action === '*')
return true;
return false;
}
function isActionable($card)
{
$action = $this->getRulesFor($card, 'a');
if (!$action || $action === '*')
return false;
return true;
}
function isPlanet($card)
{
return startsWith($card, 'card_planet');
}
function isEndOfGameTriggered()
{
$triggered = $this->getGameStateValue('end_of_game');
if ($triggered)
return true;
$players = $this->loadPlayersBasicInfos();
$num = $this->getPlayersNumber();
$total = 0;
foreach ($players as $player_id => $player_info) {
$color = $this->getPlayerColor($player_id);
$score = count($this->tokens->getTokensOfTypeInLocation('vp', "tableau_$color"));
$total += $score;
}
$max = 24;
if ($num == 5)
$max = 32;
if ($total >= $max) {
$this->setGameStateValue('end_of_game', 1);
$this->setGameStateValue('progression', 99);
return true;
}
$prox1 = $total * 100 / ($max);
$learning_variant = $this->getGameStateValue('learning_variant') == 2;
$supplies = ['supply_survey', 'supply_warfare', 'supply_colonize', 'supply_produce'];
if (!$learning_variant) {
$supplies[] = 'supply_research';
}
$extended_variant = ($this->getGameStateValue('extended_variant') == 2 && $num == 3) || $num > 3;
$empty_decks = 1;
if ($extended_variant)
$empty_decks = 2;
$ctot = count($supplies) * 16;
$rtot = 0;
foreach ($supplies as $location) {
$count = $this->tokens->countTokensInLocation($location);
if ($count <= 0)
$empty_decks--;
if ($empty_decks <= 0) {
$this->setGameStateValue('end_of_game', 1);
$this->setGameStateValue('progression', 99);
return true;
}
$rtot += $count;
}
$prox2 = ($ctot - $rtot) * 100 / $ctot;
if ($prox2 > $prox1)
$prox1 = $prox2;
$this->setGameStateValue('progression', (int) $prox1);
return false;
}
function checkTooManyCardsInHand($color, $bThrow = true)
{
$count = $this->tokens->countTokensInLocation("hand_$color");
$iconsinfo = $this->arg_iconsInfo($color, ['h']);
$max = $iconsinfo['hand_size'];
if ($count > $max) {
if ($bThrow)
$this->userAssertTrue(self::_("You must discard down to $max cards"));
else
return $max;
}
return 0;
}
function isEndOfGame($next_player_id)
{
if ($this->getFirstPlayer() == $next_player_id) {
if ($this->isEndOfGameTriggered()) {
return true;
}
}
return false;
}
function finalScoring()
{
$players = $this->loadPlayersBasicInfos();
foreach ($players as $player_id => $player_info) {
$res_count = 0;
$color = $player_info['player_color'];
$no = $player_info['player_no'];
$tokens = $this->tokens->getTokensOfTypeInLocation("card_planet", "tableau_${color}");
foreach ($tokens as $planet => $info) {
$state = $info['state'];
if ($state == 1) {
// colonized
$restokens = $this->tokens->getTokensOfTypeInLocation("resource", $planet);
$res_count += count($restokens);
} else {
$ptokens = $this->tokens->getTokensInLocation($planet);
foreach ($ptokens as $key => $info) {
$this->dbSetTokenLocation($key, "tableau_$color", 0, '', ['nod' => true]);
}
}
}
$this->tokens->moveAllTokensInLocation("hand_${color}", "deck_${color}");
$this->tokens->moveAllTokensInLocation("discard_${color}", "deck_${color}");
$tokens = $this->tokens->getTokensOfTypeInLocation("card_tech_2", "%_${color}");
foreach ($tokens as $token_id => $info) {
$this->dbSetTokenLocation($token_id, "tableau_${color}", 0, '');
}
$tokens = $this->tokens->getTokensOfTypeInLocation("card_tech_3", "%_${color}");
foreach ($tokens as $token_id => $info) {
$this->dbSetTokenLocation($token_id, "tableau_${color}", 0, '');
}
$this->notifyAnimate();
// reveal the rest
$tokens = $this->tokens->getTokensOfTypeInLocation("card", "deck_${color}");
foreach ($tokens as $token_id => $info) {
$this->dbSetTokenLocation($token_id, "tableau_${color}", 0, '', ['nod' => true]);
}
$tokens = $this->tokens->getTokensOfTypeInLocation('fighter', "tableau_$color");
$fighter = 0;
foreach ($tokens as $token_id => $info) {
if (getPart($token_id, 1) === 'B') { // Battlecruiser 2 points
$this->dbIncScoreValueAndNotify($player_id, 2, clienttranslate('${player_name} scored 2 influence for Battlecruiser'));
}
if (getPart($token_id, 1) === 'F') {
$fighter++;
}
}
$tokensF = $this->tokens->getTokensOfTypeInLocation('fighter_F', null, $player_id);
$fighter += count($tokensF);
$this->dbSetAuxScore($player_id, $fighter + $res_count);
$this->setStat($this->dbGetScore($player_id), 'game_vp', $player_id);
}
}
/**
* This only should be use for dinamic markers
*/
function dbMoveOrCreate($id, $location, $state)
{
$info = $this->tokens->getTokenInfo($id);
if ($info) {
$this->tokens->moveToken($id, $location, $state);
} else {
$this->tokens->createToken($id, $location, $state);
}
}
function dbGetFreeResourceInfo($resource)
{
switch ($resource) {
case 'f':
case 'w':
case 'i':
case 's':
break;
default:
$this->systemAssertTrue("Invalid resource type $resource");
break;
}
$restype = "resource_$resource";
$location = "stock_resource";
return $this->dbGetAutoIncToken($restype, $location, 6, 1, true);
}
function dbSetMarkerLocation($key, $location, $state)
{
$info = $this->dbGetAutoIncToken($key, 'pending_stock', 1, 1, false);
$this->tokens->moveToken($info['key'], $location, $state);
//$this->debugConsole('marker created ${token_name} ${place_name}', ['token_name'=>$info['key'], 'place_name'=>$location]);
}
function dbGetOwnVpInfo($color)
{
$resa = $this->tokens->getTokensOfTypeInLocation('vp', "tableau_${color}");
return $resa;
}
function dbGetOwnFighterInfo($color, $includeHand = true)
{
$rec = ['F' => [], 'D' => [], 'B' => []];
$resa = $this->tokens->getTokensOfTypeInLocation('fighter', "tableau_${color}");
foreach ($resa as $key => $info) {
$type = getPart($key, 1);
$rec[$type][] = $key;
}
$resa = $this->tokens->getTokensOfTypeInLocation('fighter', null, $this->getPlayerIdByColor($color));
foreach ($resa as $key => $info) {
$type = getPart($key, 1);
$rec[$type][] = $key;
}
if ($includeHand) {
$resa = $this->tokens->getTokensOfTypeInLocation('card', "hand_${color}");
foreach ($resa as $key => $info) {
$type = $this->getRulesFor($key, 'asf'); // card as ships
if (!$type)
continue;
$rec[$type][] = $key;
}
}
return $rec;
}
function getAllActivePermanents($color)
{
$loc = "tableau_${color}";
$tech = $this->tokens->getTokensOfTypeInLocation("card_tech", $loc, 1);
$planets = $this->tokens->getTokensOfTypeInLocation("card_planet", $loc, 1);
$res = array_merge($tech, $planets);
//$this->warn(toJson($res));
return $res;
}
function dbGetFreeFighterInfo($resource = 'F', $requested = 1, $array = false)
{
$max = $requested;
switch ($resource) {
case 'F':
$max += 10;
break;
case 'D':
$max += 5;
break;
case 'B':
$max += 2;
break;
default:
$this->systemAssertTrue("Invalid figher type $resource");
break;
}
$restype = "fighter_$resource";
$location = "stock_fighter";
return $this->dbGetAutoIncToken($restype, $location, $max, $requested, true, $array);
}
function dbGetAutoIncToken($restype, $location, $max = -1, $requested = 1, $syncDb = true, $array = false)
{
if ($max <= 0 || $max < $requested + 1)
$max = $requested + 1;
$resa = $this->tokens->getTokensOfTypeInLocation($restype, $location);
$count = count($resa);
$num = $max - $count;
if ($num > 0) {
// re-stock
$keys = [];
for ($i = 0; $i < $num; $i++) {
$suf = $this->tokens->createTokenAutoInc($restype, $location);
$keys[] = $suf;
}
if ($syncDb)
$this->dbSyncInfo($keys);
$resa = $this->tokens->getTokensOfTypeInLocation($restype, $location);
}
if ($requested == 1 && $array == false)
return end($resa);
else
return array_slice($resa, 0, $requested, true);
}
function dbGetFreeVpTokens($num = 1)
{
$resa = $this->tokens->getTokensInLocation("stock_vp");
while (count($resa) < $num) {
// create blue token
$total = count($this->tokens->getTokensOfTypeInLocation('vp'));
$total++;
$this->tokens->createToken("vp_b_$total", "stock_vp");
$resa = $this->tokens->getTokensInLocation("stock_vp");
}
return array_slice($resa, 0, $num, true);
}
function getCardOwnerColor($card_id)
{
$info = $this->tokens->getTokenInfo($card_id);
$loc = $info['location'];
$color = getPart($loc, 1, true);
return $color;
}
function playerHasCard($card_id, $color, $ignore_used = false)
{
$info = $this->tokens->getTokenInfo($card_id);
if (!$info) {
$this->warn("Cannot find card $card_id");
return false;
}
if ($this->isPlanet($card_id) || startsWith($card_id, 'scenario')) {