-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameData.php
More file actions
1110 lines (1017 loc) · 43 KB
/
GameData.php
File metadata and controls
1110 lines (1017 loc) · 43 KB
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
declare(strict_types=1);
###
# Class GameData
# Handles reading, writing, and manipulating game state data from a primary data file.
# __construct(string $filePath)
# Initializes the object and reads data from the specified data file.
# Arguments: $filePath – path to the data file
# Output: none
# Access: public
# readFromFile(string $file): void
# Reads the data file, decodes JSON-like sections, and populates object properties.
# Arguments: $file – path to the data file
# Output: none
# Access: public
# writeToFile(string $file): void
# Encodes object properties into the file format and writes back to the data file.
# Arguments: $file – path to the [new] data file. Uses original data file if left blank
# Output: none
# Access: public
# buildIndexes(): void
# Creates the lookup tables used by the lookup methods of the class
# Arguments: None
# Output: None
# Access Private
# calculateSystemIncome(): int
# Calculates income for a colony based on population, RAW, and status notes (Opposition/Rebellion)
# Arguments: $name - colony name
# Output: integer
# Access: public
# calculatePurchaseExpense(): int
# Calculates all of the cost from purchases made on this data sheet. Note that construction is considered a purchase
# Arguments: None
# Output: integer
# Access: public
# checkBlockaded(string $name): bool
# Determines if the named colony is blockaded
# Arguments: $name – colony name
# Output: boolean yes/no
# Access: public
# checkColonyNotes(string $colonyName, string $note): bool
# Determines if the named colony has the given note
# Arguments: $name – colony name
# $note - the note to search for
# Output: boolean yes/no
# Access: public
# checkUnitNotes(string $unitName, string $note): bool
# Determines if the named unit has the given note
# Arguments: $name – colony name
# $note - the note to search for
# Output: boolean yes/no
# getUnitsAtLocation(string $location): array
# Returns all units present at a given location, including colonies, fleets, and mothballs.
# Arguments: $location – name of colony or sector
# Output: array of unit strings. Multiple unit strings if there is more than one quantity. Unit strings are the same as $this->unitList[]['ship']
# Access: public
# getFleetByName(string $name): ?array
# Returns a fleet array by its name.
# Arguments: $name – fleet name
# Output: fleet array or null if not found
# Access: public
# getFleetByLocation(string $location): ?array
# Returns all fleets found in the fleet array by its location.
# Arguments: $name – colony name
# Output: fleet array or null if not found
# Access: public
# getColonyByName(string $name): ?array
# Returns a colony array by its name.
# Arguments: $name – colony name
# Output: colony array or null if not found
# Access: public
# getUnitByName(string $ship): ?array
# Returns a unit object from unitList by ship designation.
# Arguments: $ship – ship designation
# Output: unit array or null if not found
# Access: public
# findPath(string $start, string $end, bool $excludeRestricted = false): array
# Finds a path and distance between two systems using BFS, ignoring "Unexplored" and optionally "Restricted" links.
# Arguments: $start – starting system, $end – ending system, $excludeRestricted – ignore restricted links if true
# Output: array, where 'path' is the list of systems and 'distance' is the number of links
# Access: public
# Example out: ["path" => ["Frigga","Olympus","Priam"], "distance" => 2]
# fleetHasAbility(string $fleet, string $ability): string
# Determines if a fleet has a unit with a certain ability. e.g. is a scout fleet?
# Arguments: $fleet – fleet to check, $ability – the ability keyword to check
# Output: string - The unit name with this ability. False if none
# getErrors(): array
# Returns any errors encountered during file read/write or decoding.
# Arguments: none. Optionally erase the errors if true
# Output: array of error messages
# Access: public
# locationHasAbility(string $location, string $ability): bool
# Determines if a location has a unit with a certain ability. e.g. is a scout fleet?
# Arguments: $location – locaiton to check, $ability – the ability keyword to check
# Output: string - The unit name with this ability. False if none
# syncUnitStates(): void
# Synchronizes unitsNeedingRepair and unitStates with current units in colonies, fleets, and mothballs.
# Arguments: none
# Output: none
# Access: public
# parseUnitQuantity(string $unit): array
# Parses a unit string like "3xDD-II" into quantity and unit name.
# Arguments: $unit – string unit identifier
# Output: array [quantity:int, name:string]
# Access: public
# atLeastPoliticalState(string $treatyState, string $stateCheck): bool
# Determines if one treaty type is more hostile than another
# Example: "Do we have at least a trade treaty with them?"
# atLeastPoliticalState($ourTreaty, 'Trade'); // true if $ourTreaty is 'Trade' or 'Mutual Defense' or 'Alliance'
# Arguments: $treatyState – string Current treaty state
# $stateCheck - string Treaty type to check against
# Output: boolean yes/no
# Access: public
# atLeastShipSize(string $shipDesign, string $designCheck): bool
# Determines if one hull type (design type) is larger than another
# Example: "Is this ship at least a CL"
# atLeastShipSize($ourShipDesign, 'CL'); // true if $ourShipDesign is 'CL' or 'CW' or 'CA' or 'NCA' etc...
# Arguments: $shipDesign – string Current design type
# $designCheck - string Design type to check against
# Output: boolean yes/no
# Access: public
# traceSupplyLines(string $start, int $distance): ?array
# Finds one or more paths where supply can be traced to the given location
# Supply locations includes supply ships, supply depots, and colonies
# Arguments: $start – string The loction to check the supply status on
# $distance - integer An optional amount of hops to trace
# Output: array [paths:array, source:string] - A collection of paths that satisfy supply. Source is 'colony' or 'supply ship'
# Access: public
# rollDie(): int
# Rolls a single D10 die
# Arguments: None
# Output: Integer - A randome number from 1 to 10
# Access: public
# isInState(string $stateArray, string $shipName, string $fleetName): ?int
# Determines if an entry is in the given unit-state-array. Returns the index to the array of the first matching entry found.
# unit-state-arrays are arrays who's unit string is in the format {unit name}+" w/ "+{fleet or colony name}
# Arguments: string - The unit state array to access. Either 'unitStates' or 'unitsNeedingRepair'
# string - The unit name to search for. Blank if unknown
# string - The fleet or colony name to search for. Blank if unknown
# Output: Integer - The index to the given array. False if an error or not found
# Access: public
# getLinkStatus($a, $b): bool|string
# Get the map connection status between two systems. Returns false if they aren't neighboring
# Arguments: String - Colony name
# String - Neighboring colony name
# Output: String - Connection status or false
# Access: public
# addUnitsToFleet (string $fleetName, string $unitString): void
# Add units (string entries like "3xAvenger" or "Avenger") to a fleet. Merges quantities when designs match.
# Arguments: String - Fleet name
# String - Unit name (possibly with quantity. e.g. "3xDD")
# Output: None
# removeUnitsFromFleet (string $fleetName, string $unitString): bool
# Remove specific quantity of design from fleet. returns true if removed, false if insufficient
# Arguments: String - Fleet name
# String - Unit name (possibly with quantity. e.g. "3xDD")
# Output: True if successful. False if not
# addUnitsToColony (string $colonyName, string $unitString): void
# Add units (string entries like "3xAvenger" or "Avenger") to a colony. Merges quantities when designs match.
# Arguments: String - Colony name
# String - Unit name (possibly with quantity. e.g. "3xDD")
# Output: None
# removeUnitsFromColony (string $colonyName, string $unitString): bool
# Remove specific quantity of design from a colony. returns true if removed, false if insufficient
# Arguments: String - Colony name
# String - Unit name (possibly with quantity. e.g. "3xDD")
# Output: True if successful. False if not
# Public properties, as defined by the data file specification:
# array $colonies
# array $empire
# array $events
# array $fleets
# array $game
# array $intelProjects
# array $mapConnections
# array $mapPoints
# array $offeredTreaties
# array $orders
# array $otherEmpires
# array $purchases
# array $treaties
# array $underConstruction
# array $unitsInMothballs
# array $unitsNeedingRepair
# array $unitStates
# array $unknownMovementPlaces
# array $unitList
# Misc property for reading/writing object to disk
# string $fileName
# Private properties, used for temporary record keeping
# $this->index = array();
# ['coloniesByName'][$name] = index of $this->colonies
# ['fleetsByLocation'][$location] = array of indices of $this->fleets
# ['fleetsByName'][$name] = index of $this->fleets
# ['fleetsHasAbility'][$name] = array of ability traits by fleet name
# ['locationsHasAbility'][$name] = array of $this->unitList[]['notes'] elements
# ['unitsAtLocation'][$location] = array of $this->unitList[]['ship'] elements
# ['unitsByName'][$name] = index of $this->unitList
# ['fleetUnitWithAbility'][$name][$ability] = a $this->unitList[]['ship'] element
###
###
# Class GameData
# Handles reading, writing, and manipulating game state data from a primary data file.
###
class GameData
{
// Properties
public array $colonies = [];
public array $empire = [];
public array $events = [];
public array $fleets = [];
public array $game = [];
public array $intelProjects = [];
public array $mapConnections = [];
public array $mapPoints = [];
public array $offeredTreaties = [];
public array $orders = [];
public array $otherEmpires = [];
public array $purchases = [];
public array $treaties = [];
public array $underConstruction = [];
public array $unitsInMothballs = [];
public array $unitsNeedingRepair = [];
public array $unitStates = [];
public array $unknownMovementPlaces = [];
public array $unitList = [];
public string $fileName = "";
private array $errors = [];
private array $writeVars = ['colonies','empire','events','fleets','game','intelProjects','mapConnections',
'mapPoints','offeredTreaties','orders','otherEmpires','purchases','treaties',
'underConstruction','unitStates','unitsInMothballs','unitsNeedingRepair',
'unknownMovementPlaces','unitList'
];
###
# Initializes the object and reads data from the specified data file.
# Arguments: $filePath – path to the data file
# Output: none
###
public function __construct(string $filePath)
{
$this->readFromFile ($filePath);
$this->fileName = $filePath;
}
###
# Reads the data file, decodes JSON-like sections, and populates object properties.
# Arguments: $file – path to the data file
# Output: none
###
public function readFromFile(string $file): void
{
if (!file_exists($file)) {
$this->errors[] = "File not found: {$file}";
return;
}
$content = file_get_contents($file);
if ($content === false) {
$this->errors[] = "Failed to read file: {$file}";
return;
}
// Remove "var " assignments and semicolons for JSON decode
$pattern = '/var\s+(\w+)\s*=\s*(.*?);(\s*\/\/.*)?(?=\r?\n|$)/s';
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$key = $match[1];
$jsonStr = trim($match[2]);
$decoded = json_decode($jsonStr, true);
if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
$this->errors[] = "JSON decode error for key '{$key}': " . json_last_error_msg();
continue;
}
if (property_exists($this, $key))
$this->$key = $decoded;
}
}
// ensure that the important data-sheet keys will exist
foreach ($this->writeVars as $jsonKey) {
if (!isset($this->$jsonKey))
$this->$jsonKey = [];
}
}
###
# Encodes object properties into the file format and writes back to the data file.
# Arguments: $file – path to the [new] data file. Uses original data file if left blank
# Output: none
###
public function writeToFile(string $file = ""): void
{
$tempFileName = substr(rtrim(strtr(base64_encode(random_bytes(3)), '+/', '-_' ),'=' ), 0, 4 );
// copy data into $dataArray. Only include named keys in $this->writeVars
$dataArray = array_filter(
get_object_vars($this),
fn($key) => in_array($key, $this->writeVars, true),
ARRAY_FILTER_USE_KEY
);
// Custom sort: sort all keys alphabetically, then move 'unitList' to the end
$unitListValue = null;
if (array_key_exists('unitList', $dataArray)) {
$unitListValue = $dataArray['unitList'];
unset($dataArray['unitList']);
}
ksort($dataArray); // Sort remaining keys alphabetically
$dataArray['unitList'] = $unitListValue; // Append 'unitList' at the end
$outputLines = [];
foreach ($dataArray as $key => $value) {
// Ensure key is a valid JS variable name
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $key))
$this->errors[] = "Invalid JS variable name: {$key}";
// Encode JSON safely
$json = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($json === false)
$this->errors[] = "Could not encode JSON for key '{$key}': " . json_last_error_msg();
$outputLines[] = "var $key = $json;";
}
// Combine all lines with newlines
$output = implode("\n", $outputLines) . "\n";
// Add extra newlines for readability in arrays of objects
$output = preg_replace('/},\s*{/', "},\n {", $output);
if ($file == "") // if the argument is empty, write the original filename
$file = $this->fileName;
else // if the argument is given, treat that as our original filename
$this->fileName = $file;
// Write the file
if (file_put_contents($tempFileName, $output) === false)
$this->errors[] = "Failed to write file: {$tempFileName}";
if (chmod($tempFileName,0777) === false )
$this->errors[] = "Failed to modify file '{$tempFileName}' to be written.";
if (rename( $tempFileName, $this->fileName) === false)
$this->errors[] = "Failed to rename file '{$tempFileName}' to '{$this->fileName}'";
}
###
# Creates the lookup tables used by the lookup methods of the class
# Arguments: None
# Output: None
# $this->index = array();
# ['coloniesByName'][$name] = index of $this->colonies
# ['fleetsByLocation'][$location] = array of indices of $this->fleets
# ['fleetsByName'][$name] = index of $this->fleets
# ['fleetsHasAbility'][$name] = array of ability traits by fleet name
# ['locationsHasAbility'][$name] = array of $this->unitList[]['notes'] elements
# ['unitsAtLocation'][$location] = array of $this->unitList[]['ship'] elements
# ['unitsByName'][$name] = index of $this->unitList
# ['fleetUnitWithAbility'][$name][$ability] = a $this->unitList[]['ship'] element
###
private function buildIndexes(): void
{
$this->index = [];
# Colonies By Name
$this->index['coloniesByName'] = [];
foreach ($this->colonies as $i => $c) {
$this->index['coloniesByName'][$c['name']] = $i;
}
# Fleets By Location
# Fleets By Name
$this->index['fleetsByLocation'] = [];
$this->index['fleetsByName'] = [];
foreach ($this->fleets as $key => $f) {
$this->index['fleetsByLocation'][$f['location']][] = $key;
$this->index['fleetsByName'][$f['name']] = $key;
}
# Units By Name
$this->index['unitsByName'] = [];
foreach ($this->unitList as $key=>$u) {
$this->index['unitsByName'][$u['ship']] = $key;
}
# Fleet Has Ability
$this->index['fleetsHasAbility'] = [];
$this->index['fleetUnitWithAbility'] = [];
foreach ($this->fleets as $f) {
$traits = [];
foreach ($f['units'] as $u) {
[$qty, $name]= $this->parseUnitQuantity($u);
$index = $this->index['unitsByName'][$name];
$unitData = $this->unitList[$index];
if (!empty($unitData['notes'])) {
// Split comma-separated notes, trim spaces
$notes = array_map('trim', explode(',', $unitData['notes']));
// Strip any "(N)" suffix where N is a number
$notes = array_map(function ($note) {
return preg_replace('/\s*\(\d+\)$/', '', $note);
}, $notes);
$traits = array_merge($traits, $notes);
// write $this->index['fleetUnitWithAbility'] while we have this data queued
$this->index['fleetUnitWithAbility'][$f['name']] ??= [];
foreach ($notes as $unitTrait) {
$this->index['fleetUnitWithAbility'][$f['name']][$unitTrait] = $unitData['ship'];
}
}
}
// Store unique traits per fleet
$this->index['fleetsHasAbility'][$f['name']] = array_values(array_unique($traits));
}
# Location Has Ability
$this->index['locationsHasAbility'] = [];
foreach ($this->colonies as $c) {
$traits = [];
foreach ($c['fixed'] as $u) {
[$qty, $name]= $this->parseUnitQuantity($u);
$index = $this->index['unitsByName'][$name];
$unitData = $this->unitList[$index];
if (!empty($unitData['notes'])) {
// Split comma-separated notes, trim spaces
$notes = array_map('trim', explode(',', $unitData['notes']));
// Strip any "(N)" suffix where N is a number
$notes = array_map(function ($note) {
return preg_replace('/\s*\(\d+\)$/', '', $note);
}, $notes);
$traits = array_merge($traits, $notes);
}
}
$fleetTraits = [];
if (!isset($this->index['fleetsByLocation'][$c['name']])) $this->index['fleetsByLocation'][$c['name']] = [];
foreach ($this->index['fleetsByLocation'][$c['name']] as $fleetIndex){
$f = $this->fleets[$fleetIndex];
$fleetTraits = array_merge($this->index['fleetsHasAbility'][$f['name']], $fleetTraits);
}
// Store unique traits per fleet
$this->index['locationsHasAbility'][$c['name']] = array_values(array_unique(array_merge($traits, $fleetTraits)));
}
# Units At Location
$this->index['unitsAtLocation'] = [];
foreach ($this->colonies as $c) {
if (!isset($this->index['unitsAtLocation'][$c['name']])) $this->index['unitsAtLocation'][$c['name']] = [];
foreach ($c['fixed'] as $u) {
[$qty, $name]= $this->parseUnitQuantity($u);
$this->index['unitsAtLocation'][$c['name']] = array_merge($this->index['unitsAtLocation'][$c['name']], array_fill(0, $qty, $name));
}
}
foreach ($this->fleets as $f) {
if (!isset($this->index['unitsAtLocation'][$f['location']])) $this->index['unitsAtLocation'][$f['location']] = [];
foreach ($f['units'] as $u) {
[$qty, $name]= $this->parseUnitQuantity($u);
$this->index['unitsAtLocation'][$f['location']] = array_merge($this->index['unitsAtLocation'][$f['location']], array_fill(0, $qty, $name));
}
}
// Note that unitsAtLocation() is counting unitsInMothballs. Is it supposed to?
// Examine where it is used. Determine if those steps care about mothballs
foreach ($this->unitsInMothballs as $f) {
if (!isset($this->index['unitsAtLocation'][$f['location']])) $this->index['unitsAtLocation'][$f['location']] = [];
foreach ($f['units'] as $u) {
[$qty, $name]= $this->parseUnitQuantity($u);
$this->index['unitsAtLocation'][$f['location']] = array_merge($this->index['unitsAtLocation'][$f['location']], array_fill(0, $qty, $name));
}
}
}
###
# Calculates income for a colony based on population, RAW, and status notes (Opposition/Rebellion)
# Arguments: $name - colony name
# Output: integer
###
# No Blockade check here
# This output value may affect other rules outside of being blockaded.
# In addition, this allows us to fund in-system items, despite the blockade
public function calculateSystemIncome( $name ): int
{
$colony = $this->getColonyByName($name);
if (!$colony) {
$this->errors[] = "Missing colony '{$name}' in calculateSystemIncome()";
return 0;
}
$output = $colony['population'] * $colony['raw'];
$name = $colony['name'] ?? '';
if ($this->checkColonyNotes($name, 'rebellion'))
$output = 0;
elseif ($this->checkColonyNotes($name, 'opposition')) {
// Martial law restores full productivity, at the cost of making it likely to rebel
// So if not Martial Law but is in opposition, then reduce output
if ($this->checkColonyNotes($name, 'Martial Law') === false)
$output = ceil($output / 2);
}
return $output;
}
###
# Calculates all of the cost from purchases made on this data sheet. Note that construction is considered a purchase
# Arguments: None
# Output: integer
###
# No lookup table for this. It's value changes as we process the construction
# phase. This allows us to purchase everything up to a point where the player
# runs out of funds.
public function calculatePurchaseExpense(): int
{
$output = 0;
foreach ($this->purchases as $purchase) {
$output += $purchase['cost'];
}
return $output;
}
###
# checkBlockaded(string $name): boolean
# Determines if the named colony is blockaded
# Arguments: $name – colony name
# Output: boolean yes/no
###
function checkBlockaded(string $name): bool
{
$colony = $this->getColonyByName($name);
if (!$colony) {
$this->errors[] = "Failure to get colony {$name} in checkBlockaded().";
return true;
}
if ($this->checkColonyNotes($name, 'blockaded'))
return true;
return false;
}
###
# Determines if the named colony has the given note
# Arguments: $name – colony name
# $note - the note to search for
# Output: boolean yes/no
###
function checkColonyNotes(string $colonyName, string $note): bool
{
$colony = $this->getColonyByName($colonyName);
if (!$colony) {
$this->errors[] = "Failure to get colony {$colonyName} in checkColonyNotes().";
return true;
}
if (strpos(strtolower($colony['notes']) ?? '', strtolower($note)) !== false)
return true;
return false;
}
###
# Determines if the named colony has the given note
# Arguments: $name – colony name
# $note - the note to search for
# Output: boolean yes/no
###
function checkUnitNotes(string $unitName, string $note): bool
{
$unit = $this->getUnitByName($unitName);
if (!$unit) {
$this->errors[] = "Failure to get unit {$unitName} in checkUnitNotes().";
return true;
}
if (strpos(strtolower($unit['notes']) ?? '', strtolower($note)) !== false)
return true;
return false;
}
###
# Returns all units present at a given location, including colonies, fleets, and mothballs.
# Arguments: $location – name of colony or sector
# Output: array of unit strings. Multiple unit strings if there is more than one quantity. Unit strings are the same as $this->unitList[]['ship']
###
public function getUnitsAtLocation(string $location): array
{
if (! isset($this->index) || !isset($this->index['unitsAtLocation']))
$this->buildIndexes();
$i = $this->index['unitsAtLocation'][$location] ?? '';
return $i;
}
###
# Returns a fleet array by its name.
# Arguments: $name – fleet name
# Output: fleet array or null if not found
###
public function getFleetByName(string $name): ?array
{
if (! isset($this->index) || !isset($this->index['fleetsByName']))
$this->buildIndexes();
$i = $this->index['fleetsByName'][$name] ?? null;
return $i === null ? null : $this->fleets[$i];
}
# getFleetByLocation(string $location): ?array
# Returns all fleets found in the fleet array by its location.
# Arguments: $name – colony name
# Output: fleet array or null if not found
# Access: public
public function getFleetByLocation(string $location): ?array
{
// $this->index['fleetsByLocation'][] is an array of indices to $this->fleets
if (! isset($this->index) || !isset($this->index['fleetsByLocation']))
$this->buildIndexes();
$i = $this->index['fleetsByLocation'][$location] ?? null;
if ($i == null) return null;
$fleetOut = [];
foreach ($i as $f) {
$fleetOut[] = $this->fleets[$f];
}
return $fleetOut;
}
###
# Returns a colony array by its name.
# Arguments: $name – colony name
# Output: colony array or null if not found
###
public function getColonyByName(string $name): ?array
{
if (! isset($this->index) || !isset($this->index['coloniesByName']))
$this->buildIndexes();
$i = $this->index['coloniesByName'][$name] ?? null;
return $i === null ? null : $this->colonies[$i];
}
###
# Returns a unit object from unitList by ship designation.
# Arguments: $ship – ship designation
# Output: unit array or null if not found
###
public function getUnitByName(string $ship): ?array
{
if (! isset($this->index) || !isset($this->index['unitsByName']))
$this->buildIndexes();
$i = $this->index['unitsByName'][$ship] ?? null;
return $i === null ? null : $this->unitList[$i];
}
###
# Finds a path and distance between two systems using BFS, ignoring "Unexplored" and optionally "Restricted" links.
# Arguments: $start – starting system, $end – ending system, $excludeRestricted – ignore restricted links if true
# Output: array, where 'path' is the list of systems and 'distance' is the number of links
###
public function findPath(string $start, string $end, bool $excludeRestricted = false): array
{
$graph = [];
foreach ($this->mapConnections as $conn) {
[$from, $to, $status] = $conn;
if ($status === 'Unexplored') continue;
if ($excludeRestricted && $status === 'Restricted') continue;
if (!isset($graph[$from])) $graph[$from] = [];
if (!isset($graph[$to])) $graph[$to] = [];
$graph[$from][] = $to;
$graph[$to][] = $from;
}
$queue = [[$start]];
$visited = [$start => true];
while ($queue) {
$path = array_shift($queue);
$node = end($path);
if ($node === $end)
return ['path' => $path, 'distance' => count($path) - 1];
foreach ($graph[$node] ?? [] as $neighbor) {
if (!isset($visited[$neighbor])) {
$visited[$neighbor] = true;
$queue[] = array_merge($path, [$neighbor]);
}
}
}
return ['path' => [], 'distance' => -1];
}
###
# Determines if a fleet has a unit with a certain ability. e.g. is a scout fleet?
# Arguments: $fleet – fleet to check, $ability – the ability keyword to check
# Output: boolean - Yes/no answer
###
public function fleetHasAbility(string $fleet, string $ability): bool
{
if (! isset($this->index) || !isset($this->index['fleetsHasAbility']))
$this->buildIndexes();
if (array_search($ability, $this->index['fleetsHasAbility'][$fleet]) !== false)
return true;
return false;
}
###
# Finds and returns a fleet unit with a certain ability. e.g. find a scout in fleet
# Arguments: $fleetName – fleet to check, $ability – the ability keyword to check
# Output: string - The unit designator that has the ability
###
public function fleetUnitWithAbility(string $fleet, string $ability): bool
{
if (! isset($this->index) || !isset($this->index['fleetUnitWithAbility']))
$this->buildIndexes();
if (!isset($this->index['fleetUnitWithAbility'][$fleet]) || !isset($this->index['fleetUnitWithAbility'][$fleet][$ability]))
return false;
return $this->index['fleetUnitWithAbility'][$fleet][$ability];
}
###
# Returns any errors encountered during file read/write or decoding.
# Arguments: none. Optionally erase the errors if true
# Output: array of error messages
###
public function getErrors(bool $eraseErrors = false): array
{
if (!$eraseErrors)
return $this->errors;
// Temporarily store errors in another variable
$errors = $this->errors;
// Erase the errors array
$this->errors = [];
return $errors;
}
###
# locationHasAbility(string $location, string $ability): string
# Determines if a location has a unit with a certain ability. e.g. is a scout?
# Arguments: $location – locaiton to check, $ability – the ability keyword to check
# Output: string - The unit name with this ability. Empty if none
###
public function locationHasAbility(string $location, string $ability): string
{
$units = $this->getUnitsAtLocation($location); // get units
if (empty($units)) return '';
foreach ($units as $u) { // get each unit of the fleet
$unitData = $this->getUnitByName($u); // get the named unit
if ($this->checkUnitNotes($u, $ability)) // if the named unit has the ability, end here
return $u;
}
return ''; // we didn't find the ability in the location
}
###
# Synchronizes unitsNeedingRepair and unitStates with current units in colonies, fleets, and mothballs.
# Arguments: none
# Output: none
###
public function syncUnitStates(): void
{
// Reset unitsNeedingRepair and unitStates
$repair = [];
$states = [];
foreach ($this->colonies as $colony) {
$units = array_merge($colony['fixed'] ?? []);
foreach ($units as $u) {
[$qty, $name] = $this->parseUnitQuantity($u);
$unitStateKey = $this->isInState('unitsNeedingRepair', $name, $colony['name']);
if ($unitStateKey !== false)
$repair[] = $this->unitsNeedingRepair[$unitStateKey];
$unitStateKey = $this->isInState('unitStates', $name, $colony['name']);
if ($unitStateKey !== false)
$states[] = $this->unitStates[$unitStateKey];
}
}
foreach ($this->fleets as $fleet) {
$units = $fleet['units'] ?? [];
foreach ($units as $u) {
[$qty, $name] = $this->parseUnitQuantity($u);
$unitStateKey = $this->isInState('unitsNeedingRepair', $name, $fleet['name']);
if ($unitStateKey !== false)
$repair[] = $this->unitsNeedingRepair[$unitStateKey];
$unitStateKey = $this->isInState('unitStates', $name, $fleet['name']);
if ($unitStateKey !== false)
$states[] = $this->unitStates[$unitStateKey];
}
}
$this->unitsNeedingRepair = array_unique($repair);
$this->unitStates = array_unique($states, SORT_REGULAR);
}
###
# Parses a unit string like "3xDD-II" into quantity and unit name.
# Arguments: $unit – string unit identifier
# Output: array [quantity:int, name:string]
###
public function parseUnitQuantity(string $unit): array
{
if (preg_match('/^(\d+)x(.+)$/', $unit, $matches)) {
return [(int)$matches[1], trim($matches[2])];
}
return [1, $unit];
}
###
# Determines if one treaty type is more hostile than another
# Example: "Do we have at least a trade treaty with them?"
# atLeastPoliticalState($ourTreaty, 'Trade'); // true if $ourTreaty is 'Trade' or 'Mutual Defense' or 'Alliance'
# Arguments: $treatyState – string Current treaty state
# $stateCheck - string Treaty type to check against
# Output: boolean yes/no
###
public function atLeastPoliticalState(string $treatyState, string $stateCheck): bool
{
$treatyOrder = ['War', 'Hostilities', 'Neutral', 'Non-Aggression', 'Trade', 'Mutual Defense', 'Alliance'];
$treatyIdx = array_search($treatyState, $treatyOrder);
$checkIdx = array_search($stateCheck, $treatyOrder);
// False if the current treaty is unknown or the treaty to check is unknown or the current treaty is more hostile than the treaty to check
if ($treatyState === false || $treatyState === false || $treatyIdx < $checkIdx)
return false;
return true;
}
###
# atLeastShipSize(string $shipDesign, string $designCheck): bool
# Determines if one hull type (design type) is larger than another
# Example: "Is this ship at least a CL"
# atLeastShipSize($ourShipDesign, 'CL'); // true if $ourShipDesign is 'CL' or 'CW' or 'CA' or 'NCA' etc...
# Arguments: $shipDesign – string Current design type
# $designCheck - string Design type to check against
# Output: boolean yes/no
###
public function atLeastShipSize(string $shipDesign, string $designCheck): bool
{
// sorted by size. "New" hull versions considered larger than standard versions.
// "War" versions considered smaller than "Heavy" versions: CWs considered smaller than CAs
/*
$hullOrder = [ 'LF','MF','HF','SHF','AB','BOOM','FT',
'SAux','POL','FF','NFF','FFW','FFH','DD','NDD','DDH','DW','HDW',
'LAux','CL','CW','CWH','CA','TUG','NCA','CCH','BC','BCH',
'DNL','DNW','DN','DNH','BB'
];
// VBAM Hulls only
$hullOrder = [ 'LF','MF','HF','SHF','AB','CT','FF','DD','CL','CW','CA','BC','BB','DN','SD','TN'];
*/
// Both lists, combined. Note that VBAM puts a 'DN' as larger than a 'BB', which is switched in SFB. The SFB version is used here.
$hullOrder = [ 'LF','MF','HF','SHF','AB','BOOM','FT',
'CT','SAux','POL','FF','NFF','FFW','FFH','DD','NDD','DDH','DW','HDW',
'LAux','CL','CW','CWH','CA','TUG','NCA','CCH','BC','BCH',
'DNL','DNW','DN','DNH','BB','SD','TN'
];
$designIdx = array_search($shipDesign, $hullOrder);
$checkIdx = array_search($designCheck, $hullOrder);
// False if the current treaty is unknown or the treaty to check is unknown or the current treaty is more hostile than the treaty to check
if ($treatyState === false || $treatyState === false || $designIdx < $checkIdx)
return false;
return true;
}
###
# traceSupplyLines(string $start, int $distance): ?array
# Finds one or more paths where supply can be traced to the given location.
# Supply locations includes supply ships, supply depots, and colonies
# Arguments: $start – string The loction to check the supply status on
# $distance - integer An optional amount of hops to trace
# Output: array [paths:array, source:string] - A collection of paths that satisfy supply. Source is 'colony' or 'supply ship'
###
public function traceSupplyLines(string $start, int $distance=3): ?array
{
$output = array();
// Identify Supply Sources
$supplySources = [];
foreach ($this->colonies as $colony) {
if ($colony['owner'] != $this->empire['empire']) continue;
$isCore = ($colony['population'] >= 5);
$isGoodOrder = ($colony['morale'] >= ($colony['population'] / 2));
$hasDepot = false;
if ($this->locationHasAbility($colony['name'], 'Supply Depot') === true)
$hasDepot = true;
if (($isCore && $isGoodOrder) || $hasDepot)
$supplySources[] = [$colony['name'],'colony'];
}
// Any unit with "Supply" in its notes can resupply units in the same location that cannot otherwise trace supply.
foreach ($this->fleets as $fleet) {
if (!$this->fleetHasAbility($fleet['name'], 'Supply')) continue;
$supplyShip = $this->fleetUnitWithAbility($fleet['name'], 'Supply');
if ($supplyShip !== '') {
$isExhausted = false;
$unitStateKey = $this->isInState("unitStates",$supplyShip,$fleet['name']);
if ($unitStateKey !== false && $this->unitStates[$unitStateKey][1] === 'Exhausted')
$isExhausted = true;
// Skip fleet if its supply unit is exhausted
if ($isExhausted) continue;
$supplySources[] = [$fleet['location'],'fleet'];
}
}
// Identify paths
foreach ($supplySources as $key=>$place) {
$paths = $this->findPath($start, $place[0], true);
if ($paths['distance'] > $distance) continue;
$isBad = false;
foreach($paths['path'] as $intermediate) {
if ($intermediate == $start) continue; // skip if looking at the start location (it can be blockaded)
if ($this->checkBlockaded($intermediate) !== true) continue;
// intermediate is blockaded
$isBad = true;
}
if (!$isBad)
$output[] = ['paths'=>$paths,'source'=>$place[1]];
}
return $output;
}
###
# rollDie(): int
# Rolls a single D10 die
# Arguments: None
# Output: Integer - A random number from 1 to 10
###
public function rollDie(): int
{
return mt_rand(1,10);
}
###
# isInState(string $stateArray, string $shipName, string $fleetName): ?int
# Determines if an entry is in the given unit-state-array. Returns the index to the array of the first matching entry found.
# unit-state-arrays are arrays who's unit string is in the format {unit name}+" w/ "+{fleet or colony name}
# Arguments: string - The unit state array to access. Either 'unitStates' or 'unitsNeedingRepair'
# string - The unit name to search for. Blank if unknown
# string - The fleet or colony name to search for. Blank if unknown
# Output: Integer - The index to the given array. False if an error or not found
###
public function isInState(string $stateArray, string $shipName, string $fleetName): bool|int
{
if ($shipName == '' && $fleetName == '')
return false;
if (strtolower($stateArray) == "unitstates")
foreach ($this->unitStates as $key => $state) {
if ($shipName == '' && strpos($state[0]," w/ {$fleetName}") !== false)
return $key;
if ($fleetName == '' && strpos($state[0],"{$shipName} w/ ") === 0)
return $key;
if ($shipName !== '' && $fleetName !== '' && $state[0] == "{$shipName} w/ {$fleetName}")
return $key;
}
if (strtolower($stateArray) == "unitsneedingrepair")
foreach ($this->unitsNeedingRepair as $key => $state) {
if ($shipName == '' && strpos($state," w/ {$fleetName}") !== false)
return $key;
if ($fleetName == '' && strpos($state,"{$shipName} w/ ") === 0)
return $key;
if ($shipName !== '' && $fleetName !== '' && $state == "{$shipName} w/ {$fleetName}")
return $key;
}
return false;
}
###
# getLinkStatus($a, $b): bool|string
# Get the map connection status between two systems. Returns false if they aren't neighboring
# Arguments: String - Colony name
# String - Neighboring colony name
# Output: String - Connection status or false
###
public function getLinkStatus($a, $b): bool|string
{
foreach ($this->mapConnections as $conn) {
[$from, $to, $status] = $conn;
if (($from === $a && $to === $b) || ($from === $b && $to === $a)) return ucFirst($status);
}
return false;
}
###
# addUnitsToFleet (string $fleetName, string $unitString): void