forked from harrischristiansen/generals-bot
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgit_diff.txt
More file actions
2327 lines (2289 loc) · 151 KB
/
git_diff.txt
File metadata and controls
2327 lines (2289 loc) · 151 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
commit 6de6d0ce1c8bd95e42ea4f408387d71b1ab8c9e9
Author: Travis Drake <tdrake0x45@gmail.com>
Date: Thu Mar 26 18:50:04 2026 -0700
it thinks it's done, now attempting to run it
diff --git a/bot_ek0x45.py b/bot_ek0x45.py
index fff55d3..8684eb6 100644
--- a/bot_ek0x45.py
+++ b/bot_ek0x45.py
@@ -435,22 +435,6 @@ class EklipZBot(object):
def spawnWorkerThreads(self):
return
- # DONE STEP2: Move to BotModules/BotRepetition.py as BotRepetition.detect_repetition_at_all. Pure move-history repetition scan against bot history/map state; delegate from shell.
- def detect_repetition_at_all(self, turns=4, numReps=2) -> bool:
- return BotRepetition.detect_repetition_at_all(self, turns, numReps)
-
- # DONE STEP2: Move to BotModules/BotRepetition.py as BotRepetition.detect_repetition. Pure repetition check on a candidate move using bot history only; keep shell pass-through for call-site stability.
- def detect_repetition(self, move, turns=4, numReps=2):
- return BotRepetition.detect_repetition(self, move, turns, numReps)
-
- # DONE STEP2: Move to BotModules/BotRepetition.py as BotRepetition.detect_repetition_tile. History-based tile repetition query; belongs with other repetition heuristics.
- def detect_repetition_tile(self, tile: Tile, turns=6, numReps=2):
- return BotRepetition.detect_repetition_tile(self, tile, turns, numReps)
-
- # DONE STEP2: Move to BotModules/BotRepetition.py as BotRepetition.move_half_on_repetition. Thin policy wrapper over repetition detection; migrate with the repetition cluster unchanged.
- def move_half_on_repetition(self, move, repetitionTurns, repCount=3):
- return BotRepetition.move_half_on_repetition(self, move, repetitionTurns, repCount)
-
# STEP2: Stay in EklipZBotV2.py. Top-level move orchestration/error handling/history/render prep spanning many modules; keep on shell and have it call extracted helpers.
def find_move(self, is_lag_move=False) -> Move | None:
move: Move | None = None
@@ -543,42 +527,6 @@ class EklipZBot(object):
return move
- # DONE STEP2: Move to BotModules/BotPathingUtils.py as BotPathingUtils.clean_up_path_before_evaluating. CurPath maintenance / dedupe logic tied to path semantics, not top-level orchestration.
- def clean_up_path_before_evaluating(self):
- return BotPathingUtils.clean_up_path_before_evaluating(self)
-
- # DONE STEP2: Move to BotModules/BotRepetition.py as BotRepetition.dropped_move. Last-move/drop inference based on move history and map deltas; keep a thin bot alias because it is referenced from path maintenance.
- def droppedMove(self, fromTile=None, toTile=None, movedHalf=None):
- return BotRepetition.dropped_move(self, fromTile, toTile, movedHalf)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_city_found. Small city discovery side-effect handler updating trackers/classifiers only.
- def handle_city_found(self, tile):
- return BotEventHandlers.handle_city_found(self, tile)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_tile_captures. Capture-event bookkeeping that updates territory/army tracking and aggression state; migrate with event handlers.
- def handle_tile_captures(self, tile: Tile):
- return BotEventHandlers.handle_tile_captures(self, tile)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_player_captures. Player-death event processing that scrubs tracker state and triggers re-evaluation; belongs in the event cluster.
- def handle_player_captures(self, capturee: int, capturer: int):
- return BotEventHandlers.handle_player_captures(self, capturee, capturer)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_tile_deltas. Logging-only tile delta hook; keep with event handlers for completeness even though behavior is minimal.
- def handle_tile_deltas(self, tile):
- return BotEventHandlers.handle_tile_deltas(self, tile)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_tile_discovered. Discovery event bookkeeping touching rescans, paths, and territory updates; keep grouped with map update handlers.
- def handle_tile_discovered(self, tile):
- return BotEventHandlers.handle_tile_discovered(self, tile)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_tile_vision_change. Vision-change event handler with tracker/path invalidation side effects; migrate intact with the other event hooks.
- def handle_tile_vision_change(self, tile: Tile):
- return BotEventHandlers.handle_tile_vision_change(self, tile)
-
- # DONE STEP2: Move to BotModules/BotEventHandlers.py as BotEventHandlers.handle_army_moved. Army movement event bookkeeping updating trackers/opponent data; belongs in the event-handler module.
- def handle_army_moved(self, army: Army):
- return BotEventHandlers.handle_army_moved(self, army)
-
# STEP2: Stay in EklipZBotV2.py. Tiny shell utility used broadly for perf/log timing display; keep local on the bot.
def get_elapsed(self):
return round(self.perf_timer.get_elapsed_since_update(self._map.turn), 3)
@@ -619,7 +567,7 @@ class EklipZBot(object):
teammatePlayer = self._map.players[self.teammate]
if not teammatePlayer.dead and self._map.generals[self.teammate]:
self.teammate_general = self._map.generals[self.teammate]
- self.teammate_path = self.get_path_to_target(self.teammate_general, preferEnemy=True, preferNeutral=True)
+ self.teammate_path = BotPathingUtils.get_path_to_target(self.teammate_general, preferEnemy=True, preferNeutral=True)
else:
self.teammate_general = None
self.teammate_path = None
@@ -635,7 +583,7 @@ class EklipZBot(object):
chatUpdate = self._chat_messages_received.get()
self.handle_chat_message(chatUpdate)
- self.check_target_player_just_took_city()
+ BotTargeting.check_target_player_just_took_city(self)
# None tells the cache to recalculate this turn to either true or false... Don't change to false, moron.
self._spawn_cramped = None
@@ -799,108 +747,6 @@ class EklipZBot(object):
self.cached_scrims = {}
- # DONE STEP2: Move to BotModules/BotTimings.py as BotTimings.is_player_aggressive. Small timing/policy query over aggression_factor; belongs with timing heuristics.
- def is_player_aggressive(self, player: int, turnPeriod: int = 50) -> bool:
- return BotTimings.is_player_aggressive(self, player, turnPeriod)
-
- # DONE STEP2: Move to BotModules/BotTimings.py as BotTimings.get_timings_old. Legacy timing policy retained for reference/compatibility; move intact with timing logic and keep a shell pass-through if still referenced.
- def get_timings_old(self) -> Timings:
- return BotTimings.get_timings_old(self)
-
- # DONE STEP2: Move to BotModules/BotTimings.py as BotTimings.get_timings. Primary timing/cycle policy calculator; strongly cohesive with other timing heuristics and should migrate as one unit.
- def get_timings(self) -> Timings:
- return BotTimings.get_timings(self)
-
- # DONE STEP2: Move to BotModules/BotPathingUtils.py as BotPathingUtils.get_undiscovered_count_on_path. Tiny path-content utility used by timing/targeting logic; belongs with path helpers.
- def get_undiscovered_count_on_path(self, path: Path) -> int:
- return BotPathingUtils.get_undiscovered_count_on_path(self, path)
-
- # DONE STEP2: Move to BotModules/BotPathingUtils.py as BotPathingUtils.get_enemy_count_on_path. Tiny path-content utility used by timing/path evaluation; keep with path helper cluster.
- def get_enemy_count_on_path(self, path: Path) -> int:
- return BotPathingUtils.get_enemy_count_on_path(self, path)
-
- # DONE STEP2: Move to BotModules/BotExpansionOps.py as BotExpansionOps.timing_expand. Expansion timing stub/policy helper; keep with expansion even though it currently returns None.
- def timing_expand(self):
- return BotExpansionOps.timing_expand(self)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.timing_gather. Main timing-window gather executor with gather planning/pruning and path conversion; migrate intact with gather helpers.
- def timing_gather(
- self,
- startTiles: typing.List[Tile],
- negativeTiles: typing.Set[Tile] | None = None,
- skipTiles: typing.Set[Tile] | None = None,
- force=False,
- priorityTiles: typing.Set[Tile] | None = None,
- targetTurns=-1,
- includeGatherTreeNodesThatGatherNegative=False, # DO NOT set this to True, causes us to slam tiles into dumb shit everywhere
- useTrueValueGathered: bool = False,
- pruneToValuePerTurn: bool = False,
- priorityMatrix: MapMatrixInterface[float] | None = None,
- distancePriorities: MapMatrixInterface[int] | None = None,
- logStuff: bool = False
- ) -> Move | None:
- return BotGatherOps.timing_gather(self, startTiles, negativeTiles, skipTiles, force, priorityTiles, targetTurns, includeGatherTreeNodesThatGatherNegative, useTrueValueGathered, pruneToValuePerTurn, priorityMatrix, distancePriorities, logStuff)
-
- # DONE STEP2: Move to BotModules/BotExpansionOps.py as BotExpansionOps.make_first_25_move. Early-game opening/expansion move chooser tied to city expansion plans and expansion search policy.
- def make_first_25_move(self) -> Move | None:
- return BotExpansionOps.make_first_25_move(self)
-
- # self.viewInfo.add_info_line('wtf, explan plan was empty but we\'re in first 25 still..? Switching to old expansion')
- # else:
- # with self.perf_timer.begin_move_event(
- # f'First 25 expansion FFA'):
- #
- # if self._map.turn < 22:
- # return None
- #
- # nonGeneralArmyTiles = [tile for tile in filter(lambda tile: tile != self.general and tile.army > 1, self._map.players[self.general.player].tiles)]
- #
- # skipTiles = set()
- #
- # if len(nonGeneralArmyTiles) > 0:
- # skipTiles.add(self.general)
- # elif self.general.army < 3 and self._map.turn < 45:
- # return None
- #
- # # EXPLORATION was the old way for 1v1 pre-optimal-first-25
- # # path = self.get_optimal_exploration(50 - self._map.turn, skipTiles=skipTiles)
- #
- # # prioritize tiles that explore the least
- # distMap = [[1000 for y in range(self._map.rows)] for x in range(self._map.cols)]
- # for tile in self._map.reachableTiles:
- # val = 60 - int(self.get_distance_from_board_center(tile, center_ratio=0.0))
- # distMap[tile.x][tile.y] = val
- #
- # # hack
- # oldDistMap = self.board_analysis.intergeneral_analysis.bMap
- # try:
- # self.board_analysis.intergeneral_analysis.bMap = distMap
- # path, allPaths = ExpandUtils.get_optimal_expansion(
- # self._map,
- # self.general.player,
- # self.player,
- # 50 - self._map.turn,
- # self.board_analysis,
- # self.territories.territoryMap,
- # skipTiles,
- # viewInfo=self.viewInfo
- # )
- # finally:
- # self.board_analysis.intergeneral_analysis.bMap = oldDistMap
- #
- # if (self._map.turn < 46
- # and self.general.army < 3
- # and len(nonGeneralArmyTiles) == 0
- # and SearchUtils.count(self.general.movable, lambda tile: not tile.isMountain and tile.player == -1) > 0):
- # self.info("Skipping move because general.army < 3 and all army on general and self._map.turn < 46")
- # # dont send 2 army except right before the bonus, making perfect first 25 much more likely
- # return None
- # move = None
- # if path:
- # self.info("Dont make me expand. You don't want to see me when I'm expanding.")
- # move = self.get_first_path_move(path)
- # return move
-
# STEP2: Stay in EklipZBotV2.py. High-level pre-move orchestration that coordinates timings, path recalculation, out-of-play mode, all-in state, and dropped-move recovery across many domains.
def perform_move_prep(self, is_lag_move: bool = False):
with self.perf_timer.begin_move_event('scan_map_for_large_tiles_and_leaf_moves()'):
@@ -1069,12 +915,6 @@ class EklipZBot(object):
for t in self.general.movable:
if t.isCity and t.isNeutral and t.army == -1:
return Move(self.general, t)
-
- # with self.perf_timer.begin_move_event('Checking 1 move kills'):
- # quickKillMove = self.check_for_1_move_kills()
- # if quickKillMove is not None:
- # return quickKillMove
-
self.clean_up_path_before_evaluating()
if self.curPathPrio >= 0:
@@ -1152,7 +992,7 @@ class EklipZBot(object):
if defenseSavePath is not None:
self.viewInfo.color_path(PathColorer(defenseSavePath, 255, 100, 255, 200))
if defenseMove is not None:
- if not self.detect_repetition(defenseMove, turns=6, numReps=3) or (threat.threatType == ThreatType.Kill and threat.path.tail.tile.isGeneral):
+ if not BotRepetition.detect_repetition(defenseMove, turns=6, numReps=3) or (threat.threatType == ThreatType.Kill and threat.path.tail.tile.isGeneral):
if defenseMove.source in self.largePlayerTiles and self.targetingArmy is None:
logbook.info(f'threatDefense overriding targetingArmy with {str(threat.path.start.tile)}')
self.targetingArmy = self.get_army_at(threat.path.start.tile)
@@ -1255,7 +1095,7 @@ class EklipZBot(object):
if self.curPath.length > 1:
self.curPath = self.curPath.get_subsegment(path.length - 2)
move = self.get_first_path_move(path)
- if not self.detect_repetition(move):
+ if not BotRepetition.detect_repetition(move):
return move
if self.force_far_gathers and self.force_far_gathers_turns > 0:
@@ -1373,15 +1213,6 @@ class EklipZBot(object):
# if ahead on economy, but not %30 ahead on army we should play defensively
self.defend_economy = self.should_defend_economy(defenseCriticalTileSet)
- # if self.targetingArmy and not self.targetingArmy.scrapped and self.targetingArmy.tile.army > 2 and not self.is_all_in_losing:
- # with self.perf_timer.begin_move_event('Continue Army Kill'):
- # armyTargetMove = self.continue_killing_target_army()
- # if armyTargetMove:
- # # already logged internally
- # return armyTargetMove
- # else:
- # self.targetingArmy = None
-
if WinCondition.DefendContestedFriendlyCity in self.win_condition_analyzer.viable_win_conditions:
with self.perf_timer.begin_move_event(f'Getting city preemptive defense {str(self.win_condition_analyzer.defend_cities)}'):
cityDefenseMove = self.get_city_preemptive_defense_move(defenseCriticalTileSet)
@@ -1405,9 +1236,6 @@ class EklipZBot(object):
if self.expansion_plan and self.expansion_plan.includes_intercept and not self.is_all_in_losing:
move = self.expansion_plan.selected_option.get_first_move()
if not self.detect_repetition(move):
- # if isinstance(self.expansion_plan.selected_option, InterceptionOptionInfo):
- # atTile = self.expansion_plan.selected_option.
- # atTile = None
self.info(f'Pass thru EXP int! {move} {self.expansion_plan.selected_option}')
return move
@@ -1418,84 +1246,14 @@ class EklipZBot(object):
expNegs.update(self.win_condition_analyzer.contestable_cities)
largeArmyExpContinuationMove = self.try_get_enemy_territory_exploration_continuation_move(expNegs)
- if largeArmyExpContinuationMove is not None and not self.detect_repetition(largeArmyExpContinuationMove):
+ if largeArmyExpContinuationMove is not None and not BotRepetition.detect_repetition(largeArmyExpContinuationMove):
# already logged
return largeArmyExpContinuationMove
- # if self.threat_kill_path is not None and self.threat_kill_path:
- # self.info(f"we're pretty safe from threat via gather, trying to kill threat instead.")
- # # self.curPath = path
- # self.targetingArmy = self.get_army_at(self.threat.path.start.tile)
- # move = self.get_first_path_move(self.threat_kill_path)
- # if not self.detect_repetition(move, 4, numReps=3):
- # if self.detect_repetition(move, 4, numReps=2):
- # move.move_half = True
- # return move
-
if 50 <= self._map.turn < 75:
move = self.try_gather_tendrils_towards_enemy()
if move is not None:
return move
- #
- # threatDefenseLength = 2 * self.distance_from_general(self.targetPlayerExpectedGeneralLocation) // 3 + 1
- # if self.targetPlayerExpectedGeneralLocation.isGeneral:
- # threatDefenseLength = self.distance_from_general(self.targetPlayerExpectedGeneralLocation) // 2 + 2
- #
- # if (
- # threat is not None
- # and threat.threatType == ThreatType.Kill
- # and threat.path.length < threatDefenseLength
- # and not self.is_all_in()
- # and self._map.remainingPlayers < 4
- # and threat.threatPlayer == self.targetPlayer
- # ):
- # logbook.info(f"*\\*\\*\\*\\*\\*\n Kill (non-vision) threat??? ({time.perf_counter() - start:.3f} in)")
- # threatKill = self.kill_threat(threat)
- # if threatKill and self.worth_path_kill(threatKill, threat.path, threat.armyAnalysis):
- # if self.targetingArmy is None:
- # logbook.info(f'setting targetingArmy to {str(threat.path.start.tile)} in Kill (non-vision) threat')
- # self.targetingArmy = self.get_army_at(threat.path.start.tile)
- # saveTile = threatKill.start.tile
- # nextTile = threatKill.start.next.tile
- # move = Move(saveTile, nextTile)
- # if not self.detect_repetition(move, 6, 3):
- # self.viewInfo.color_path(PathColorer(threatKill, 0, 255, 204, 255, 10, 200))
- # move.move_half = self.should_kill_path_move_half(threatKill)
- # self.info(f"Threat kill. half {move.move_half}, {threatKill.toString()}")
- # return move
-
- # ARMY INTERCEPTION SHOULD NOW COVER VISION THREAT STUFF.
- # if (
- # threat is not None
- # and threat.threatType == ThreatType.Vision
- # and not self.is_all_in()
- # and threat.path.start.tile.visible
- # and self.should_kill(threat.path.start.tile)
- # and self.just_moved(threat.path.start.tile)
- # and threat.path.length < min(10, self.distance_from_general(self.targetPlayerExpectedGeneralLocation) // 2 + 1)
- # and self._map.remainingPlayers < 4
- # and threat.threatPlayer == self.targetPlayer
- # ):
- # logbook.info(f"*\\*\\*\\*\\*\\*\n Kill vision threat. ({time.perf_counter() - start:.3f} in)")
- # # Just kill threat then, nothing crazy
- # path = self.kill_enemy_path(threat.path, allowGeneral = True)
- #
- # visionKillDistance = 5
- # if path is not None and self.worth_path_kill(path, threat.path, threat.armyAnalysis, visionKillDistance):
- # if self.targetingArmy is None:
- # logbook.info(f'setting targetingArmy to {str(threat.path.start.tile)} in Kill VISION threat')
- # self.targetingArmy = self.get_army_at(threat.path.start.tile)
- # self.info(f"Killing vision threat {threat.path.start.tile.toString()} with path {str(path)}")
- # self.viewInfo.color_path(PathColorer(path, 0, 156, 124, 255, 10, 200))
- # move = self.get_first_path_move(path)
- # if not self.detect_repetition(move, turns=4, numReps=2) and (not path.start.tile.isGeneral or self.general_move_safe(move.dest)):
- # move.move_half = self.should_kill_path_move_half(path)
- # return move
- # elif threat.path.start.tile == self.targetingArmy:
- # logbook.info("threat.path.start.tile == self.targetingArmy and not worth_path_kill. Setting targetingArmy to None")
- # self.targetingArmy = None
- # elif path is None:
- # logbook.info("No vision threat kill path?")
if self.curPath is not None:
move = self.continue_cur_path(threat, defenseCriticalTileSet)
@@ -1595,12 +1353,6 @@ class EklipZBot(object):
self.info(f'FFA AFK')
return None
- # if self._map.turn > 150:
- # with self.perf_timer.begin_move_event(f'No gather found final scrim'):
- # scrimMove = self.find_end_of_turn_scrim_move(threat, kingKillPath)
- # if scrimMove is not None:
- # return scrimMove
-
# NOTE NOTHING PAST THIS POINT CAN TAKE ANY EXTRA TIME
if not self.is_all_in():
@@ -1636,27 +1388,8 @@ class EklipZBot(object):
return gathMove
move = None
value = -1
- #
- # with self.perf_timer.begin_move_event('FOUND NO MOVES FINAL MST GATH'):
- # gathers = self.build_mst(self.target_player_gather_targets, 1.0, 50, None)
- #
- # turns, value, gathers = Gather.prune_mst_to_max_army_per_turn_with_values(
- # gathers,
- # 1,
- # self.general.player,
- # teams=MapBase.get_teams_array(self._map),
- # preferPrune=self.expansion_plan.preferred_tiles if self.expansion_plan is not None else None,
- # viewInfo=self.viewInfo if self.info_render_gather_values else None)
- # self.gatherNodes = gathers
- # # move = self.get_gather_move(gathers, None, 1, 0, preferNeutral = True)
- # move = self.get_tree_move_default(gathers)
if move is None:
- # turnInCycle = self.timings.get_turn_in_cycle(self._map.turn)
- # if self.timings.cycleTurns - turnInCycle < self.timings.cycleTurns - self.target_player_gather_path.length * 0.66:
- # self.info("Found-no-moves-gather NO MOVE? Set launch now.")
- # self.timings.launchTiming = self._map.turn % self.timings.cycleTurns
- # else:
self.info("Found-no-moves-gather found no move, random expansion move?")
if self.expansion_plan and self.expansion_plan.selected_option:
for opt in self.expansion_plan.all_paths:
@@ -1674,702 +1407,6 @@ class EklipZBot(object):
return None
- # DONE STEP2: Move to BotModules/BotStateQueries.py late in the migration, or leave as a thin shell helper. Tiny derived-state query used everywhere; defer moving until larger modules stabilize.
- def is_all_in(self):
- return BotStateQueries.is_all_in(self)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.should_kill. Small combat predicate for whether a visible enemy/city should be treated as a kill target.
- def should_kill(self, tile):
- return BotCombatOps.should_kill(self, tile)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.just_moved. Small combat/targeting delta predicate used by tactical kill logic.
- def just_moved(self, tile):
- return BotCombatOps.just_moved(self, tile)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.should_kill_path_move_half. Tactical combat heuristic for partial-path kill execution; migrate with kill-path logic.
- def should_kill_path_move_half(self, threatKill, additionalArmy=0):
- return BotCombatOps.should_kill_path_move_half(self, threatKill, additionalArmy)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.find_key_enemy_vision_tiles. Tactical target selection for enemy vision/retake pressure; belongs with combat utility heuristics.
- def find_key_enemy_vision_tiles(self):
- return BotCombatOps.find_key_enemy_vision_tiles(self)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.worth_path_kill. Core tactical evaluator deciding whether a computed kill path is strategically worth taking.
- def worth_path_kill(self, pathKill: Path, threatPath: Path, analysis=None, cutoffDistance=5):
- return BotCombatOps.worth_path_kill(self, pathKill, threatPath, analysis, cutoffDistance)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.kill_army. Army-targeted tactical kill wrapper that builds/filters kill paths for tracked armies.
- def kill_army(
- self,
- army: Army,
- allowGeneral=False,
- allowWorthPathKillCheck=True
- ):
- return BotCombatOps.kill_army(self, army, allowGeneral, allowWorthPathKillCheck)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.kill_enemy_path. Thin wrapper into multi-path kill logic; migrate with the rest of the kill-path combat helpers.
- def kill_enemy_path(self, threatPath: Path, allowGeneral=False) -> Path | None:
- return BotCombatOps.kill_enemy_path(self, threatPath, allowGeneral)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.kill_enemy_paths. Main tactical kill-path construction logic over one or more threat paths; keep as a single intact combat cluster.
- def kill_enemy_paths(self, threatPaths: typing.List[Path], allowGeneral=False) -> Path | None:
- return BotCombatOps.kill_enemy_paths(self, threatPaths, allowGeneral)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.kill_threat. Tiny threat wrapper over kill_enemy_path; migrate with combat kill helpers.
- def kill_threat(self, threat: ThreatObj, allowGeneral=False):
- return BotCombatOps.kill_threat(self, threat, allowGeneral)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_gather_to_target_tile. Thin single-target adapter over the generic gather helper; keep with gather helper cluster.
- def get_gather_to_target_tile(
- self,
- target: Tile,
- maxTime: float,
- gatherTurns: int,
- negativeSet: typing.Set[Tile] | None = None,
- targetArmy: int = -1,
- useTrueValueGathered=False,
- includeGatherTreeNodesThatGatherNegative=False,
- maximizeArmyGatheredPerTurn: bool = False
- ) -> typing.Tuple[Move | None, int, int, typing.Union[None, typing.List[GatherTreeNode]]]:
- return BotGatherOps.get_gather_to_target_tile(
- self,
- target,
- maxTime,
- gatherTurns,
- negativeSet,
- targetArmy,
- useTrueValueGathered,
- includeGatherTreeNodesThatGatherNegative,
- maximizeArmyGatheredPerTurn)
-
- # set useTrueValueGathered to True for things like defense gathers,
- # where you want to take into account army lost gathering over enemy or neutral tiles etc.
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_defensive_gather_to_target_tiles. Defensive gather planner using targetArmy/priority adjustments; belongs in the gather module.
- def get_defensive_gather_to_target_tiles(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet=None,
- targetArmy=-1,
- useTrueValueGathered=False,
- leafMoveSelectionValueFunc=None,
- includeGatherTreeNodesThatGatherNegative=False,
- maximizeArmyGatheredPerTurn: bool = False,
- additionalIncrement: int = 0,
- distPriorityMap: MapMatrix[int] | None = None,
- priorityMatrix: MapMatrixInterface[float] | None = None,
- skipTiles: TileSet | None = None,
- shouldLog: bool = False,
- fastMode: bool = False
- ) -> typing.Tuple[Move | None, int, int, typing.Union[None, typing.List[GatherTreeNode]]]:
- return BotGatherOps.get_defensive_gather_to_target_tiles(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet,
- targetArmy,
- useTrueValueGathered,
- leafMoveSelectionValueFunc,
- includeGatherTreeNodesThatGatherNegative,
- maximizeArmyGatheredPerTurn,
- additionalIncrement,
- distPriorityMap,
- priorityMatrix,
- skipTiles,
- shouldLog,
- fastMode)
-
- # set useTrueValueGathered to True for things like defense gathers,
- # where you want to take into account army lost gathering over enemy or neutral tiles etc.
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_gather_to_target_tiles. Main generic gather planner with PCST/old-MST/max-set/knapsack branches; migrate intact to avoid behavior drift.
- def get_gather_to_target_tiles(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet=None,
- targetArmy=-1,
- useTrueValueGathered=False,
- leafMoveSelectionValueFunc=None,
- includeGatherTreeNodesThatGatherNegative=False,
- maximizeArmyGatheredPerTurn: bool = False,
- additionalIncrement: int = 0,
- distPriorityMap: MapMatrix[int] | None = None,
- priorityMatrix: MapMatrixInterface[float] | None = None,
- skipTiles: TileSet | None = None,
- shouldLog: bool = False,
- fastMode: bool = False
- ) -> typing.Tuple[Move | None, int, int, typing.Union[None, typing.List[GatherTreeNode]]]:
- return BotGatherOps.get_gather_to_target_tiles(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet,
- targetArmy,
- useTrueValueGathered,
- leafMoveSelectionValueFunc,
- includeGatherTreeNodesThatGatherNegative,
- maximizeArmyGatheredPerTurn,
- additionalIncrement,
- distPriorityMap,
- priorityMatrix,
- skipTiles,
- shouldLog,
- fastMode)
-
- # set useTrueValueGathered to True for things like defense gathers,
- # where you want to take into account army lost gathering over enemy or neutral tiles etc.
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_gather_to_target_tiles_greedy. Greedy fallback gather variant; keep with the rest of the gather planning surface.
- def get_gather_to_target_tiles_greedy(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet=None,
- targetArmy=-1,
- useTrueValueGathered=False,
- priorityFunc=None,
- valueFunc=None,
- includeGatherTreeNodesThatGatherNegative=False,
- maximizeArmyGatheredPerTurn: bool = False,
- shouldLog: bool = False
- ) -> typing.Tuple[Move | None, int, int, typing.Union[None, typing.List[GatherTreeNode]]]:
- return BotGatherOps.get_gather_to_target_tiles_greedy(
- self,
- targets,
- maxTime,
- gatherTurns,
- negativeSet,
- targetArmy,
- useTrueValueGathered,
- priorityFunc,
- valueFunc,
- includeGatherTreeNodesThatGatherNegative,
- maximizeArmyGatheredPerTurn,
- shouldLog)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.sum_enemy_army_near_tile. Local tactical enemy-pressure query used by combat/city logic.
- def sum_enemy_army_near_tile(self, startTile: Tile, distance: int = 2) -> int:
- return BotCombatOps.sum_enemy_army_near_tile(self, startTile, distance)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.count_enemy_territory_near_tile. Tactical territory-pressure query used by combat/city heuristics.
- def count_enemy_territory_near_tile(self, startTile: Tile, distance: int = 2) -> int:
- return BotCombatOps.count_enemy_territory_near_tile(self, startTile, distance)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.count_enemy_tiles_near_tile. Small tactical proximity count helper used by combat heuristics.
- def count_enemy_tiles_near_tile(self, startTile: Tile, distance: int = 2) -> int:
- return BotCombatOps.count_enemy_tiles_near_tile(self, startTile, distance)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.sum_player_army_near_tile. Local army-pressure helper for arbitrary player proximity calculations.
- def sum_player_army_near_tile(self, tile: Tile, distance: int = 2, player: int | None = None) -> int:
- return BotCombatOps.sum_player_army_near_tile(self, tile, distance, player)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.sum_player_standing_army_near_or_on_tiles. Shared low-level army aggregation helper used by defense/combat heuristics.
- def sum_player_standing_army_near_or_on_tiles(self, tiles: typing.List[Tile], distance: int = 2, player: int | None = None) -> int:
- return BotCombatOps.sum_player_standing_army_near_or_on_tiles(self, tiles, distance, player)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.sum_friendly_army_near_tile. Friendly-team variant of the local army proximity helper.
- def sum_friendly_army_near_tile(self, tile: Tile, distance: int = 2, player: int | None = None) -> int:
- return BotCombatOps.sum_friendly_army_near_tile(self, tile, distance, player)
-
- # DONE STEP2: Move to BotModules/BotCombatOps.py as BotCombatOps.sum_friendly_army_near_or_on_tiles. Shared team-aware army aggregation helper used in economy-defense and tactical checks.
- def sum_friendly_army_near_or_on_tiles(self, tiles: typing.List[Tile], distance: int = 2, player: int | None = None) -> int:
- return BotCombatOps.sum_friendly_army_near_or_on_tiles(self, tiles, distance, player)
-
- # DONE STEP2: Move to BotModules/BotPathingUtils.py as BotPathingUtils.get_first_path_move. Extremely small convenience wrapper that is broadly referenced.
- def get_first_path_move(self, path: TilePlanInterface):
- return BotPathingUtils.get_first_path_move(self, path)
-
- # DONE STEP2: Move to BotModules/BotTargeting.py as BotTargeting.get_afk_players. Cached opponent-state classification helper used for targeting/behavior decisions.
- def get_afk_players(self) -> typing.List[Player]:
- return BotTargeting.get_afk_players(self)
-
- # DONE STEP2: Move to BotModules/BotExpansionOps.py as BotExpansionOps.get_optimal_exploration. Main exploration path planner using watchman routing and target reveal heuristics; keep intact with exploration logic.
- def get_optimal_exploration(
- self,
- turns,
- negativeTiles: typing.Set[Tile] = None,
- valueFunc=None,
- priorityFunc=None,
- initFunc=None,
- skipFunc=None,
- minArmy=0,
- maxTime: float | None = None,
- emergenceRatio: float = 0.15,
- includeCities: bool | None = None,
- ) -> Path | None:
- return BotExpansionOps.get_optimal_exploration(self, turns, negativeTiles, valueFunc, priorityFunc, initFunc, skipFunc, minArmy, maxTime, emergenceRatio, includeCities)
-
- # allow exploration again
- #
- # negMinArmy = 0 - minArmy
- #
- # logbook.info(f"\n\nAttempting Optimal EXPLORATION (tm) for turns {turns}:\n")
- # startTime = time.perf_counter()
- # generalPlayer = self._map.players[self.general.player]
- # searchingPlayer = self.general.player
- # if negativeTiles is None:
- # negativeTiles = set()
- # else:
- # negativeTiles = negativeTiles.copy()
- # logbook.info(f"negativeTiles: {str(negativeTiles)}")
- #
- # distSource = self.general
- # if self.target_player_gather_path is not None:
- # distSource = self.targetPlayerExpectedGeneralLocation
- # distMap = self._map.distance_mapper.get_tile_dist_matrix(distSource)
- #
- # ourArmies = SearchUtils.where(self.armyTracker.armies.values(), lambda army: army.player == self.general.player and army.tile.player == self.general.player and army.tile.army > 1)
- # ourArmyTiles = [army.tile for army in ourArmies]
- # if len(ourArmyTiles) == 0:
- # logbook.info("We didn't have any armies to use to optimal_exploration. Using our tiles with army > 5 instead.")
- # ourArmyTiles = SearchUtils.where(self._map.players[self.general.player].tiles, lambda tile: tile.army > 5)
- # if len(ourArmyTiles) == 0:
- # logbook.info("We didn't have any armies to use to optimal_exploration. Using our tiles with army > 2 instead.")
- # ourArmyTiles = SearchUtils.where(self._map.players[self.general.player].tiles, lambda tile: tile.army > 2)
- # if len(ourArmyTiles) == 0:
- # logbook.info("We didn't have any armies to use to optimal_exploration. Using our tiles with army > 1 instead.")
- # ourArmyTiles = SearchUtils.where(self._map.players[self.general.player].tiles, lambda tile: tile.army > 1)
- #
- # ourArmyTiles = SearchUtils.where(ourArmyTiles, lambda t: t.army > negMinArmy)
- #
- # # require any exploration path go through at least one of these tiles.
- # validExplorationTiles = MapMatrixSet(self._map)
- # for tile in self._map.pathableTiles:
- # if (
- # not tile.discovered
- # and (self.territories.territoryMap[tile] == self.targetPlayer or distMap[tile] < 6)
- # ):
- # validExplorationTiles.add(tile)
- #
- # # skipFunc(next, nextVal). Not sure why this is 0 instead of 1, but 1 breaks it. I guess the 1 is already subtracted
- # if not skipFunc:
- # def skip_after_out_of_army(nextTile, nextVal):
- # wastedMoves, pathPriorityDivided, negArmyRemaining, negValidExplorationCount, negRevealedCount, enemyTiles, neutralTiles, pathPriority, distSoFar, tileSetSoFar, revealedSoFar = nextVal
- # if negArmyRemaining >= negMinArmy:
- # return True
- # if distSoFar > 6 and negValidExplorationCount == 0:
- # return True
- # if wastedMoves > 3:
- # return True
- # return False
- #
- # skipFunc = skip_after_out_of_army
- #
- # if not valueFunc:
- # def value_priority_army_dist(currentTile, priorityObject):
- # wastedMoves, pathPriorityDivided, negArmyRemaining, negValidExplorationCount, negRevealedCount, enemyTiles, neutralTiles, pathPriority, distSoFar, tileSetSoFar, revealedSoFar = priorityObject
- # # negative these back to positive
- # if negValidExplorationCount == 0:
- # return None
- # if negArmyRemaining > 0:
- # return None
- #
- # posPathPrio = 0 - pathPriorityDivided
- #
- # # pathPriority includes emergence values.
- # value = 0 - (negRevealedCount + enemyTiles * 6 + neutralTiles) / distSoFar
- #
- # return value, posPathPrio, distSoFar
- #
- # valueFunc = value_priority_army_dist
- #
- # if not priorityFunc:
- # def default_priority_func(nextTile, currentPriorityObject):
- # wastedMoves, pathPriorityDivided, negArmyRemaining, negValidExplorationCount, negRevealedCount, enemyTiles, neutralTiles, pathPriority, distSoFar, tileSetSoFar, revealedSoFar = currentPriorityObject
- # armyRemaining = 0 - negArmyRemaining
- # nextTileSet = tileSetSoFar.copy()
- # distSoFar += 1
- # # weight tiles closer to the target player higher
- # addedPriority = -4 - max(2.0, distMap[nextTile] / 3)
- # # addedPriority = -7 - max(3, distMap[nextTile] / 4)
- # if nextTile not in nextTileSet:
- # armyRemaining -= 1
- # releventAdjacents = SearchUtils.where(nextTile.adjacents, lambda adjTile: adjTile not in revealedSoFar and adjTile not in tileSetSoFar)
- # revealedCount = SearchUtils.count(releventAdjacents, lambda adjTile: not adjTile.discovered)
- # negRevealedCount -= revealedCount
- # if negativeTiles is None or (nextTile not in negativeTiles):
- # if searchingPlayer == nextTile.player:
- # armyRemaining += nextTile.army
- # else:
- # armyRemaining -= nextTile.army
- # if nextTile in validExplorationTiles:
- # negValidExplorationCount -= 1
- # addedPriority += 3
- # nextTileSet.add(nextTile)
- # # enemytiles or enemyterritory undiscovered tiles
- # if self.targetPlayer != -1 and (nextTile.player == self.targetPlayer or (not nextTile.visible and self.territories.territoryMap[nextTile] == self.targetPlayer)):
- # if nextTile.player == -1:
- # # these are usually 2 or more army since usually after army bonus
- # armyRemaining -= 2
- # # # points for maybe capping target tiles
- # # addedPriority += 4
- # # enemyTiles -= 0.5
- # # neutralTiles -= 0.5
- # # # treat this tile as if it is at least 1 cost
- # # else:
- # # # points for capping target tiles
- # # addedPriority += 6
- # # enemyTiles -= 1
- # addedPriority += 8
- # enemyTiles -= 1
- # ## points for locking all nearby enemy tiles down
- # # numEnemyNear = SearchUtils.count(nextTile.adjacents, lambda adjTile: adjTile.player == self.player)
- # # numEnemyLocked = SearchUtils.count(releventAdjacents, lambda adjTile: adjTile.player == self.player)
- # ## for every other nearby enemy tile on the path that we've already included in the path, add some priority
- # # addedPriority += (numEnemyNear - numEnemyLocked) * 12
- # elif nextTile.player == -1:
- # # we'd prefer to be killing enemy tiles, yeah?
- # wastedMoves += 0.2
- # neutralTiles -= 1
- # # points for capping tiles in general
- # addedPriority += 1
- # # points for taking neutrals next to enemy tiles
- # numEnemyNear = SearchUtils.count(nextTile.movable, lambda adjTile: adjTile not in revealedSoFar and adjTile.player == self.targetPlayer)
- # if numEnemyNear > 0:
- # addedPriority += 1
- # else: # our tiles and non-target enemy tiles get negatively weighted
- # # addedPriority -= 2
- # # 0.7
- # wastedMoves += 1
- # # points for discovering new tiles
- # addedPriority += revealedCount * 2
- # if self.armyTracker.emergenceLocationMap[self.targetPlayer][nextTile] > 0 and not nextTile.visible:
- # addedPriority += (self.armyTracker.emergenceLocationMap[self.targetPlayer][nextTile] ** 0.5)
- # ## points for revealing tiles in the fog
- # # addedPriority += SearchUtils.count(releventAdjacents, lambda adjTile: not adjTile.visible)
- # else:
- # wastedMoves += 1
- #
- # nextRevealedSet = revealedSoFar.copy()
- # for adj in SearchUtils.where(nextTile.adjacents, lambda tile: not tile.discovered):
- # nextRevealedSet.add(adj)
- # newPathPriority = pathPriority - addedPriority
- # # if generalPlayer.tileCount < 46:
- # # logbook.info("nextTile {}, newPathPriority / distSoFar {:.2f}, armyRemaining {}, newPathPriority {}, distSoFar {}, len(nextTileSet) {}".format(nextTile.toString(), newPathPriority / distSoFar, armyRemaining, newPathPriority, distSoFar, len(nextTileSet)))
- # return wastedMoves, newPathPriority / distSoFar, 0 - armyRemaining, negValidExplorationCount, negRevealedCount, enemyTiles, neutralTiles, newPathPriority, distSoFar, nextTileSet, nextRevealedSet
- #
- # priorityFunc = default_priority_func
- #
- # if not initFunc:
- # def initial_value_func_default(t: Tile):
- # startingSet = set()
- # startingSet.add(t)
- # startingAdjSet = set()
- # for adj in t.adjacents:
- # startingAdjSet.add(adj)
- # return 0, 10, 0 - t.army, 0, 0, 0, 0, 0, 0, startingSet, startingAdjSet
- #
- # initFunc = initial_value_func_default
- #
- # if turns <= 0:
- # logbook.info("turns <= 0 in optimal_exploration? Setting to 50")
- # turns = 50
- # remainingTurns = turns
- # sortedTiles = sorted(ourArmyTiles, key=lambda t: t.army, reverse=True)
- # paths = []
- #
- # player = self._map.players[self.general.player]
- # logStuff = False
- #
- # # BACKPACK THIS EXPANSION! Don't stop at remainingTurns 0... just keep finding paths until out of time, then knapsack them
- #
- # # Switch this up to use more tiles at the start, just removing the first tile in each path at a time. Maybe this will let us find more 'maximal' paths?
- #
- # while sortedTiles:
- # timeUsed = time.perf_counter() - startTime
- # # Stages:
- # # first 0.1s, use large tiles and shift smaller. (do nothing)
- # # second 0.1s, use all tiles (to make sure our small tiles are included)
- # # third 0.1s - knapsack optimal stuff outside this loop i guess?
- # if timeUsed > 0.03:
- # logbook.info(f"timeUsed {timeUsed:.3f} > 0.03... Breaking loop and knapsacking...")
- # break
- #
- # # startIdx = max(0, ((cutoffFactor - 1) * len(sortedTiles))//fullCutoff)
- #
- # # hack, see what happens TODO
- # # tilesLargerThanAverage = SearchUtils.where(generalPlayer.tiles, lambda tile: tile.army > 1)
- # # logbook.info("Filtered for tilesLargerThanAverage with army > {}, found {} of them".format(tilePercentile[-1].army, len(tilesLargerThanAverage)))
- # startDict = {}
- # for i, tile in enumerate(sortedTiles):
- # # skip tiles we've already used or intentionally ignored
- # if tile in negativeTiles:
- # continue
- # # self.mark_tile(tile, 10)
- #
- # initVal = initFunc(tile)
- # # wastedMoves, pathPriorityDivided, armyRemaining, pathPriority, distSoFar, tileSetSoFar
- # # 10 because it puts the tile above any other first move tile, so it gets explored at least 1 deep...
- # startDict[tile] = (initVal, 0)
- # path, pathValue = SearchUtils.breadth_first_dynamic_max(
- # self._map,
- # startDict,
- # valueFunc,
- # 0.025,
- # remainingTurns,
- # turns,
- # noNeutralCities=True,
- # negativeTiles=negativeTiles,
- # searchingPlayer=self.general.player,
- # priorityFunc=priorityFunc,
- # useGlobalVisitedSet=False,
- # skipFunc=skipFunc,
- # logResultValues=logStuff,
- # includePathValue=True)
- #
- # if path:
- # (pathPriorityPerTurn, posPathPrio, distSoFar) = pathValue
- # logbook.info(f"Path found for maximizing army usage? Duration {time.perf_counter() - startTime:.3f} path {path.toString()}")
- # node = path.start
- # # BYPASSED THIS BECAUSE KNAPSACK...
- # # remainingTurns -= path.length
- # tilesGrabbed = 0
- # visited = set()
- # friendlyCityCount = 0
- # while node is not None:
- # negativeTiles.add(node.tile)
- #
- # if self._map.is_tile_friendly(node.tile) and (node.tile.isCity or node.tile.isGeneral):
- # friendlyCityCount += 1
- # # this tile is now worth nothing because we already intend to use it ?
- # # skipTiles.add(node.tile)
- # node = node.next
- # sortedTiles.remove(path.start.tile)
- # paths.append((friendlyCityCount, pathPriorityPerTurn, path))
- # else:
- # logbook.info("Didn't find a super duper cool optimized EXPLORATION pathy thing. Breaking :(")
- # break
- #
- # alpha = 75
- # minAlpha = 50
- # alphaDec = 2
- # trimmable = {}
- #
- # # build knapsack weights and values
- # weights = [pathTuple[2].length for pathTuple in paths]
- # values = [int(100 * pathTuple[1]) for pathTuple in paths]
- # logbook.info(f"Feeding the following paths into knapsackSolver at turns {turns}...")
- # for i, pathTuple in enumerate(paths):
- # friendlyCityCount, pathPriorityPerTurn, curPath = pathTuple
- # logbook.info(f"{i}: cities {friendlyCityCount} pathPriorityPerTurn {pathPriorityPerTurn} length {curPath.length} path {curPath.toString()}")
- #
- # totalValue, maxKnapsackedPaths = solve_knapsack(paths, turns, weights, values)
- # logbook.info(f"maxKnapsackedPaths value {totalValue} length {len(maxKnapsackedPaths)},")
- #
- # path = None
- # if len(maxKnapsackedPaths) > 0:
- # maxVal = (-100, -1)
- #
- # # Select which of the knapsack paths to move first
- # for pathTuple in maxKnapsackedPaths:
- # friendlyCityCount, tilesCaptured, curPath = pathTuple
- #
- # thisVal = (0 - friendlyCityCount, tilesCaptured / curPath.length)
- # if thisVal > maxVal:
- # maxVal = thisVal
- # path = curPath
- # logbook.info(f"no way this works, evaluation [{'], ['.join(str(x) for x in maxVal)}], path {path.toString()}")
- #
- # # draw other paths darker
- # alpha = 150
- # minAlpha = 150
- # alphaDec = 0
- # self.viewInfo.color_path(PathColorer(curPath, 50, 51, 204, alpha, alphaDec, minAlpha))
- # logbook.info(f"EXPLORATION PLANNED HOLY SHIT? Duration {time.perf_counter() - startTime:.3f}, path {path.toString()}")
- # # draw maximal path darker
- # alpha = 255
- # minAlpha = 200
- # alphaDec = 0
- # self.viewInfo.paths = deque(SearchUtils.where(self.viewInfo.paths, lambda pathCol: pathCol.path != path))
- # self.viewInfo.color_path(PathColorer(path, 55, 100, 200, alpha, alphaDec, minAlpha))
- # else:
- # logbook.info(f"No EXPLORATION plan.... :( Duration {time.perf_counter() - startTime:.3f},")
- #
- # return path
-
- # DONE STEP2: Move to BotModules/BotExpansionOps.py as BotExpansionOps.explore_target_player_undiscovered. Higher-level exploration decision logic around whether/when to run exploration and accept a reveal path.
- def explore_target_player_undiscovered(self, negativeTiles: typing.Set[Tile] | None, onlyHuntGeneral: bool | None = None, maxTime: float | None = None) -> Path | None:
- return BotExpansionOps.explore_target_player_undiscovered(self, negativeTiles, onlyHuntGeneral, maxTime)
-
- ## don't explore to 1 army from inside our own territory
- ##if not self.timings.in_gather_split(self._map.turn):
- # if skipTiles is None:
- # skipTiles = set()
- # skipTiles = skipTiles.copy()
- # for tile in genPlayer.tiles:
- # if self.territories.territoryMap[tile] == self.general.player:
- # logbook.info("explore: adding tile {} to skipTiles for lowArmy search".format(tile.toString()))
- # skipTiles.add(tile)
-
- # path = SearchUtils.breadth_first_dynamic(self._map,
- # enemyUndiscBordered,
- # goal_func_short,
- # 0.1,
- # 3,
- # noNeutralCities = True,
- # skipTiles = skipTiles,
- # searchingPlayer = self.general.player,
- # priorityFunc = priority_func_non_all_in)
- # if path is not None:
- # path = path.get_reversed()
- # self.info("UD SMALL: depth {} bfd kill (pre-prune) \n{}".format(path.length, path.toString()))
-
- # DONE STEP2: Move to BotModules/BotTargeting.py as BotTargeting.get_median_tile_value. Small targeting/heuristic utility over player tile-army distribution.
- def get_median_tile_value(self, percentagePoint=50, player: int = -1):
- return BotTargeting.get_median_tile_value(self, percentagePoint, player)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.build_mst. Core legacy MST gather/path builder used by multiple gather routines; migrate intact to the gather module.
- def build_mst(self, startTiles, maxTime=0.1, maxDepth=150, negativeTiles: typing.Set[Tile] = None, avoidTiles=None, priorityFunc=None):
- return BotGatherOps.build_mst(self, startTiles, maxTime, maxDepth, negativeTiles, avoidTiles, priorityFunc)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.build_mst_rebuild. Rebuild phase for the legacy MST gather structure; keep adjacent to build_mst.
- def build_mst_rebuild(self, startTiles, fromMap, searchingPlayer):
- return BotGatherOps.build_mst_rebuild(self, startTiles, fromMap, searchingPlayer)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_gather_mst. Recursive gather-tree reconstruction helper used only by the MST gather pipeline.
- def get_gather_mst(self, tile, fromTile, fromMap, turn, searchingPlayer):
- return BotGatherOps.get_gather_mst(self, tile, fromTile, fromMap, turn, searchingPlayer)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_tree_move_non_city_leaf_count. Gather-tree scoring helper used to evaluate leaf/city composition.
- def get_tree_move_non_city_leaf_count(self, gathers):
- return BotGatherOps.get_tree_move_non_city_leaf_count(self, gathers)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps._get_tree_move_non_city_leaf_count_recurse. Internal recursive helper for gather-tree leaf counting; keep adjacent to its caller.
- def _get_tree_move_non_city_leaf_count_recurse(self, gather):
- return BotGatherOps._get_tree_move_non_city_leaf_count_recurse(self, gather)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps._get_tree_move_default_value_func. Default gather-tree move valuation factory; core gather module helper.
- def _get_tree_move_default_value_func(self) -> typing.Callable[[Tile, typing.Tuple], typing.Tuple | None]:
- return BotGatherOps._get_tree_move_default_value_func(self)
-
- # DONE STEP2: Move to BotModules/BotGatherOps.py as BotGatherOps.get_tree_move_default. Central gather-tree-to-move selector used throughout gather/city/defense flows.
- def get_tree_move_default(
- self,
- gathers: typing.List[GatherTreeNode],
- valueFunc: typing.Callable[[Tile, typing.Tuple], typing.Tuple | None] | None = None,
- pop: bool = False
- ) -> Move | None:
- return BotGatherOps.get_tree_move_default(self, gathers, valueFunc, pop)
-
- # DONE STEP2: Move to BotModules/BotDefense.py as BotDefense.get_threat_killer_move. Threat-specific defensive kill attempt helper; belongs with threat response logic.
- def get_threat_killer_move(self, threat: ThreatObj, searchTurns, negativeTiles) -> Move | None:
- return BotDefense.get_threat_killer_move(self, threat, searchTurns, negativeTiles)
-
- # DONE STEP2: Move to BotModules/BotCityOps.py as BotCityOps.should_proactively_take_cities. City-capture policy gate deciding when proactive neutral-city taking is strategically allowed.
- def should_proactively_take_cities(self):
- return BotCityOps.should_proactively_take_cities(self)
-
- # DONE STEP2: Move to BotModules/BotCityOps.py as BotCityOps.capture_cities. Main city-capture orchestrator covering neutral/enemy city selection, contestation, gather planning, and all-in-on-cities behavior.
- def capture_cities(
- self,
- negativeTiles: typing.Set[Tile],
- forceNeutralCapture: bool = False,
- ) -> typing.Tuple[Path | None, Move | None]:
- return BotCityOps.capture_cities(self, negativeTiles, forceNeutralCapture)
-
- # DONE STEP2: Move to BotModules/BotRendering.py as BotRendering.mark_tile. Pure view-info annotation helper; presentation-only.
- def mark_tile(self, tile, alpha=100):
- return BotRendering.mark_tile(self, tile, alpha)
-
- # DONE STEP2: Move to BotModules/BotCityOps.py as BotCityOps.find_neutral_city_path. Neutral-city candidate ranking and path selection logic; belongs in city operations.
- def find_neutral_city_path(self) -> Path | None:
- return BotCityOps.find_neutral_city_path(self)
-
- # DONE STEP2: Move to BotModules/BotTargeting.py as BotTargeting.find_enemy_city_path. Enemy-city candidate ranking and path selection logic; belongs in targeting.
- def find_enemy_city_path(self, negativeTiles: TileSet, force: bool = False) -> typing.Tuple[int, Path | None]:
- return BotTargeting.find_enemy_city_path(self, negativeTiles, force)
-