-
Notifications
You must be signed in to change notification settings - Fork 1
/
homeworlds.game.php
1689 lines (1500 loc) · 65.1 KB
/
homeworlds.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]>
* Homeworlds implementation : © Jonathan Baker <[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.
* -----
*
* homeworlds.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' );
class homeworlds 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(
'used_free' => 10,
'used_cat' => 11,
'sacrifice_color' => 20,
'sacrifice_actions' => 21,
'draw_offerer' => 30,
// System name tracking
'system_name_list_idx' => 101, // This is a setup option
'system_idx' => 40,
'saved_system_idx' => 41,
'system_name_start' => 42,
'system_name_inc' => 43,
// Track statistics until end of turn (in case of restart)
'turn_ships_captured' => 51,
'turn_systems_discovered' => 52,
'turn_movements' => 57,
'turn_ships_built' => 53,
'turn_ships_traded' => 54,
'turn_ships_sacrificed' => 55,
'turn_catastrophes_trigged' => 56
));
}
protected function getGameName( ) {
// Used for translations and stuff. Please do not modify.
return 'homeworlds';
}
/*
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'] )."'
)";
}
$sql .= implode(',',$values);
self::DbQuery($sql);
self::reattributeColorsBasedOnPreferences( $players, $gameinfos['player_colors'] );
// Additional color trickery could be performed here
self::reloadPlayersBasicInfos();
/************ Start the game initialization *****/
$sql = 'UPDATE player
SET player_score=0';
self::DbQuery($sql);
/////////////////////////////////////////////////
// Build up one big SQL command for all pieces //
/////////////////////////////////////////////////
$sql = 'INSERT INTO Pieces (color,pips) VALUES (';
for($color=1;$color<=4;$color++){
for($pips=1;$pips<=3;$pips++){
for($i=1;$i<=3;$i++){
// Three pieces in each of the three sizes and four colors
$sql .= $color . ',' . $pips . '),(';
}
}
}
// Remove the final ',('
$sql=substr($sql,0,-2);
self::DbQuery($sql);
/* START DEBUG SETUP
// Put a few pieces on the board to see if they're displayed properly
//[$system_id,$null_name] = $this->make_system(2357472);
[$system_id,$null_name] = $this->make_system($player_id);
$this->make_star(1,$system_id);
$this->make_star(31,$system_id);
$this->make_ship(25,$player_id,$system_id);
$this->make_ship(2,$player_id,$system_id);
$this->make_ship(10,$player_id,$system_id);
$this->make_ship(3,666,$system_id);
$this->make_ship(7,666,$system_id);
//END DEBUG SETUP */
// Change used_free to 1 when free move has been used
// (This flag is needed in after_cat state to determine
// whether to transition to want_free or want_catastrophe
// if there has been no sacrifice)
self::setGameStateInitialValue('used_free',0);
// Change used_cat to 1 when a catastrophe has occurred this turn.
// In the rare case that player's first action is a catastrophe,
// this is the only record that the player has performed any action.
// In the want_free state, the client may want to know this
// so that Restart Turn button can be shown/hidden intelligently
self::setGameStateInitialValue('used_cat' ,0);
// Color zero indicates no sacrifice has occurred
self::setGameStateInitialValue('sacrifice_color' ,0);
// Number of sacrifice actions available
self::setGameStateInitialValue('sacrifice_actions',0);
// ID of the player who has offered a draw
// 0 if no draw has been offered
// or -1 if the draw has been accepted (end game at once)
self::setGameStateInitialValue('draw_offerer',0);
// Number of systems that have been created
self::setGameStateInitialValue('system_idx',0);
self::setGameStateInitialValue('saved_system_idx',0);
// Actions taken this turn (added to stats unless turn is reset)
self::setGameStateInitialValue('turn_ships_captured',0);
self::setGameStateInitialValue('turn_systems_discovered',0);
self::setGameStateInitialValue('turn_movements',0);
self::setGameStateInitialValue('turn_ships_built',0);
self::setGameStateInitialValue('turn_ships_traded',0);
self::setGameStateInitialValue('turn_ships_sacrificed',0);
self::setGameStateInitialValue('turn_catastrophes_trigged',0);
// Prepare to access system name list
$name_list_choice = self::getGameStateValue('system_name_list_idx');
$system_names = $this->system_name_lists[$name_list_choice];
$name_count = count($system_names);
switch($name_list_choice){
case 1:
// nonsense
// Start at the beginning with same order every time
// Same as next case
case 2:
// real stars
// Start at the beginning with same order every time
self::setGameStateInitialValue('system_name_start',0);
self::setGameStateInitialValue('system_name_inc',1);
break;
case 3:
// fictional
// Randomize the first name and the name incrementation
self::setGameStateInitialValue(
'system_name_start',
bga_rand(0,$name_count-1)
);
self::setGameStateInitialValue(
'system_name_inc',
bga_rand(1,$name_count-1)
);
}
// Setup stats
self::initStat('player','turns_number',0);
self::initStat('player','ships_captured',0);
self::initStat('player','systems_discovered',0);
self::initStat('player','ships_built',0);
self::initStat('player','ships_traded',0);
self::initStat('player','ships_sacrificed',0);
self::initStat('player','catastrophes_trigged',0);
/************ End of the game initialization *****/
self::activeNextPlayer();
}
function get_system_name_list(){
$name_list_choice = self::getGameStateValue('system_name_list_idx');
return $this->system_name_lists[$name_list_choice];
}
/*
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();
// !! We must only return informations visible by this player !!
// The first column of the SELECT command will be the key of the array
// returned by getCollectionFromDb
// $current_player_id = self::getCurrentPlayerId();
// Get information about players
$sql = "SELECT
player_id,
player_name,
player_score,
player_no
FROM player";
$result['players'] = self::getCollectionFromDb($sql);
// Get bank pieces
$sql = "SELECT piece_id,color,pips
FROM Pieces
WHERE system_id IS NULL";
$result['bank'] = self::getCollectionFromDb($sql);
////////////////////////////////////////
// Get info on all the in-play pieces //
////////////////////////////////////////
$sql = "SELECT piece_id,color,pips,system_id
FROM Pieces
WHERE (system_id IS NOT NULL) AND (owner_id IS NULL)";
$stars = self::getCollectionFromDb($sql);
$sql = "SELECT piece_id,color,pips,system_id,owner_id
FROM Pieces
WHERE owner_id IS NOT NULL";
$ships = self::getCollectionFromDb($sql);
//////////////////////////////
// Set up system structures //
//////////////////////////////
$systems = [];
// The amperstand makes it a reference that can be changed
$result['systems'] =& $systems;
// Add stars and names to systems
foreach($stars as $piece_id => $row){
$system_id = $row['system_id'];
if(!array_key_exists($system_id,$systems)){
$systems[$system_id]['system_id'] = $system_id;
$systems[$system_id]['homeplayer_id'] = $this->get_homeplayer($system_id);
$systems[$system_id]['system_name'] = $this->get_system_name($system_id);
$systems[$system_id]['stars'] = [];
$systems[$system_id]['ships'] = [];
}
$systems[$system_id]['stars'][$piece_id] = $row;
}
// Add ships to systems
foreach($ships as $piece_id => $row){
$system_id = $row['system_id'];
$systems[$system_id]['ships'][$piece_id] = $row;
}
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() {
// For Homeworlds, this is hard to estimate.
if(0){
/*
VERSION 1:
Progress is the proportion of pieces that are in play
*/
$sql = 'SELECT piece_id FROM Pieces
WHERE system_id IS NOT NULL';
$result = self::getCollectionFromDb($sql);
// Number of pieces in play
$n_in_play = count($result);
return intdiv(100*$n_in_play,36);
}
elseif(0){
/*
VERSION 2:
Progress approaches 100% assymptotically
It reaches 50% when 30 ply have passed
1-1/(ply/30+1)
*/
$sql = 'SELECT player_id FROM player';
$player_ids = self::getCollectionFromDb($sql);
$plys = 0;
foreach($player_ids as $player_id=>$row){
$plys += self::getStat('turns_number',$player_id);
}
return round(100*( 1-1/($plys/30+1) ));
}
elseif(0){
/*
VERSION 3:
Progress estimate smoothly transitions from simple estimate f to a fancy estimate g
f is a linear function of the number of turns
Besides very short games where someone quits,
the mode game length on SDG is about 40 ply
f=0% at 0 ply
f=100% at 40 ply
g is increased by a player's material advantage and by bank exhaustion
g=0% if neither player has a ship
g=75% if players have equal pip count and bank is empty
g=100% if either player has every piece as a ship
*/
$sql = 'SELECT piece_id,owner_id FROM Pieces
WHERE owner_id IS NOT NULL';
$pieces = self::getCollectionFromDb($sql);
// Check for the extremely unlikely case that all ships are eliminated
if(count($pieces)==0){
return 100;
}
// Total material for each player, order doesn't matter
$m0 = 0;
$m1 = 0;
// ID of the player corresponding to $m0
$p0id = $pieces[$this->array_key_first($pieces)]['owner_id'];
foreach($pieces as $piece_id=>$row){
$pips = $row['pips'];
$owner_id = $row['owner_id'];
if($owner_id == $p0id)
$m0 += $pips;
else{
$m1 += $pips;
}
}
$theta = atan2($m1,$m0);
$g = ($m0+$m2)/72 * (0.75+0.25*abs(4*$theta/pi - 1));
// As a shortcut, use
$f = min(1, self::getStat('turns_number',$p0id)/20 );
}
else{
// Verision 4: return 50% so that players can resign any time
return 50;
}
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
// Send a debug notification
function say($s){
self::notifyAllPlayers('notif_debug',$s,[]);
}
function any_null($x){
foreach($x as $i=>$v){
if($v==NULL)
return true;
}
return false;
}
function array_key_first($x){
foreach($x as $key=>$value)
return $key;
return NULL;
}
function get_piece_string($piece_id){
// THIS WILL BREAK IF PIECES ARE CONSTRUCTED IN A DIFFERENT ORDER
// First piece has id 1
$color = intdiv($piece_id-1,9)+1;
$pips = intdiv($piece_id-1-9*($color-1),3)+1;
return $this->color_names_eng[$color][0].$pips;
}
function get_system_name($system_id){
// Yes this is a little silly,
// but it seemed easier than learning to use a deck
$num_players = $this->getPlayersNumber();
if($system_id<=$num_players){
// This is a homeworld
$sql = 'SELECT player_id,player_name FROM player
WHERE homeworld_id='.$system_id;
$result = self::getCollectionFromDb($sql);
$homeplayer_id = $this->array_key_first($result);
$player_name = $result[$homeplayer_id]['player_name'];
return "Homeworld ${player_name}";
}
// This is NOT a homeworld
$start = self::getGameStateValue('system_name_start');
$inc = self::getGameStateValue('system_name_inc');
$name_list = $this->get_system_name_list();
$name_count = count($name_list);
$idx = $system_id-$num_players-1;
$idx_loop = ( $idx*$inc + $start) % $name_count;
// $this->say('('.$idx.'*'.$inc.'+'.$start.')%'.$name_count.'='.$idx_loop);
$system_name = $name_list[$idx_loop];
if($idx >= $name_count)
// This system name has been used before, so suffix a number
$system_name .= ' '.(1+intdiv($idx,$name_count));
return $system_name;
}
function make_system($homeplayer_id=NULL){
self::incGameStateValue('system_idx',1);
$system_id = self::getGameStateValue('system_idx');
if(!is_null($homeplayer_id)){
// Set this as the player's homeworlds
$sql = 'UPDATE player
SET homeworld_id='.$system_id.'
WHERE player_id='.$homeplayer_id;
self::DbQuery($sql);
}
return $system_id;
}
// Raise a user-visible exception if piece is not in bank
function ensure_in_bank($piece_id){
$sql = 'SELECT piece_id FROM Pieces
WHERE piece_id='.$piece_id.'
AND system_id IS NOT NULL';
$result = self::getCollectionFromDb($sql);
if(count($result)!=0){
// Use BgaVisibleSystemException for code that should only be reachable by cheaters
// Use BgaUserException for problems that could be the result of innocent user error
throw new BgaVisibleSystemException(
self::_('No such piece in the bank.')
);
}
}
function get_all_overpopulations(){
// The first SELECT column must be unique.
// For a single unique column representing color and count,
// put system_id as the tens digit and count as the ones digit.
// (There are only 9 pieces of each color)
// TODO adapt for more players
$sql = 'SELECT color+10*system_id,COUNT(piece_id),system_id,color
FROM Pieces
WHERE system_id IS NOT NULL
GROUP BY system_id,color
HAVING COUNT(piece_id)>=4';
$result = self::getCollectionFromDb($sql);
return $result;
}
function exist_overpopulations(){
return count($this->get_all_overpopulations()) > 0;
}
// Put the piece with the given id into the bank
function put_in_bank($piece_ids){
if(!is_array($piece_ids)){
$sql = 'UPDATE Pieces
SET system_id=NULL,
owner_id=NULL
WHERE piece_id='.$piece_ids;
self::DbQuery($sql);
return;
}
if(count($piece_ids) == 0)
return;
// Construct a query to return all the pieces
$sql = 'UPDATE Pieces
SET system_id=NULL,
owner_id=NULL
WHERE ';
foreach($piece_ids as $piece_id)
$sql .= 'piece_id='.$piece_id.' OR ';
// Remove final ' OR '
$sql=substr($sql,0,-4);
self::DbQuery($sql);
}
// Put the piece with the given id into the system with the given id
// as a star
// Throws an error if the piece is not in the bank
function make_star($piece_id,$system_id){
$this->ensure_in_bank($piece_id);
$sql = 'UPDATE Pieces
SET system_id='.$system_id.',
owner_id=NULL
WHERE piece_id='.$piece_id;
self::DbQuery($sql);
}
// Put the piece with the given id into the system with the given id
// as a ship with the given owner
// Throws an error if the piece is not in the bank
function make_ship($piece_id,$owner,$system_id){
$this->ensure_in_bank($piece_id);
$sql = 'UPDATE Pieces
SET system_id='.$system_id.',
owner_id='.$owner.'
WHERE piece_id='.$piece_id;
self::DbQuery($sql);
}
// Returns the id of any one piece of the given color and size from the bank.
// Returns NULL if there are none.
function get_id_from_bank($color,$pips){
$sql = 'SELECT piece_id FROM Pieces
WHERE color='.$color.'
AND pips='.$pips.'
AND system_id IS NULL
LIMIT 1';
$result = self::getCollectionFromDb($sql);
return $this->array_key_first($result);
}
function get_homeplayer($system_id){
if($system_id > $this->getPlayersNumber())
return null;
$sql = 'SELECT player_id FROM player
WHERE homeworld_id='.$system_id;
$result = self::getCollectionFromDb($sql);
return $this->array_key_first($result);
}
// Ensure that current player has the right to empower piece_id with power
function validate_power_action($power,$ship_id){
$player_id = $this->getActivePlayerId();
// Check ship ownership
$sql = 'SELECT piece_id,system_id FROM Pieces
WHERE piece_id='.$ship_id.'
AND owner_id='.$player_id;
$result = self::getCollectionFromDb($sql);
if(count($result) != 1){
throw new BgaVisibleSystemException(
self::_("You can only empower your own ships."));
}
// Check sacrifice power availability
$sacrifice_color = self::getGameStateValue('sacrifice_color');
if($sacrifice_color != 0){
// This is a sacrifice turn, so the power must match
// and there must be an action available
if($sacrifice_color != $power){
throw new BgaVisibleSystemException(
self::_('Technology must match sacrificed ship.'));
}
if(self::getGameStateValue('sacrifice_actions') <= 0){
throw new BgaVisibleSystemException(
self::_('No sacrifice actions remaining.'));
}
// Sacrifice action check passed
// Decrement available action counter
self::incGameStateValue('sacrifice_actions',-1);
// The "used_free" gameStateValue is set by the sacrifice function
return;
}
// Check if free move has been used
// This check appears to be redundant since power actions are
if(self::getGameStateValue('used_free') == 1)
throw new BgaVisibleSystemException(
self::_('Free action has already been used.'));
// Check free power availability
$ship = $result[$ship_id];
$sql = 'SELECT piece_id FROM Pieces
WHERE system_id='.$ship['system_id'].'
AND (owner_id='.$player_id.' OR owner_id IS NULL)';
$result = self::getCollectionFromDb($sql);
if(count($result) == 0){
throw new BgaVisibleSystemException(
self::_('That technology is not available.'));
}
// Free action check passed
self::setGameStateValue('used_free',1);
}
// For each piece in the list that isn't already saved,
// put its current values in saved columns
//function save_state($piece_ids){
// Save the current state of all pieces
function save_state(){
////////////////////////////
// Clever careful version //
////////////////////////////
// (might be slower due to needing several DB operations on complex turns)
// $sql = 'UPDATE Pieces
// SET saved=TRUE,saved_system_id=system_id,saved_owner_id=owner_id
// WHERE NOT saved AND (piece_id=';
// if(!is_array($piece_ids)){
// // $piece_ids is a single ID
// $sql .= $piece_ids;
// }
// else{
// $sql .= implode(' OR piece_id=',$piece_ids);
// }
// $sql .= ')';
//////////////////
// Lazy version //
//////////////////
$sql = 'UPDATE Pieces
SET saved_owner_id=owner_id,saved_system_id=system_id';
self::DbQuery($sql);
self::setGameStateValue(
'saved_system_idx',
self::getGameStateValue('system_idx')
);
}
// The number of times that this state has appeared
// Assumes active player has just finished their turn but hasn't passed token yet
// i.e. player on move is the player following the active player
function get_state_repetitions(){
$s = $this->state_string(true);
// Don't forget the quotes around the varchar
$sql = "SELECT state_str,tally FROM States WHERE state_str='".$s."'";
$result = self::getCollectionFromDb($sql);
if(count($result) == 0){
return 0;
}
return $result[$s]['tally'];
}
// Returns the number of times that this state has appeared
// Assumes token has already been passed
// i.e. current player is on move
function increment_state_repetitions(){
$s = $this->state_string(false);
// Don't forget the quotes around the varchar
$sql = "SELECT state_str,tally FROM States WHERE state_str='".$s."'";
$result = self::getCollectionFromDb($sql);
if(count($result) == 0){
// This is the first time this state has been seen
// Don't forget the quotes around the varchar
$sql = "INSERT INTO States (state_str,tally)
VALUES ('".$s."',1)";
self::DbQuery($sql);
return 1;
}
$tally = $result[$s]['tally']+1;
$sql = 'UPDATE States
SET tally='.$tally."
WHERE state_str='".$s."'";
self::DbQuery($sql);
return $tally;
}
// Return a string representing the current game state
// The same game state will always produce the same string
// Equality of game states does depend on the player on move,
// but it does NOT depend on piece ID or system IDs/names
// Set $next_player true if it should be considered to be the next player's turn
// In multiplayer games, this may cause issues if the next player is being eliminated
function state_string($skip){
$allDatas = $this->getAllDatas();
$players = $allDatas['players'];
$systems = $allDatas['systems'];
// Map player ids to numbers
$player_nos = [];
foreach($players as $player_id => $player){
$player_no = $player['player_no'];
$player_nos[$player_id] = $player_no;
}
// Get all system strings, keeping homeworld strings separate
// $home_strs will map player numbers to system strings
$home_strs = [];
$system_strs = [];
foreach($systems as $system_id => $system){
$s = $this->system_str($system,$player_nos);
$homeplayer_id = $system['homeplayer_id'];
if(is_null($homeplayer_id)){
// Not a homeworld, add it to the regulat list
array_push($system_strs,$s);
}
else{
// It is a homeworld
// Get the player number and map it to the str
$home_strs[$player_nos[$homeplayer_id]] = $s;
}
}
// Sort homeworld strings by player number
// ksort sorts by key
ksort($home_strs);
// Sort other systems by string for uniqueness
sort($system_strs);
// Start the string with the active player number
$active_id = $this->getActivePlayerId();
if($skip)
$active_id = self::getPlayerAfter($active_id);
$active_no = $players[$active_id]['player_no'];
$s = $active_no;
$s .= implode('',$home_strs);
$s .= implode('',$system_strs);
return $s;
}
// $system is an array with the format as produced by getAllDatas
// $player_nos is an array mapping player ids to player numbers (e.g. 1,2)
function system_str($system,$player_nos){
$nplayers = count($player_nos);
$star_strs = [];
foreach($system['stars'] as $piece_id => $piece){
array_push($star_strs,$this->piece_chr($piece,1));
}
sort($star_strs);
// Make empty arrays for each player to which ships may be added
$ships = [];
foreach($player_nos as $player_id => $player_no){
$ships[$player_no] = [];
}
// Put $ships in the order of the player numbers
// ksort sorts by key
ksort($ships);
// For each ship, add its letter to the array for its player
foreach($system['ships'] as $piece_id => $piece){
$player_id = $piece['owner_id'];
$player_no = $player_nos[$player_id];
$ship_str = $this->piece_chr($piece,0);
array_push($ships[$player_no],$ship_str);
}
// Sort each player's ship strs
foreach($ships as $player_no => &$ship_strs){
sort($ship_strs);
}
// String everything together
$str = implode('',$star_strs);
foreach($ships as $player_no => &$ship_strs){
$str .= implode('',$ship_strs);
$str .= ',';
}
// Remove the final ','
$str=substr($str,0,-1);
return $str;
}
// $piece is an array with fields pips (1-3) and color (1-4)
// $is_star indicates whether this is a ship or star
// returns a letter a-l for a ship or A-L for a star
function piece_chr($piece,$is_star){
if($is_star)
$a = ord('A');
else
$a = ord('a');
return chr( ($piece['color']-1)*3 + $piece['pips']-1 + $a);
}
// Put all saved values back into the regular columns
// The old saved start is retained in case of another restart
// Also restore the system counter
function restore_state(){
//$sql = 'SELECT piece_id,owner_id,system_id FROM Pieces
// WHERE saved';
//$result = self::getCollectionFromDb($sql);
$sql = 'UPDATE Pieces
SET system_id=saved_system_id,
owner_id=saved_owner_id';
self::DbQuery($sql);
self::setGameStateValue(
'system_idx',
self::getGameStateValue('saved_system_idx')
);
self::setGameStateValue('turn_ships_captured',0);
self::setGameStateValue('turn_systems_discovered',0);
self::setGameStateValue('turn_movements',0);
self::setGameStateValue('turn_ships_built',0);
self::setGameStateValue('turn_ships_traded',0);
self::setGameStateValue('turn_ships_sacrificed',0);
self::setGameStateValue('turn_catastrophes_trigged',0);
//return $result;
}
function get_piece_row($piece_id){
return self::getCollectionFromDb(
'SELECT * FROM Pieces WHERE piece_id='.$piece_id
)[$piece_id];
}
function get_player_row($player_id){
$sql = 'SELECT * FROM player WHERE player_id='.$player_id;
$result = self::getCollectionFromDb($sql);
return $result[$this->array_key_first($result)];
}
function get_stars($system_id){
return self::getCollectionFromDb(
'SELECT * FROM Pieces WHERE owner_id IS NULL AND system_id='.$system_id
);
}
function get_containing_system($piece_id){
$sql = 'SELECT piece_id,system_id FROM Pieces
WHERE piece_id='.$piece_id;
$result = self::getCollectionFromDb($sql);
return $result[$piece_id]['system_id'];
}
// NOTE: If turn_over is true and stars are all destroyed,
// this method returns false (system should have already faded)
function is_empty($system_id,$turn_over=false){
// Check for lack of stars
$sql = 'SELECT piece_id FROM Pieces
WHERE system_id='.$system_id.'
AND owner_id IS NULL';
$stars = self::getCollectionFromDb($sql);
if(count($stars)==0)
return !$turn_over;
// Home systems that still have stars are ONLY removed at the end of the turn
// (the no-star case was checked first)
if(!$turn_over && !is_null($this->get_homeplayer($system_id))){
return false;
}
// Check for lack of ships
$sql = 'SELECT piece_id FROM Pieces
WHERE system_id='.$system_id.'
AND owner_id IS NOT NULL';
$ships = self::getCollectionFromDb($sql);
$no_ships = count($ships)==0;
return $no_ships;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Player actions
////////////
function creation($star1_id,$star2_id,$ship_id){
self::checkAction('act_creation');
$player_id = $this->getActivePlayerId();
$player_name = $this->getActivePlayerName();
$system_id = $this->make_system($player_id);
$system_name = $this->get_system_name($system_id);
$this->make_star($star1_id,$system_id);
$this->make_star($star2_id,$system_id);
$this->make_ship( $ship_id,$player_id,$system_id);
self::notifyAllPlayers(
'notif_create',
clienttranslate('${player_name} establishes a homeworld with a ${ship_str} ship at ${star1_str} and ${star2_str} binary stars.'),
array(
'homeplayer_id' => $player_id,
'player_name' => $player_name,
'system_name' => $system_name,
'system_id' => $system_id,
'star1_id' => $star1_id,
'star2_id' => $star2_id,
'ship_id' => $ship_id,
'star1_str' => $this->get_piece_string($star1_id),
'star2_str' => $this->get_piece_string($star2_id),
'ship_str' => $this->get_piece_string($ship_id)
)
);
$this->gamestate->nextState('trans_after_creation');
}
function capture($piece_id,$capture_id){
self::checkAction('act_power_action');
$this->validate_power_action(1,$piece_id);
$attack_ship = $this->get_piece_row($piece_id);
$target_ship = $this->get_piece_row($capture_id);
// Check validity
if($attack_ship['owner_id'] == $target_ship['owner_id']
|| is_null($target_ship['owner_id']) ){
throw new BgaVisibleSystemException(
self::_('You may only capture enemy ships.'));
}
if($attack_ship['system_id'] != $target_ship['system_id']){
throw new BgaVisibleSystemException(
self::_('A ship may only capture ships in the same system.'));
}
if($attack_ship['pips'] < $target_ship['pips']){
throw new BgaUserException(
self::_('Attacking ship must not be smaller than target.'));
}
$player_id = $this->getActivePlayerId();
$player_name = $this->getActivePlayerName();
$sql = 'UPDATE Pieces
SET owner_id='.$attack_ship['owner_id'].'
WHERE piece_id='.$capture_id;
self::DbQuery($sql);
$system_id = $this->get_containing_system($piece_id);
$system_name = $this->get_system_name($system_id);
self::notifyAllPlayers(
'notif_capture',
clienttranslate('${player_name} captures a ${target_str} ship in ${system_name}.'),
array(
'player_name' => $player_name,
'target_id' => $capture_id,
'target_str' => $this->get_piece_string($capture_id),
'system_name' => $system_name
)
);
$this->gamestate->nextState('trans_after_power_action');
self::incGameStateValue('turn_ships_captured',1);
}
function move($ship_id,$system_id){
self::checkAction('act_power_action');
$this->validate_power_action(2,$ship_id);
$ship = $this->get_piece_row($ship_id);
$old_system_id = $ship['system_id'];
// Make sure systems are connected
$old_stars = $this->get_stars($old_system_id);
$new_stars = $this->get_stars($system_id);
foreach($old_stars as $old_star_id => $old_star){
foreach($new_stars as $new_star_id => $new_star){
if($old_star['pips'] == $new_star['pips']){
throw new BgaUserException(
self::_('Systems are not connected.'));
}
}
}
$sql = 'UPDATE Pieces
SET system_id='.$system_id.'
WHERE piece_id='.$ship_id;
self::DbQuery($sql);
$player_name = $this->getActivePlayerName();
$system_name = $this->get_system_name($system_id);
$old_system_name = $this->get_system_name($old_system_id);
self::notifyAllPlayers('notif_move',
clienttranslate('${player_name} moves a ${ship_str} ship from ${old_system_name} to ${system_name}.'),
array(
'player_name' => $player_name,
'system_id' => $system_id,
'ship_id' => $ship_id,
'ship_str' => $this->get_piece_string($ship_id),
'system_name' => $system_name,
'old_system_name' => $old_system_name
)
);
if($this->is_empty($old_system_id))
$this->fade($old_system_id);
$this->gamestate->nextState('trans_after_power_action');
self::incGameStateValue('turn_movements',1);
}
function fade($system_id){
// Notify client
$system_name = $this->get_system_name($system_id);
self::notifyAllPlayers('notif_fade',