forked from harrischristiansen/generals-bot
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSearchUtils.py
4964 lines (4257 loc) · 190 KB
/
SearchUtils.py
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
"""
@ Travis Drake (EklipZ) eklipz.io - tdrake0x45 at gmail)
April 2017
Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot
EklipZ bot - Tries to play generals lol
"""
import heapq
import types
from argparse import ArgumentError
from heapq import heappush, heappop
import logbook
import math
import typing
import time
from collections import deque
from heapq_max import heappush_max, heappop_max
import DebugHelper
# from numba import jit, float32, int64
from Interfaces import MapMatrixInterface, TileSet
from Path import Path
from math import inf as INF
from base.client.tile import Tile
from base.client.map import MapBase
from MapMatrix import MapMatrix, MapMatrixSet
BYPASS_TIMEOUTS_FOR_DEBUGGING = False
T = typing.TypeVar('T')
class HeapQueue(typing.Generic[T]):
"""Create a Heap Priority Queue object."""
def __init__(self):
self.queue: typing.List[T] = []
def __bool__(self):
return len(self.queue) > 0
def put(self, item: T):
"""Put an item into the queue."""
heappush(self.queue, item)
def get(self) -> T:
"""Remove and return an item from the queue."""
return heappop(self.queue)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
__class_getitem__ = classmethod(types.GenericAlias)
class HeapQueueMax(typing.Generic[T]):
"""
Create a Heap Priority Queue object.
Fastest way to empty check is
while myHeapQMax.queue:
...
Note the Min HeapQueue is much faster than this Max heapqueue.
With integers only:
20: HeapQueue 0.646 seconds (250000 runs of 20 pushes + pops)
100: HeapQueue 0.707 seconds (50000 runs of 100 pushes + pops)
500: HeapQueue 0.912 seconds (10000 runs of 500 pushes + pops)
2000: HeapQueue 1.034 seconds (2500 runs of 2000 pushes + pops)
20: HeapQueueMax 1.306 seconds (250000 runs of 20 pushes + pops)
100: HeapQueueMax 1.707 seconds (50000 runs of 100 pushes + pops)
500: HeapQueueMax 2.026 seconds (10000 runs of 500 pushes + pops)
2000: HeapQueueMax 2.411 seconds (2500 runs of 2000 pushes + pops)
With 5 pair tuple objects of bool, float, int, int, int:
20: HeapQueue 0.727 seconds (250000 runs of 20 pushes + pops)
100: HeapQueue 0.898 seconds (50000 runs of 100 pushes + pops)
500: HeapQueue 1.264 seconds (10000 runs of 500 pushes + pops)
2000: HeapQueue 1.551 seconds (2500 runs of 2000 pushes + pops)
20: HeapQueueMax 1.498 seconds (250000 runs of 20 pushes + pops)
100: HeapQueueMax 1.975 seconds (50000 runs of 100 pushes + pops)
500: HeapQueueMax 2.494 seconds (10000 runs of 500 pushes + pops)
2000: HeapQueueMax 3.026 seconds (2500 runs of 2000 pushes + pops)
"""
def __init__(self):
self.queue: typing.List[T] = []
def __bool__(self):
return len(self.queue) > 0
def put(self, item: T):
"""Put an item into the queue."""
heappush_max(self.queue, item)
def get(self) -> T:
"""Remove and return an item from the queue."""
return heappop_max(self.queue)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
__class_getitem__ = classmethod(types.GenericAlias)
class Counter(object):
def __init__(self, value):
self.value = value
def add(self, value):
self.value = self.value + value
def __repr__(self):
return str(self.value)
def __str__(self):
return str(self.value)
def where(enumerable: typing.Iterable[T], filter_func: typing.Callable[[T], bool]):
results = [item for item in enumerable if filter_func(item)]
return results
def any_where(enumerable: typing.Iterable[T], filter_func: typing.Callable[[T], bool]) -> bool:
for item in enumerable:
if filter_func(item):
return True
return False
def count(enumerable: typing.Iterable[T], filter_func: typing.Callable[[T], bool]) -> int:
countMatch = 0
for item in enumerable:
if filter_func(item):
countMatch += 1
return countMatch
def dest_breadth_first_target(
map: MapBase,
goalList: typing.Dict[Tile, typing.Tuple[int, int, float]] | typing.Iterable[Tile],
targetArmy=1,
maxTime=0.1,
maxDepth=20,
negativeTiles=None,
searchingPlayer=-2,
dontEvacCities=False,
dupeThreshold=3,
noNeutralCities=True,
skipTiles=None,
ignoreGoalArmy=False,
noLog=True,
additionalIncrement: float = 0.0,
preferCapture: bool = False
) -> Path | None:
"""
Gets a path that results in {targetArmy} army on one of the goalList tiles.
GoalList can be a dict that maps from start tile to (startDist, goalTargetArmy)
additionalIncrement can be set if for example capturing one of two nearby cities and you want to kill with enough to kill both.
Positive means gather EXTRA, negative means gather LESS.
"""
if searchingPlayer == -2:
searchingPlayer = map.player_index
if map.teammates and searchingPlayer == map.player_index:
if skipTiles:
skipTiles = set(t for t in skipTiles)
else:
skipTiles = set()
for tId in map.teammates:
if map.generals[tId] and map.generals[tId].isGeneral and map.generals[tId].player == tId:
skipTiles.add(map.generals[tId])
frontier = []
visited = MapMatrix(map, None)
if isinstance(goalList, dict):
for goal in goalList.keys():
(startDist, goalTargetArmy, goalIncModifier) = goalList[goal]
if goal.isMountain:
# logbook.info("BFS DEST SKIPPING MOUNTAIN {},{}".format(goal.x, goal.y))
continue
goalInc = goalIncModifier + additionalIncrement
# THE goalIncs below might be wrong, unit test.
if not map.is_player_on_team_with(searchingPlayer, goal.player):
startArmy = 0 + goalTargetArmy # + goalInc
else:
startArmy = 0 - goalTargetArmy # - goalInc
if ignoreGoalArmy:
# then we have to inversely increment so we dont have to figure that out in the loop every time
if not map.is_player_on_team_with(searchingPlayer, goal.player):
if negativeTiles is None or goal not in negativeTiles:
startArmy -= goal.army
else:
if negativeTiles is None or goal not in negativeTiles:
startArmy += goal.army
startVal = (startDist, 0, 0 - startArmy)
heapq.heappush(frontier, (startVal, goal, startDist, startArmy, int(goalInc * 2), None))
else:
goal: Tile
for goal in goalList:
if goal.isMountain:
# logbook.info("BFS DEST SKIPPING MOUNTAIN {},{}".format(goal.x, goal.y))
continue
goalInc = additionalIncrement
# fixes the off-by-one error because we immediately decrement army, but the target shouldn't decrement
startArmy = 1
if ignoreGoalArmy and (negativeTiles is None or goal not in negativeTiles):
# then we have to inversely increment so we dont have to figure that out in the loop every time
if not map.is_player_on_team_with(searchingPlayer, goal.player):
if goal.army > 0:
startArmy -= goal.army
else:
startArmy += goal.army
startVal = (0, 0, 0 - startArmy)
heapq.heappush(frontier, (startVal, goal, 0, startArmy, int(goalInc * 2), None))
start = time.perf_counter()
iter = 0
foundGoal = False
foundArmy = -1000
foundDist = -1
endNode = None
depthEvaluated = 0
baseTurn = map.turn
noNegs = negativeTiles is None or not negativeTiles
while frontier:
iter += 1
(prioVals, current, dist, army, goalInc, fromTile) = heapq.heappop(frontier)
if visited.raw[current.tile_index] is not None:
continue
if skipTiles and current in skipTiles:
continue
if current.isMountain or (
noNeutralCities and current.isCostlyNeutral and current not in goalList) or (
not current.discovered and current.isNotPathable
):
continue
_, negCaptures, prioArmy = prioVals
nextArmy = army - 1
isInc = (baseTurn + dist) & 1 == 0 and dist > 0
isTeam = map.is_player_on_team_with(searchingPlayer, current.player)
if preferCapture and not isTeam: # and army > current.army // 3
negCaptures -= 1
# nextArmy is effectively "you must bring this much army to the tile next to me for this to kill"
if (current.isCity and current.player != -1) or current.isGeneral:
if isTeam:
goalInc -= 1
# if isInc:
# nextArmy -= int(goalInc * 2)
else:
goalInc += 1
# if isInc:
# nextArmy += int(goalInc * 2)
notNegativeTile = noNegs or current not in negativeTiles
# we screw up the paths if we let negatives happen, we think a 1 can make it all the way across the map to capture a 1000...?
if current.army > 0:
if isTeam:
if notNegativeTile:
nextArmy += current.army
else:
if notNegativeTile:
nextArmy -= current.army
else:
nextArmy -= 1
if current.isSwamp:
nextArmy -= 2
newDist = dist + 1
visited.raw[current.tile_index] = (nextArmy, fromTile)
if nextArmy >= targetArmy and nextArmy > foundArmy and current.player == searchingPlayer and current.army > 1:
foundDist = newDist
foundArmy = nextArmy
endNode = current
if not noLog and iter < 100:
logbook.info(
f"GOAL popped {current.toString()}, army {nextArmy}, goalInc {goalInc}, targetArmy {targetArmy}, processing")
break
if isInc: #(current.x == 2 and current.y == 7) or (current.x == 2 and current.y == 8) or (current.x == 2 and current.y == 9) or (current.x == 3 and current.y == 9) or (current.x == 4 and current.y == 9) or (current.x == 5 and current.y == 9)
nextArmy -= goalInc
if newDist > depthEvaluated:
depthEvaluated = newDist
# targetArmy += goalInc
if not noLog and iter < 100:
logbook.info(
f"Popped current {current.toString()}, army {nextArmy}, goalInc {goalInc}, targetArmy {targetArmy}, processing")
if newDist <= maxDepth and not foundGoal:
for nextMove in current.movable: # new spots to try
heapq.heappush(frontier, ((newDist, negCaptures, 0 - nextArmy), nextMove, newDist, nextArmy, goalInc, current))
if not noLog:
logbook.info(
f"BFS DEST SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}, FOUNDDIST: {foundDist}")
if foundDist < 0:
return None
node = endNode
dist = foundDist
nodes = []
army = foundArmy
# logbook.info(json.dumps(visited))
# logbook.info("PPRINT FULL")
# logbook.info(pformat(visited))
while node is not None:
# logbook.info("ARMY {} NODE {},{} DIST {}".format(army, node.x, node.y, dist))
nodes.append((army, node))
# logbook.info(pformat(visited[node.x][node.y]))
(army, node) = visited.raw[node.tile_index]
dist -= 1
nodes.reverse()
(startArmy, startNode) = nodes[0]
# round against our favor so we always error on the side of too much defense
# or too much offense instead of not enough
if searchingPlayer == map.player_index:
foundArmy = math.floor(foundArmy)
else:
foundArmy = math.ceil(foundArmy)
pathObject = Path(foundArmy)
pathObject.add_next(startNode)
# pathStart = PathNode(startNode, None, foundArmy, foundDist, -1, None)
# path = pathStart
dist = foundDist
for i, armyNode in enumerate(nodes[1:]):
(curArmy, curNode) = armyNode
if curNode is not None:
# logbook.info("curArmy {} NODE {},{}".format(curArmy, curNode.x, curNode.y))
# path = PathNode(curNode, path, curArmy, dist, -1, None)
pathObject.add_start(curNode)
dist -= 1
while pathObject.start is not None and (pathObject.start.tile.army <= 1 or pathObject.start.tile.player != searchingPlayer):
logbook.info(
"IS THIS THE INC BUG? OMG I THINK I FOUND IT!!!!!! Finds path where waiting 1 move for city increment is superior, but then we skip the 'waiting' move and just move the 2 army off the city instead of 3 army?")
logbook.info(f"stripping path node {pathObject.start.tile}")
pathObject.remove_start()
pathObject.requiredDelay += 1
if pathObject.length <= 0:
logbook.info("abandoned path")
return None
logbook.info(
f"DEST BFS FOUND KILLPATH OF LENGTH {pathObject.length} VALUE {pathObject.value}\n{pathObject.toString()}")
return pathObject
def _shortestPathHeur(goals, cur) -> int:
minFound = 100000
for goal in goals:
minFound = min(minFound, abs(goal.x - cur.x) + abs(goal.y - cur.y))
return minFound
def _shortestPathHeurTile(goal, cur) -> int:
# MUCH much slower
# return (abs(goal.x - cur.x)**2 + abs(goal.y - cur.y)**2)**0.5
# TODO need to replace with torus safe calls to map...
return abs(goal.x - cur.x) + abs(goal.y - cur.y)
def a_star_kill(
map,
startTiles,
goalSet,
maxTime=0.1,
maxDepth=20,
restrictionEvalFuncsLookup=None,
ignoreStartTile=False,
requireExtraArmy=0,
negativeTiles=None):
frontier = []
came_from = {}
cost_so_far = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
logbook.info(f"a* enqueued start tile {start.toString()} with extraArmy {requireExtraArmy}")
startArmy = start.army
if ignoreStartTile:
startArmy = 0
startArmy -= requireExtraArmy
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = (startDist, 0 - startArmy)
heapq.heappush(frontier, ((_shortestPathHeur(goalSet, start) + startDist, 0 - startArmy), start))
came_from[start.tile_index] = None
else:
for start in startTiles:
logbook.info(f"a* enqueued start tile {start.toString()} with extraArmy {requireExtraArmy}")
startArmy = start.army
if ignoreStartTile:
startArmy = 0
startArmy -= requireExtraArmy
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = (0, 0 - startArmy)
heapq.heappush(frontier, ((_shortestPathHeur(goalSet, start), 0 - startArmy), start))
came_from[start.tile_index] = None
start = time.perf_counter()
iter = 0
foundDist = -1
foundArmy = -1
depthEvaluated = 0
while frontier:
iter += 1
prio, current = heapq.heappop(frontier)
dist, negArmy = cost_so_far[current.tile_index]
army = 0 - negArmy
if dist > depthEvaluated:
depthEvaluated = dist
if current in goalSet:
if army > 1 and army > foundArmy:
foundDist = dist
foundArmy = army
break
else: # skip paths that go through target, that wouldn't make sense
# logbook.info("a* path went through target")
continue
if dist >= maxDepth:
continue
newDist = dist + 1
for next in current.movable: # new spots to try
if next == came_from[current.tile_index]:
continue
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if restrictionEvalFuncsLookup is not None:
try:
f = restrictionEvalFuncsLookup[current]
if f(next):
logbook.info(f"dangerous, vetod: {current}")
continue
else:
logbook.info(f"safe: {current}")
except KeyError:
pass
inc = 0 if not ((next.isCity and next.player != -1) or next.isGeneral) else (dist + 1) / 2
# new_cost = cost_so_far[current.tile_index] + graph.cost(current, next)
nextArmy = army - 1
if negativeTiles is None or next not in negativeTiles:
if startTiles[0].player == next.player:
nextArmy += next.army + inc
else:
nextArmy -= (next.army + inc)
# if next.isCity and next.player == -1:
# nextArmy -= next.army * 2
if nextArmy <= 0 < army: # prune out paths that go negative after initially going positive
# logbook.info("a* next army <= 0: {}".format(nextArmy))
continue
new_cost = (newDist, (0 - nextArmy))
try:
curCost = cost_so_far[next.tile_index]
except KeyError:
curCost = (1000, -10000)
if new_cost < curCost:
cost_so_far[next.tile_index] = new_cost
priority = (newDist + _shortestPathHeur(goalSet, next), 0 - nextArmy)
heapq.heappush(frontier, (priority, next))
# logbook.info("a* enqueued next")
came_from[next.tile_index] = current
logbook.info(
f"A* KILL SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
goal = None
for possibleGoal in goalSet:
if possibleGoal.tile_index in came_from:
goal = possibleGoal
if goal is None:
return None
pathObject = Path(foundArmy)
pathObject.add_next(goal)
node = goal
dist = foundDist
while came_from[node.tile_index] is not None:
# logbook.info("Node {},{}".format(node.x, node.y))
node = came_from[node.tile_index]
dist -= 1
pathObject.add_start(node)
logbook.info(f"A* FOUND KILLPATH OF LENGTH {pathObject.length} VALUE {pathObject.value}\n{pathObject.toString()}")
pathObject.calculate_value(startTiles[0].player, teams=map.team_ids_by_player_index)
if pathObject.value < requireExtraArmy:
logbook.info(f"A* path {pathObject.toString()} wasn't good enough, returning none")
return None
return pathObject
def a_star_find(
startTiles,
goal: Tile,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False):
frontier = []
came_from = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
heapq.heappush(frontier, (startDist + _shortestPathHeurTile(goal, start), startDist, start))
came_from[start.tile_index] = None
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
came_from[start.tile_index] = None
start = time.perf_counter()
iter = 0
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
break
new_cost = dist + 1
if dist < maxDepth:
for next in current.movable: # new spots to try
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
if next.tile_index in came_from:
continue
priority = new_cost + _shortestPathHeurTile(goal, next)
heapq.heappush(frontier, (priority, new_cost, next))
# logbook.info("a* enqueued next")
came_from[next.tile_index] = current
if not noLog:
logbook.info(
f"a_star_find SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
if goal.tile_index not in came_from:
return None
pathObject = Path()
pathObject.add_next(goal)
node = goal
while came_from[node.tile_index] is not None:
# logbook.info("Node {},{}".format(node.x, node.y))
node = came_from[node.tile_index]
pathObject.add_start(node)
if not noLog:
logbook.info(f"a_star_find FOUND PATH OF LENGTH {pathObject.length} VALUE {pathObject.value}\n{pathObject}")
# pathObject.calculate_value(startTiles[0].player, teams=map._teams)
return pathObject
def a_star_find_official(
startTiles,
goal: Tile,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False):
frontier = []
came_from = {}
cost_so_far = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = startDist
heapq.heappush(frontier, (startDist + _shortestPathHeurTile(goal, start), startDist, start))
came_from[start.tile_index] = None
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = 0
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
came_from[start.tile_index] = None
start = time.perf_counter()
iter = 0
foundDist = -1
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
foundDist = dist
break
new_cost = dist + 1
if dist < maxDepth:
for next in current.movable: # new spots to try
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
curNextCost = cost_so_far.get(next.tile_index, 1000)
if new_cost < curNextCost:
cost_so_far[next.tile_index] = new_cost
priority = new_cost + _shortestPathHeurTile(goal, next)
heapq.heappush(frontier, (priority, new_cost, next))
# logbook.info("a* enqueued next")
came_from[next.tile_index] = current
if not noLog:
logbook.info(
f"a_star_find SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
if goal.tile_index not in came_from:
return None
pathObject = Path()
pathObject.add_next(goal)
node = goal
while came_from[node.tile_index] is not None:
# logbook.info("Node {},{}".format(node.x, node.y))
node = came_from[node.tile_index]
pathObject.add_start(node)
if not noLog:
logbook.info(f"a_star_find FOUND PATH OF LENGTH {pathObject.length} VALUE {pathObject.value}\n{pathObject}")
# pathObject.calculate_value(startTiles[0].player, teams=map._teams)
return pathObject
def a_star_find_raw(
startTiles,
goal: Tile,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False) -> typing.List[Tile] | None:
"""Returns tile list instead of path object"""
frontier = []
came_from = {}
cost_so_far = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = startDist
heapq.heappush(frontier, (startDist + _shortestPathHeurTile(goal, start), startDist, start))
came_from[start.tile_index] = None
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = 0
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
came_from[start.tile_index] = None
start = time.perf_counter()
iter = 0
foundDist = -1
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
foundDist = dist
break
new_cost = dist + 1
if dist < maxDepth:
for next in current.movable: # new spots to try
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
curNextCost = cost_so_far.get(next.tile_index, 1000)
if new_cost < curNextCost:
cost_so_far[next.tile_index] = new_cost
priority = new_cost + _shortestPathHeurTile(goal, next)
heapq.heappush(frontier, (priority, new_cost, next))
# logbook.info("a* enqueued next")
came_from[next.tile_index] = current
if not noLog:
logbook.info(
f"a_star_find_raw SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
if goal.tile_index not in came_from:
return None
tileList = [goal]
node = goal
while came_from[node.tile_index] is not None:
node = came_from[node.tile_index]
tileList.append(node)
if not noLog:
logbook.info(f"a_star_find_raw FOUND PATH OF LENGTH {len(tileList) - 1} {tileList}")
tileList.reverse()
return tileList
def a_star_find_raw_with_try_avoid(
startTiles,
goal: Tile,
tryAvoid: TileSet,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False) -> typing.List[Tile] | None:
frontier = []
came_from = {}
cost_so_far = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = startDist
heapq.heappush(frontier, (startDist + _shortestPathHeurTile(goal, start), startDist, start))
came_from[start.tile_index] = None
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = 0
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
came_from[start.tile_index] = None
start = time.perf_counter()
iter = 0
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
break
if dist < maxDepth:
for next in current.movable: # new spots to try
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
new_cost = dist + 1
if next in tryAvoid:
new_cost += 0.05
curNextCost = cost_so_far.get(next.tile_index, 1000)
if new_cost < curNextCost:
cost_so_far[next.tile_index] = new_cost
extraCost = 0
if next in tryAvoid:
extraCost = 0.3
priority = new_cost + _shortestPathHeurTile(goal, next) + extraCost
heapq.heappush(frontier, (priority, new_cost, next))
# logbook.info("a* enqueued next")
came_from[next.tile_index] = current
if not noLog:
logbook.info(
f"a_star_find_raw SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
if goal.tile_index not in came_from:
return None
tileList = [goal]
node = goal
while came_from[node.tile_index] is not None:
node = came_from[node.tile_index]
tileList.append(node)
if not noLog:
logbook.info(f"a_star_find_raw FOUND PATH OF LENGTH {len(tileList) - 1} {tileList}")
tileList.reverse()
return tileList
def a_star_find_matrix(
map: MapBase,
startTiles,
goal: Tile,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False):
frontier = []
came_from: MapMatrixInterface[Tile | None] = MapMatrix(map, None)
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
heapq.heappush(frontier, (startDist + _shortestPathHeurTile(goal, start), startDist, start))
came_from.raw[start.tile_index] = start
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
came_from.raw[start.tile_index] = start
start = time.perf_counter()
iter = 0
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
break
new_cost = dist + 1
if dist < maxDepth:
for next in current.movable: # new spots to try
if came_from.raw[next.tile_index] is not None:
continue
came_from.raw[next.tile_index] = current
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
priority = new_cost + _shortestPathHeurTile(goal, next)
heapq.heappush(frontier, (priority, new_cost, next))
if not noLog:
logbook.info(
f"A* FIND SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
if not came_from.raw[goal.tile_index]:
return None
pathObject = Path()
pathObject.add_next(goal)
node = goal
while came_from.raw[node.tile_index] is not None and came_from.raw[node.tile_index] is not node:
node = came_from.raw[node.tile_index]
pathObject.add_start(node)
if not noLog:
logbook.info(f"A* FOUND KILLPATH OF LENGTH {pathObject.length} VALUE {pathObject.value}\n{pathObject.toString()}")
return pathObject
def a_star_find_dist(
startTiles,
goal: Tile,
maxDepth: int = 200,
allowNeutralCities: bool = False,
noLog: bool = False) -> int:
frontier = []
cost_so_far = {}
if isinstance(startTiles, dict):
for start in startTiles.keys():
startDist = startTiles[start]
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = startDist
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start) + startDist, 0, start))
else:
for start in startTiles:
if not noLog:
logbook.info(f"a* enqueued start tile {start.toString()}")
# if (start.player == map.player_index and start.isGeneral and map.turn > GENERAL_HALF_TURN):
# startArmy = start.army / 2
cost_so_far[start.tile_index] = 0
heapq.heappush(frontier, (_shortestPathHeurTile(goal, start), 0, start))
start = time.perf_counter()
iter = 0
foundDist = -1
depthEvaluated = 0
while frontier:
iter += 1
prio, dist, current = heapq.heappop(frontier)
if dist > depthEvaluated:
depthEvaluated = dist
if current is goal:
foundDist = dist
break
new_cost = dist + 1
if dist < maxDepth:
for next in current.movable: # new spots to try
if next.isMountain or ((not next.discovered) and next.isNotPathable):
# logbook.info("a* mountain")
continue
if next.isCostlyNeutral and not allowNeutralCities:
continue
curNextCost = cost_so_far.get(next.tile_index, 1000)
if new_cost < curNextCost:
cost_so_far[next.tile_index] = new_cost
priority = new_cost + _shortestPathHeurTile(goal, next)
heapq.heappush(frontier, (priority, new_cost, next))
# logbook.info("a* enqueued next")
if not noLog:
logbook.info(
f"A* FIND SEARCH ITERATIONS {iter}, DURATION: {time.perf_counter() - start:.4f}, DEPTH: {depthEvaluated}")
return foundDist
# TODO this is in need of optimization
def breadth_first_dynamic(
map,
startTiles,
goalFunc: typing.Callable[[Tile, typing.Tuple], bool],
maxDepth=100,
noNeutralCities: bool = True,
negativeTiles: TileSet | None = None,
skipTiles: TileSet | None = None,
searchingPlayer: int = -2,
priorityFunc: typing.Callable[[Tile, typing.Tuple], typing.Tuple | None] = None,
ignoreStartTile: bool = False,
incrementBackward: bool = False,
noLog: bool = False,