forked from harrischristiansen/generals-bot
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEarlyExpandUtils.py
More file actions
2495 lines (2125 loc) · 92.9 KB
/
EarlyExpandUtils.py
File metadata and controls
2495 lines (2125 loc) · 92.9 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
import random
from collections import deque
import logbook
import time
import typing
import Gather
import SearchUtils
from Models import Move, GatherTreeNode
from Interfaces import MapMatrixInterface, TileSet
from MapMatrix import MapMatrix, MapMatrixSet
from Path import Path
from SearchUtils import breadth_first_foreach, breadth_first_dynamic_max
from ViewInfo import ViewInfo, PathColorer
from base.client.map import MapBase, Tile
DEBUG_ASSERTS = False
ALLOW_RANDOM_SKIPS = False
EMPTY_COMBINATION = (0, 0, 0, 0)
# TODO alt approach
# Get all possible paths from general of length 5 (cant be that many, right?)
# Figure out which ones combine together to achieve the things we want and lead to tile islands with enough capturable material?
class CityExpansionPlan(object):
def __init__(self, tile_captures: int, plan_paths: typing.List[Path | None], launch_turn: int, core_tile: Tile):
self.core_tile: Tile = core_tile
self.tile_captures: int = tile_captures
self.launch_turn: int = launch_turn
if plan_paths is None:
plan_paths = []
self.plan_paths: typing.List[Path | None] = plan_paths
self.intended_deserts: typing.Set[Tile] = set()
for p in self.plan_paths:
if not p:
continue
for t in p.tileList:
if t.isDesert:
self.intended_deserts.add(t)
def get_start_expand_captures(
map: MapBase,
general: Tile,
generalArmy: int,
curTurn: int,
expandPaths: typing.List[Path | None],
alreadyOwned: typing.Set[Tile] | None = None,
launchTurn: int = -1,
noLog: bool = False
) -> int:
"""
Does NOT update the visitedSet.
Returns the number of NEW tiles captured that are not already owned.
None's represent waiting moves, paths represent path moves.
Include launchTurn to simplify the None BS.
@param map:
@param general:
@param generalArmy: General army ON current turn (not at launch turn)
@param curTurn:
@param expandPaths:
@param alreadyOwned:
@param launchTurn: if launchTurn is provided, the leading Nones will be ignored and we'll begin at launchTurn from the first non-None path (after incrementing general army from generalArmy at current turn).
@param noLog:
@return:
"""
if not expandPaths:
return 0
genPlayer = general.player
# logbook.info(f'running get_start_expand_value')
#
# if visitedSet is not None:
# tilesCapped: typing.Set[Tile] = {t for t in visitedSet if t.player == general.player}
# else:
alreadyVisited: typing.Set[Tile]
if alreadyOwned:
alreadyVisited = alreadyOwned.copy()
else:
alreadyVisited = set(map.players[genPlayer].tiles)
# alreadyVisited.add(general)
numCapped = 0
enCapped = set()
curGenArmy = generalArmy
pathIdx = 0
p = expandPaths[pathIdx]
if launchTurn != -1:
while p is None and pathIdx + 1 < len(expandPaths):
pathIdx += 1
p = expandPaths[pathIdx]
logbook.info(f'incrementing curTurn {curTurn} towards launchTurn {launchTurn}, dropped {pathIdx} Nones')
while curTurn < launchTurn:
curTurn += 1
if curTurn & 1 == 0:
curGenArmy += 1
curMoves: typing.List[Move] | None = None
if p is not None:
curMoves = p.get_move_list()
curMoveIdx = 0
movingArmy = 0
teamPlayers = map.get_teammates_no_self(genPlayer)
turn = curTurn
if not noLog:
logbook.info(f'get_start_expand_value turn {curTurn}, genArmy {generalArmy}, paths {len(expandPaths)}, alreadyVisited {len(alreadyVisited)} - {" | ".join([str(t) for t in sorted(alreadyVisited)])}')
while turn <= 50:
movingGen = False
pathComplete = False
if curMoves is None:
if not noLog:
logbook.info(f'{turn} ({curGenArmy}) - no-opped move')
pathIdx += 1
if pathIdx >= len(expandPaths):
break
pathComplete = True
movingArmy = 0
else:
move = curMoves[curMoveIdx]
if move.source == general:
movingArmy = curGenArmy
movingGen = True
elif move.dest.isGeneral and move.dest.player in teamPlayers:
raise AssertionError(f'Pathed into another general....? {move}')
curMoveIdx += 1
nextTile = move.dest
wasVisited = nextTile in alreadyVisited
alreadyVisited.add(nextTile)
if nextTile.isSwamp:
if turn % 2 == 0:
# we'll lose an extra army the turn we arrive
movingArmy -= 1
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) swamp (bad cycle)')
else:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) swamp (better cycle)')
# we'll lose the army we left behind, too
# movingArmy -= 1
elif wasVisited:
if not noLog:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) already capped')
elif nextTile.isDesert:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) desert')
movingArmy -= 1
elif nextTile.player == genPlayer:
movingArmy += nextTile.army
movingArmy -= 1
if not noLog:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) was our tile')
elif nextTile.player in teamPlayers:
movingArmy += nextTile.army
movingArmy -= 1
if not noLog:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) was ally tile')
else:
numCapped += 1
# TODO wait, we don't decrement this because we currently want to route THROUGH enemy tiles as if they werent there (?) I uncommented this for now to see what goes wrong.
movingArmy -= nextTile.army + 1
if nextTile.player >= 0:
enCapped.add(nextTile)
if not noLog:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) ({len(alreadyVisited)}) CAPPED EN')
elif not noLog:
logbook.info(f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) ({len(alreadyVisited)})')
if movingArmy <= 0 and DEBUG_ASSERTS and len(enCapped) == 0:
tileState = f'{turn} ({curGenArmy}) - {str(nextTile)} (a{movingArmy}) ({len(alreadyVisited)})'
if noLog:
logbook.error(tileState)
msg = '^^^^^^illegal plan, moved negative army^^^^^^'
logbook.error(msg)
raise AssertionError(f'{tileState}\r\n{msg}')
if curMoveIdx >= len(curMoves):
pathIdx += 1
if pathIdx >= len(expandPaths):
break
pathComplete = True
if movingArmy > 1 and turn < 50:
if not noLog:
logbook.info(f"Army not fully used. {movingArmy} army ended at {str(nextTile)}, turn {turn}. Should almost never see this in a final result...")
if pathComplete:
p = expandPaths[pathIdx]
curMoves = None
if p is not None:
curMoves = p.get_move_list()
curMoveIdx = 0
if movingGen:
curGenArmy = 1
if turn & 1 == 1:
curGenArmy += 1
turn += 1
if pathIdx < len(expandPaths) and map.turn < 25:
errorMsg = f'Plan incomplete at turn 50 (there were extra moves in the plan), pathIdx {pathIdx} with subsequent paths {", ".join([str(path) for path in expandPaths[pathIdx:]])}'
if DEBUG_ASSERTS:
raise AssertionError(errorMsg)
else:
logbook.error(errorMsg)
if not noLog:
logbook.info(
f'result of curTurn {curTurn}: newCapped {numCapped}, capped {len(alreadyVisited)}, enCapped {len(enCapped)}, final genArmy {curGenArmy}')
# return numCapped
return len(alreadyVisited)
def __evaluate_plan_value(
map: MapBase,
general: Tile,
general_army: int,
cur_turn: int,
path_list: typing.List[Path | None],
dist_to_gen_map: MapMatrixInterface[int],
tile_weight_map: MapMatrixInterface[int],
already_owned: typing.Set[Tile],
launch_turn: int = -1,
no_log: bool = False
) -> typing.Tuple[int, int, int, int]:
"""
@param map:
@param general:
@param general_army:
@param cur_turn:
@param path_list:
@param dist_to_gen_map:
@param tile_weight_map:
@param already_owned: Must be ONLY the players tiles, no ally tiles or skip tiles.
@param launch_turn: if set to something other than -1, Nones will be ignored at the start of the thingy
@param no_log:
@return:
"""
adjAvailable = SearchUtils.Counter(0)
planTileSet = set()
visibleTileSet = already_owned.copy()
for tile in already_owned:
# no points for stuff we can already see
visibleTileSet.update(tile.adjacents)
for path in path_list:
if path is not None:
visibleTileSet.update(path.tileList)
planTileSet.update(path.tileList)
tileWeightSum = 0
genDistSum = 0
visibilityValue = 0.0
for tile in planTileSet:
tileWeightSum += tile_weight_map[tile]
genDistSum += dist_to_gen_map[tile]
for adj in tile.adjacents:
if adj not in visibleTileSet:
visibleTileSet.add(adj)
if not adj.isObstacle:
# TODO the fuck is this 8 - *? We should straight up respect the tile_weight_map, not do janky math in here. If we expect to use this weighting, then we damn well should build the -8 into the weight map instead.
reward = 8 - tile_weight_map[adj]
if reward > 0:
visibilityValue += reward
def count_func(tile: Tile):
if (tile not in planTileSet
and tile not in already_owned
and not tile.isNotPathable
and not tile.isCity
and tile.player == -1
and tile.army == 0):
adjAvailable.value += 1
SearchUtils.breadth_first_foreach_fast_no_neut_cities(map, planTileSet, 3, count_func)
pathValue = get_start_expand_captures(map, general, general_army, cur_turn, path_list, alreadyOwned=already_owned, launchTurn=launch_turn, noLog=no_log)
# pathValue = len(already_owned) + get_start_expand_captures(map, general, general_army, cur_turn, path_list, alreadyOwned=already_owned, noLog=no_log)
return (
pathValue,
# adjAvailable.value,
adjAvailable.value + int(visibilityValue),
# int(visibilityValue.value),
0 - tileWeightSum,
genDistSum
)
def recalculate_max_plan(plan1: CityExpansionPlan, plan2: CityExpansionPlan, map: MapBase, distToGenMap, tile_weight_map, visited, no_log: bool = False) -> CityExpansionPlan:
launchVal1 = __evaluate_plan_value(
map,
plan1.core_tile,
plan1.core_tile.army,
map.turn,
plan1.plan_paths,
dist_to_gen_map=distToGenMap,
tile_weight_map=tile_weight_map,
already_owned=visited,
no_log=no_log)
plan1.tile_captures = launchVal1[0]
launchVal2 = __evaluate_plan_value(
map,
plan2.core_tile,
plan2.core_tile.army,
map.turn,
plan2.plan_paths,
dist_to_gen_map=distToGenMap,
tile_weight_map=tile_weight_map,
already_owned=visited,
no_log=no_log)
plan2.tile_captures = launchVal2[0]
if launchVal1 >= launchVal2:
return plan1
return plan2
def optimize_first_25(
map: MapBase,
general: Tile,
tile_minimization_map: MapMatrixInterface[float],
debug_view_info: typing.Union[None, ViewInfo] = None,
no_recurse: bool = False,
skipTiles: typing.Set[Tile] | None = None,
no_log=not DEBUG_ASSERTS,
cutoff_time: float | None = None,
prune_cutoff: int = -1,
cramped: bool = False,
shuffle_launches: bool = False
) -> CityExpansionPlan:
"""
@param map:
@param general:
@param tile_minimization_map: lower numbers = better
@param debug_view_info: the viewInfo to write debug data to (mainly for unit testing).
@param no_recurse: Used to prevent infinite recursion when optimizing with alt tile weights
@param skipTiles: Tiles that will be not counted for expansion
@param no_log: skip logging everything except the final result
@return:
"""
distToGenMap = map.distance_mapper.get_tile_dist_matrix(general)
if debug_view_info:
debug_view_info.bottomLeftGridText = distToGenMap
alreadyOwned: typing.Set[Tile] = {t for t in map.players[general.player].tiles if t.isCity or t.isGeneral or t.army <= 1}
#
# if skipTiles is not None:
# visited = skipTiles.copy()
# for player in map.players:
# if map.is_player_on_team_with(player.index, general.player):
# player = map.players[general.player]
# for tile in player.tiles:
# visited.add(tile)
mapTurnAtStart = map.turn
genArmyAtStart = general.army
maxResultPaths = None
maxVal = None
maxTiles = prune_cutoff
if prune_cutoff == -1:
if map.turn > 13:
# Get a preliminary no-wasted-moves result as our baseline
startTime = time.perf_counter()
genArmy = general.army
launchResult = _sub_optimize_remaining_cycle_expand_from_cities(
map,
general,
general.army,
distToGenMap,
tile_minimization_map,
turn=map.turn,
max_allow_wasted_moves=-20, # force no wasted moves for this attempt
debug_view_info=debug_view_info,
visited_set=alreadyOwned,
prune_below=maxTiles,
skip_tiles=skipTiles,
cutoff_time=0.01,
no_log=no_log)
launchVal = __evaluate_plan_value(map, general, genArmyAtStart, map.turn, launchResult, dist_to_gen_map=distToGenMap, tile_weight_map=tile_minimization_map, already_owned=alreadyOwned, no_log=no_log)
logbook.info(f'{genArmy} NO WASTED BASELINE launch ({launchVal}) in {time.perf_counter() - startTime:.4f}s')
maxVal = launchVal
maxResultPaths = launchResult
maxTiles = launchVal[0]
else:
prune_cutoff = 16
if cramped:
# genArmy, optimalMaxWasteMoves
combinationsWithMaxOptimal = [
None, # buys 11 more time
(11, 8),
(10, 10),
(13, 2),
None,
None, # buys 8 more time
(8, 10),
None, # buys 7 more time
(7, 14),
None,
None,
(9, 10),
# None,
# None,
(14, 0),
(15, 0),
# (12, 4),
# (13, 8),
]
else:
# genArmy, turn, optimalMaxWasteMoves
combinationsWithMaxOptimal = [
(13, 2), # most likely to find high value paths first
(11, 6),
(10, 8),
None, # buys 9 more time
(9, 10),
(12, 4),
(14, 0),
]
# 12-6-5-4-1
if shuffle_launches:
random.shuffle(combinationsWithMaxOptimal)
if len(alreadyOwned) > 1:
logbook.info(f'DUE TO NUM VISITED {len(alreadyOwned)}, USING NON-PRE-ARRANGED WASTED COUNTS')
return optimize_city_expand(alreadyOwned, cutoff_time, debug_view_info, distToGenMap, genArmyAtStart, general, map, mapTurnAtStart, no_log, prune_cutoff, shuffle_launches, skipTiles, tile_minimization_map)
timeLimit = 3.0
if cutoff_time:
timeLimit = cutoff_time - time.perf_counter()
cutoff_time = None
startTime = time.perf_counter()
i = 0
for comboTuple in combinationsWithMaxOptimal:
i += 1
if comboTuple is None:
continue
(genArmy, optimalWastedMoves) = comboTuple
launchTurn = (genArmy - 1) * 2
perCutoff = cutoff_time
if perCutoff is None:
if shuffle_launches:
perCutoff = startTime + timeLimit
else:
perCutoff = startTime + (timeLimit / len(combinationsWithMaxOptimal)) * i
if mapTurnAtStart > launchTurn:
continue
launchResult = _sub_optimize_remaining_cycle_expand_from_cities(
map,
general,
genArmy,
distToGenMap,
tile_minimization_map,
turn=launchTurn,
try_bi_directional_first_launch=True, # required to pass test_can_attempt_backwards_initial_paths_for_higher_land_count
max_allow_wasted_moves=optimalWastedMoves + 3,
debug_view_info=debug_view_info,
visited_set=alreadyOwned,
prune_below=maxTiles,
skip_tiles=skipTiles,
cutoff_time=perCutoff,
no_log=no_log)
for _ in range(mapTurnAtStart, launchTurn):
launchResult.insert(0, None)
launchVal = __evaluate_plan_value(map, general, genArmyAtStart, map.turn, launchResult, dist_to_gen_map=distToGenMap, tile_weight_map=tile_minimization_map, already_owned=alreadyOwned, no_log=no_log)
logbook.info(f'{genArmy} ({optimalWastedMoves}) launch ({launchVal}) {">>>" if maxVal is None or maxVal < launchVal else "<"} prev launches (prev max {maxVal})')
if maxVal is None or launchVal > maxVal:
maxVal = launchVal
maxResultPaths = launchResult
maxTiles = launchVal[0]
if genArmy <= 8:
# We need to early terminate if we're going to do a 7-plan
break
launchTurn = mapTurnAtStart
maxTiles = 0
if maxResultPaths is not None:
for path in maxResultPaths:
if path is not None:
break
launchTurn += 1
maxTiles = maxVal[0]
logbook.info(f'max launch result v')
val = get_start_expand_captures(map, general, general.army, mapTurnAtStart, maxResultPaths, alreadyOwned=alreadyOwned, noLog=False)
# val = len(alreadyOwned) + get_start_expand_captures(map, general, general.army, mapTurnAtStart, maxResultPaths, alreadyOwned=alreadyOwned, noLog=False)
logbook.info(f'max launch result {maxVal}, turn {launchTurn} ^')
if val != maxTiles:
raise AssertionError(f'maxTiles {maxTiles} did not match expand val {val}')
return CityExpansionPlan(maxTiles, maxResultPaths, launchTurn, general)
def optimize_city_expand(alreadyOwned, cutoff_time, debug_view_info, distToGenMap, genArmyAtStart, general, map, mapTurnAtStart, no_log, prune_cutoff, shuffle_launches, skipTiles, tile_minimization_map):
turnInCycle = mapTurnAtStart % 50
turnsLeft = 50 - turnInCycle
allowWasted = 3
if map.turn < 50:
# determine phase in launch cycle:
tileCount = len(map.players[general.player].tiles)
capsLeftForPerfect = 25 - tileCount
allowWasted = turnsLeft - capsLeftForPerfect
logbook.info(f'NON PRE ARRANGED F25: for turn {map.turn} with turns left {turnsLeft} and tileCount {tileCount}, capsLeftForPerfect was {capsLeftForPerfect}, so allowWasted was {allowWasted}')
else:
totalGenArmy = general.army + turnsLeft // 2
tileCount = len(map.players[general.player].tiles)
capsLeftForPerfect = totalGenArmy
allowWasted = max(3, turnsLeft - capsLeftForPerfect)
logbook.info(f'NON PRE ARRANGED LATE: for turn {map.turn} with turns left {turnsLeft} and tileCount {tileCount}, capsLeftForPerfect was {capsLeftForPerfect}, so allowWasted was {allowWasted}')
result = _sub_optimize_remaining_cycle_expand_from_cities(
map,
general,
genArmyAtStart,
distToGenMap,
tile_minimization_map,
turn=turnInCycle, # TODO is this +1 right...?
visited_set=alreadyOwned,
prune_below=prune_cutoff,
max_allow_wasted_moves=allowWasted,
shuffle_launches=shuffle_launches,
dont_force_first=True,
debug_view_info=debug_view_info,
try_bi_directional_first_launch=True,
skip_tiles=skipTiles,
cutoff_time=cutoff_time,
no_log=no_log)
val = get_start_expand_captures(map, general, genArmyAtStart, turnInCycle, result, alreadyOwned=alreadyOwned, noLog=False)
# val = len(alreadyOwned) + get_start_expand_captures(map, general, genArmyAtStart, turnInCycle, result, alreadyOwned=alreadyOwned, noLog=False)
return CityExpansionPlan(val, result, mapTurnAtStart, general)
def _sub_optimize_first_25_specific_wasted(
map: MapBase,
general: Tile,
gen_army: int,
dist_to_gen_map: MapMatrixInterface[int],
tile_weight_map: MapMatrixInterface[int],
turn: int,
force_wasted_moves: int,
allow_wasted_moves: int,
prune_below: int,
visited_set: typing.Set[Tile],
cutoff_time: float,
additional_one_level_skips: typing.Set[Tile] | None = None,
skip_tiles: typing.Set[Tile] = None,
shuffle_launches: bool = False,
dont_force_first: bool = False,
debug_view_info: typing.Union[None, ViewInfo] = None,
try_random_skips: bool = False,
no_log: bool = not DEBUG_ASSERTS
) -> typing.Tuple[typing.Tuple[int, int, int, int], typing.List[Path | None]]:
"""
@param map:
@param general:
@param gen_army:
@param dist_to_gen_map:
@param tile_weight_map:
@param turn:
@param force_wasted_moves: The amount of moves to force-waste on THIS segment. Must always be less than allow_wasted_moves.
@param allow_wasted_moves: The amount of wasted moves allowed overall for the remaining segments.
@param visited_set:
@param shuffle_launches: if set to True, will randomize launch combinations
@param dont_force_first: If true, will not force a segment at this exact timing and will instead test subsegments now and at the next general bonus turn.
@param debug_view_info:
@param no_log:
@return:
"""
pathList = []
curAttemptGenArmy = gen_army
curTurn = turn
capped = EMPTY_COMBINATION
if time.perf_counter() > cutoff_time:
return capped, pathList
visited_set = visited_set.copy()
if not dont_force_first:
if curAttemptGenArmy <= 1:
raise AssertionError(f'Someone ran a sub_optimize_specific_wasted with gen army 1 lol')
skipToUse = skip_tiles
if additional_one_level_skips:
skipToUse = skip_tiles.union(additional_one_level_skips) if skip_tiles else additional_one_level_skips
path1 = _optimize_25_launch_segment(
map,
general,
curAttemptGenArmy,
50 - curTurn,
dist_to_gen_map,
force_wasted_moves=force_wasted_moves,
tile_weight_map=tile_weight_map,
visited_set=visited_set,
skip_tiles=skipToUse,
debug_view_info=debug_view_info,
no_log=no_log)
if path1 is None:
if not no_log:
logbook.info(f'got none path for genArmy {curAttemptGenArmy} with allow_wasted {force_wasted_moves} (already visited {len(visited_set)})')
pathList.append(None)
return capped, pathList
capped = __evaluate_plan_value(map, general, curAttemptGenArmy, curTurn, [path1], dist_to_gen_map=dist_to_gen_map, tile_weight_map=tile_weight_map, already_owned=visited_set, no_log=no_log)
if capped[0] == 0:
pathList.append(None)
logbook.info(f'got 0 value path {str(path1)}, returning None instead')
return capped, pathList
if not no_log:
logbook.info(f'appending val {capped}, path {str(path1)}')
pathList.append(path1)
for tile in path1.tileList:
if tile in visited_set and tile != general:
allow_wasted_moves -= 1
visited_set.add(tile)
curAttemptGenArmy = 1
if not no_log:
logbook.info(f'path1.length {path1.length} ({str(path1)})')
for _ in range(path1.length):
curTurn += 1
if curTurn & 1 == 0:
curAttemptGenArmy += 1
if curTurn >= 50:
if not no_log:
logbook.info(f'curTurn {curTurn} >= 50, returning current path')
return capped, pathList
allow_wasted_moves = max(0, allow_wasted_moves)
# try immediate launch
if not no_log:
logbook.info(f'immediate, curTurn {curTurn}, genArmy {curAttemptGenArmy}')
maxOptimized = _sub_optimize_remaining_cycle_expand_from_cities(
map,
general,
curAttemptGenArmy,
dist_to_gen_map,
tile_weight_map,
curTurn,
allow_wasted_moves,
prune_below=prune_below,
cutoff_time=cutoff_time,
visited_set=visited_set,
skip_tiles=skip_tiles,
shuffle_launches=shuffle_launches,
try_random_skips=try_random_skips,
debug_view_info=debug_view_info,
no_log=no_log)
maxValue = __evaluate_plan_value(map, general, curAttemptGenArmy, curTurn, maxOptimized, dist_to_gen_map=dist_to_gen_map, tile_weight_map=tile_weight_map, already_owned=visited_set, no_log=no_log)
isSuboptimalLaunchTurn = curTurn & 1 == 1
# try one turn wait if turns remaining long enough
if curTurn <= 47:
curAttemptGenArmy += 1
curTurn += 1
allow_wasted_moves -= 1
if not isSuboptimalLaunchTurn:
curTurn += 1
allow_wasted_moves -= 1
if not no_log:
logbook.info(
f'withWait (double: {not isSuboptimalLaunchTurn}), curTurn {curTurn}, genArmy {curAttemptGenArmy}')
withOneWait = _sub_optimize_remaining_cycle_expand_from_cities(
map,
general,
curAttemptGenArmy,
dist_to_gen_map,
tile_weight_map,
curTurn,
allow_wasted_moves,
cutoff_time=cutoff_time,
prune_below=max(maxValue[0], prune_below),
visited_set=visited_set,
skip_tiles=skip_tiles,
shuffle_launches=shuffle_launches,
debug_view_info=debug_view_info,
no_log=no_log)
oneWaitVal = __evaluate_plan_value(map, general, curAttemptGenArmy, curTurn, withOneWait, dist_to_gen_map=dist_to_gen_map, tile_weight_map=tile_weight_map, already_owned=visited_set, no_log=no_log)
if oneWaitVal >= maxValue:
if not no_log:
logbook.info(
f'waiting (double: {not isSuboptimalLaunchTurn}) until {curTurn} resulted in better yield, {maxValue} vs {oneWaitVal}')
maxOptimized = withOneWait
maxValue = oneWaitVal
pathList.append(None)
if not isSuboptimalLaunchTurn:
pathList.append(None)
if maxValue[0] == 0:
if not no_log:
logbook.info('throwing out bad path')
return maxValue, [None]
for pathVal in maxOptimized:
pathList.append(pathVal)
return maxValue, pathList
def _sub_optimize_remaining_cycle_expand_from_cities(
map: MapBase,
general: Tile,
gen_army: int,
dist_to_gen_map: MapMatrixInterface[int],
tile_weight_map: MapMatrixInterface[int],
turn: int,
max_allow_wasted_moves: int,
prune_below: int,
cutoff_time: float,
visited_set: typing.Set[Tile] = None,
skip_tiles: typing.Set[Tile] = None,
shuffle_launches: bool = False,
dont_force_first: bool = False,
debug_view_info: typing.Union[None, ViewInfo] = None,
try_bi_directional_first_launch: bool = False,
try_random_skips: bool = False,
no_log: bool = not DEBUG_ASSERTS,
) -> typing.List[Path | None]:
"""
recursively optimize first 25
@param map:
@param general:
@param gen_army:
@param dist_to_gen_map: higher = better priority
@param tile_weight_map: lower = better priority
@param turn: turn launch is from (used to cap paths at turn 50)
@param max_allow_wasted_moves: number of tiles ALLOWED to be repeated / moves allowed to be wasted.
@param visited_set:
@param shuffle_launches: if set to True, will randomize launch combinations
@param dont_force_first:
@param debug_view_info:
@return:
"""
if not no_log:
logbook.info(f'sub-optimizing tile {general} - turn {turn} genArmy {gen_army}')
maxCombinationValue = EMPTY_COMBINATION
maxCombinationPathList = [None]
if visited_set is None or len(visited_set) == 0:
visited_set = set(map.players[general.player].tiles)
# visited_set = set()
# visited_set.add(general)
if skip_tiles is None and ALLOW_RANDOM_SKIPS:
skip_tiles = set()
turn = turn % 50
allowWastedMoves = max_allow_wasted_moves
skipMoveCount = 0
if not dont_force_first:
if gen_army == 1:
gen_army = 2
turn += 1
allowWastedMoves -= 1
skipMoveCount += 1
# if we didn't actually increment enough to get to the next gen army
if turn & 1 == 1:
turn += 1
allowWastedMoves -= 1
skipMoveCount += 1
turnsLeft = 50 - turn
if turnsLeft <= 0:
return []
minWastedMovesThisLaunch = max(0, allowWastedMoves // 2 - 2)
maxForce = allowWastedMoves + 4
# prevent maxForce from retraversing the whole launch path.
visitLen = len(visited_set)
if visitLen > 6 and maxForce > visitLen - 1:
maxForce = visitLen - 1
# # THIS IMPL ORDERS FROM MIN WASTED TO MAX WASTED
# forced = []
# for forceWasted in range(minWastedMovesThisLaunch, maxForce):
# bestCaseResult = len(visited_set) + turnsLeft - forceWasted
# if bestCaseResult < prune_below:
# if not no_log:
# logbook.info(f'pruning due to bestCaseResult {bestCaseResult} compared to prune_below {prune_below}')
# break
# forced.append(forceWasted)
# # END IMPL
# THIS IMPL ORDERS FROM CLOSEST TO 'allow_wasted_moves' TO FURTHEST RATHER THAN LEAST WASTED TO MOST, WHICH MAY BE PREFERABLE.
forced = []
# start low, move up into optimal allow wasted, and further up into max wasted stuff.
baseline = max(0, allowWastedMoves - 1)
# this prevents the bot from preferring paths that waste more moves than the initial launch.
if baseline > 5:
baseline = 5
curLess = baseline - 1
curMore = baseline
while True:
if curMore < maxForce:
forced.append(curMore)
curMore += 1
if curLess >= minWastedMovesThisLaunch:
forced.append(curLess)
curLess -= 1
elif curMore >= maxForce:
break
oldForced = forced
forced = []
for forceWasted in oldForced:
bestCaseResult = len(visited_set) + turnsLeft - forceWasted
if bestCaseResult < prune_below:
if not no_log:
logbook.info(f'pruning due to bestCaseResult {bestCaseResult} compared to prune_below {prune_below}')
continue
forced.append(forceWasted)
# END IMPL
if len(forced) == 0:
return maxCombinationPathList
if shuffle_launches:
random.shuffle(forced)
nextStart = time.perf_counter()
totalTime = cutoff_time - nextStart
timeEach = totalTime / len(forced)
divisions = 1
if try_bi_directional_first_launch:
divisions += 1
if ALLOW_RANDOM_SKIPS and try_random_skips:
divisions += 1
addlLevelsRandSkips = False
if try_random_skips and turnsLeft > 20:
addlLevelsRandSkips = True
timeEach = timeEach / divisions
# curTimeWeight = timeEach /
# we want to give more time to the most likely to succeed combinations...?
timeEach *= max(3, len(forced) - 5)
# if not shuffle_launches:
# # timeEachWeight = len(forced)
# # give more priority to the low waste attempts
# reduc = totalTime / (len(forced) * divisions + 4)
reduc = totalTime / (len(forced) * divisions + 4 * divisions)
minTimeEach = 0.003
for i, force_wasted_moves in enumerate(forced):
bestCaseResult = len(visited_set) + turnsLeft - force_wasted_moves
if bestCaseResult < prune_below:
if not no_log:
logbook.info(f'pruning due to bestCaseResult {bestCaseResult} compared to prune_below {prune_below}')
continue
if time.perf_counter() > cutoff_time:
if not no_log:
logbook.info(f'breaking early at force_wasted_moves {force_wasted_moves} (out of {forced})')
break
newCutoff = min(cutoff_time, nextStart + timeEach)
timeEach = max(minTimeEach, timeEach - reduc)
if not no_log:
logbook.info(f'timeEach reduced to {timeEach:.4f}')
value, pathList = _sub_optimize_first_25_specific_wasted(
map=map,
general=general,
gen_army=gen_army,
dist_to_gen_map=dist_to_gen_map,
tile_weight_map=tile_weight_map,
turn=turn,
force_wasted_moves=force_wasted_moves,
allow_wasted_moves=allowWastedMoves,
prune_below=prune_below,
visited_set=visited_set,
skip_tiles=skip_tiles,
shuffle_launches=shuffle_launches,
dont_force_first=dont_force_first,
try_random_skips=addlLevelsRandSkips,
debug_view_info=debug_view_info,
cutoff_time=newCutoff,
no_log=no_log
)
if value > maxCombinationValue:
maxCombinationValue = value
maxCombinationPathList = pathList
prune_below = max(prune_below, value[0])
nextStart = time.perf_counter()
if try_random_skips:
if len(pathList) > 1:
path = None
for p in pathList:
if p is None:
continue
path = p
break
if path is not None:
pathLen = path.length
if pathLen > 5:
newCutoff = min(cutoff_time, nextStart + timeEach)
timeEach = max(minTimeEach, timeEach - reduc)
if not no_log:
logbook.info(f'timeEach reduced to {timeEach:.4f}')
randomSkip = random.choice(path.tileList[1:min(pathLen - 1, 6)])
altValue, altPathList = _sub_optimize_first_25_specific_wasted(
map=map,
general=general,
gen_army=gen_army,
dist_to_gen_map=dist_to_gen_map,
tile_weight_map=tile_weight_map,
turn=turn,
force_wasted_moves=force_wasted_moves,
allow_wasted_moves=allowWastedMoves,
prune_below=prune_below,
visited_set=visited_set,
shuffle_launches=shuffle_launches,
skip_tiles=skip_tiles,
additional_one_level_skips={randomSkip},
dont_force_first=dont_force_first,
try_random_skips=addlLevelsRandSkips,
debug_view_info=debug_view_info,
cutoff_time=newCutoff,
no_log=no_log
)
nextStart = time.perf_counter()
if altValue > maxCombinationValue:
logbook.info(f'try_random_skips FOUND BETTER! {altValue} >>> {maxCombinationValue}')
maxCombinationValue = altValue
maxCombinationPathList = altPathList
prune_below = max(prune_below, altValue[0])
if try_bi_directional_first_launch:
if len(pathList) > 1:
path = None
for p in pathList:
if p is None:
continue
path = p
break
if path is not None:
skips = path.tileSet