forked from harrischristiansen/generals-bot
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPath.py
More file actions
800 lines (674 loc) · 25.5 KB
/
Path.py
File metadata and controls
800 lines (674 loc) · 25.5 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
"""
@ 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
"""
from __future__ import annotations
import logbook
import typing
from Models import GatherTreeNode, Move
from collections import deque
from Interfaces.TilePlanInterface import TilePlanInterface, PathMove
from base.client.tile import Tile
from base.client.map import MapBase
class Path(TilePlanInterface):
__slots__ = (
'start',
'_pathQueue',
'tail',
'_tileList',
'_tileSet',
'_adjacentSet',
'value',
'_econ_value',
'_requiredDelay',
)
def __init__(self, armyRemaining: float = 0):
self.start: PathMove | None = None
self._pathQueue: typing.Deque[PathMove] = deque()
self.tail: PathMove | None = None
self._tileList: typing.List[Tile] | None = None
self._tileSet: typing.Set[Tile] | None = None
self._adjacentSet: typing.Set[Tile] | None = None
# The exact army tile number that will exist on the final tile at the end of the path run.
# So for a path that exactly kills a tile with minimum kill army, this should be 1.
self.value: float = armyRemaining
self._econ_value: float = 0.0
self._requiredDelay: int = 0
# def __gt__(self, other) -> bool:
# if other is None:
# return True
# return self.length > other.length
#
# def __lt__(self, other) -> bool:
# if other is None:
# return True
# return self.length < other.length
# @property
# def value(self) -> float:
# return self._value
#
# @value.setter
# def value(self, val: float):
# self._value = val
@property
def econValue(self) -> float:
return self._econ_value
@econValue.setter
def econValue(self, val: float):
self._econ_value = val
@property
def length(self) -> int:
return max(0, len(self._pathQueue) - 1)
@property
def tileSet(self) -> typing.Set[Tile]:
if self._tileSet is None:
if self._tileList is not None:
self._tileSet = set(self._tileList)
else:
self._tileSet = set()
for t in self._pathQueue:
self._tileSet.add(t.tile)
return self._tileSet
@tileSet.setter
def tileSet(self, value):
raise AssertionError("NO SETTING!")
@property
def tileList(self) -> typing.List[Tile]:
if self._tileList is None:
self._tileList = [t.tile for t in self._pathQueue]
return self._tileList
@property
def adjacentSet(self) -> typing.Set[Tile]:
"""Includes the tileSet itself, too."""
if self._adjacentSet is None:
self._adjacentSet = set()
for t in self._pathQueue:
self._adjacentSet.update(t.tile.adjacents)
return self._adjacentSet
@property
def requiredDelay(self) -> int:
return self._requiredDelay
@requiredDelay.setter
def requiredDelay(self, val: int):
self._requiredDelay = val
def get_move_list(self) -> typing.List[Move]:
moves = []
node = self.start
while node.next is not None:
moves.append(Move(node.tile, node.next.tile, node.move_half))
node = node.next
return moves
def add_next(self, nextTile, move_half=False):
move = PathMove(nextTile)
move.prev = self.tail
if self.start is None:
self.start = move
if self.tail is not None:
self.tail.next = move
self.tail.move_half = move_half
if self._tileList is not None:
self._tileList.append(nextTile)
if self._tileSet is not None:
self._tileSet.add(nextTile)
if self._adjacentSet is not None:
self._adjacentSet.update(nextTile.adjacents)
self.tail = move
self._pathQueue.append(move)
def add_start(self, startTile: Tile):
move = PathMove(startTile)
if self.start is not None:
move.next = self.start
self.start.prev = move
else:
self.tail = move
self.start = move
if self._tileList is not None:
self._tileList.insert(0, startTile)
if self._tileSet is not None:
self._tileSet.add(startTile)
if self._adjacentSet is not None:
self._adjacentSet.update(startTile.adjacents)
self._pathQueue.appendleft(move)
def remove_start(self):
if len(self._pathQueue) == 0:
raise ", bitch? Why you tryin to remove_start when there aint no moves to made?"
self._tileSet = None
self._tileList = None
self._adjacentSet = None
self.start = self.start.next
self._pathQueue.popleft()
def get_first_move(self) -> Move | None:
if len(self._pathQueue) <= 1:
return None
move = Move(self.start.tile, self.start.next.tile, self.start.move_half)
return move
def pop_first_move(self) -> Move | None:
if len(self._pathQueue) <= 1:
raise ", bitch? Why you tryin to pop_first_move when there aint no moves to made?"
move = self.get_first_move()
self._tileSet = None
self._tileList = None
self._adjacentSet = None
self.start = self.start.next
self._pathQueue.popleft()
return move
def remove_end(self):
if len(self._pathQueue) == 0:
logbook.info(", bitch? Removing nothing??")
return None
self._tileSet = None
self._tileList = None
self._adjacentSet = None
move = self._pathQueue.pop()
self.tail = self.tail.prev
if self.tail is not None:
self.tail.next = None
def convert_to_dist_dict(self, offset: int = 0) -> typing.Dict[Tile, int]:
"""
returns a dict[Tile, int] starting at offset(emptyVal 0) for path.start and working up from there.
@param offset:
@return:
"""
dist = offset # + 0.00001
dict = {}
node = self.start
while node is not None:
dict[node.tile] = dist
node = node.next
dist += 1
# dist += 1.0001
return dict
def calculate_value(
self,
forPlayer: int,
teams: typing.List[int],
negativeTiles: None | typing.Set[Tile] | typing.Dict[Tile, typing.Any] = None,
ignoreNonPlayerArmy: bool = False,
ignoreIncrement: bool = False,
incrementBackwards: bool = False,
doNotSaveToPath: bool = False
) -> int:
# have to offset the first [val - 1] I guess since the first tile didn't get moved to
val = 1
node = self.start
i = 0
while node is not None:
tile = node.tile
if negativeTiles is None or tile not in negativeTiles:
if tile.player != -1 and teams[tile.player] == teams[forPlayer]:
val += tile.army
if (tile.isCity or tile.isGeneral) and not ignoreIncrement:
incVal = (i - 1)
if incrementBackwards:
incVal = self.length - incVal
val += incVal // 2
elif not ignoreNonPlayerArmy:
val -= tile.army
if (tile.isCity or tile.isGeneral) and tile.player != -1 and not ignoreIncrement:
incVal = (i - 1)
if incrementBackwards:
incVal = self.length - incVal
val -= incVal // 2
if not node.move_half:
val = val - 1
else:
val = (val + 1) // 2
node = node.next
i += 1
if not doNotSaveToPath:
self.value = val
return val
def get_positive_subsegment(
self,
forPlayer: int,
teams: typing.List[int],
negativeTiles: None | typing.Set[Tile] | typing.Dict[Tile, typing.Any] = None,
ignoreIncrement: bool = False
) -> Path | None:
# have to offset the first [val - 1] I guess since the first tile didn't get moved to
val = 1
node = self.start
i = 0
while node is not None:
tile = node.tile
oldVal = val
if negativeTiles is None or tile not in negativeTiles:
if tile.player != -1 and teams[tile.player] == teams[forPlayer]:
val += tile.army
if (tile.isCity or tile.isGeneral) and not ignoreIncrement:
incVal = (i - 1)
val += incVal // 2
else:
val -= tile.army
if (tile.isCity or tile.isGeneral) and tile.player != -1 and not ignoreIncrement:
incVal = (i - 1)
val -= incVal // 2
if not node.move_half:
val = val - 1
else:
val = (val + 1) // 2
if val <= 0:
val = oldVal
break
node = node.next
i += 1
sub = self.get_subsegment(i - 1)
sub.value = val
return sub
def get_subsegment_until_visible_to_player(self, players: typing.List[int]) -> Path:
# have to offset the first [val - 1] I guess since the first tile didn't get moved to
val = 1
node = self.start
i = 0
while node is not None:
tile = node.tile
shouldBreak = False
for vSource in tile.visibleTo:
if vSource.player in players:
shouldBreak = True
break
if shouldBreak:
break
node = node.next
i += 1
if i <= 1:
i = 2
sub = self.get_subsegment(i - 1)
return sub
def clone(self) -> Path:
newPath = Path(self.value)
node = self.start
while node is not None:
newPath.add_next(node.tile)
node = node.next
newPath._requiredDelay = self._requiredDelay
newPath._econ_value = self._econ_value
return newPath
def get_reversed(self) -> Path:
if self.start is None or self.start.next is None:
return self.clone()
newPath = Path()
temp = self.tail
while temp is not None:
newPath.add_next(temp.tile)
temp = temp.prev
newPath.value = self.value
newPath._econ_value = self._econ_value
return newPath
def get_subsegment(self, count: int, end: bool = False) -> Path:
"""
The subsegment path will be count moves long, count+1 TILES long
@param count:
@param end: If True, get the subsegment of the LAST {count} moves instead of FIRST {count} moves
@return:
"""
if count <= 0:
return Path()
newPath = self.clone()
i = 0
if end:
while i < self.length - count:
i += 1
newPath.start = newPath.start.next
newPath._pathQueue.popleft()
else:
while i < self.length - count:
i += 1
newPath._pathQueue.pop()
newPath.tail = newPath.tail.prev
if newPath.tail is not None:
newPath.tail.next = None
return newPath
def __str__(self) -> str:
node = self.start
nodeStrs = []
half = False
while node is not None:
nodeStrs.append(f'{node.tile.x},{node.tile.y}{"" if not half else "z"}')
half = node.move_half
node = node.next
valStr = ''
if self._econ_value != 0.0:
valStr = f' {self._econ_value:.2f}v'
return f"[{self.value}a{valStr} {self.length}t] {' -> '.join(nodeStrs)}"
def toString(self) -> str:
return str(self)
def to_move_string(self):
node = self.start
nodeStrs = []
half = False
while node is not None:
nodeStrs.append(f'{node.tile.x},{node.tile.y}{"" if not half else "z"}')
half = node.move_half
node = node.next
return '->'.join(nodeStrs)
def __repr__(self) -> str:
return str(self)
def convert_to_tree_nodes(self, map: MapBase, forPlayer: int) -> GatherTreeNode:
curGatherTreeNode = None
curPathNode = self.start
prevPathTile = None
turn = 0
value = 0
while curPathNode is not None:
prevGatherTreeNode = curGatherTreeNode
t = curPathNode.tile
curGatherTreeNode = GatherTreeNode(t, prevPathTile)
if prevGatherTreeNode is not None:
curGatherTreeNode.children.append(prevGatherTreeNode)
if map.is_tile_on_team_with(t, forPlayer):
value += t.army
else:
value -= t.army
value -= 1
curGatherTreeNode.gatherTurns = turn
curGatherTreeNode.value = value
turn += 1
prevPathTile = t
curPathNode = curPathNode.next
return curGatherTreeNode
def break_overflow_into_one_move_path_subsegments(self, lengthToKeepInOnePath: int = 1) -> typing.List[typing.Union[Path, None]]:
"""
Takes a path and gets a lengthToKeepInOnePath subsegment, PLUS the rest of the path as single-move subsegments. Useful when you need to interrupt a paths execution with other moves after a certain time.
@param lengthToKeepInOnePath:
@return:
"""
if lengthToKeepInOnePath >= self.length:
copy = self.clone()
segments = [copy]
# # can never happen in first 25 but may need to pad with Nones to keep it the original length...?
# for _ in range(self.length, lengthToKeepInOnePath):
# segments.append(None)
return segments
# break the new path up into multiple segments, replacing the None's
firstSegment = self.get_subsegment(lengthToKeepInOnePath)
segments = [firstSegment]
newCopyEnd = self.get_subsegment(self.length - lengthToKeepInOnePath, end=True)
for i in range(newCopyEnd.length):
segments.append(newCopyEnd.get_subsegment(1))
newCopyEnd = newCopyEnd.get_subsegment(newCopyEnd.length - 1, end=True)
return segments
def convert_to_move_list(self) -> typing.List[Move]:
moves = []
node = self.start
while node.next is not None:
moves.append(Move(node.tile, node.next.tile, node.move_half))
node = node.next
return moves
@classmethod
def from_string(cls, map: MapBase, pathStr: str) -> Path:
moves = pathStr.split('->')
prevTile: Tile | None = None
path = Path()
for move_str in moves:
xStr, yStr = move_str.strip().split(',')
moveHalf = False
if yStr.strip().endswith('z'):
moveHalf = True
yStr = yStr.strip('z ')
nextTile = map.GetTile(int(xStr), int(yStr))
if prevTile is None:
path.add_next(nextTile)
prevTile = nextTile
continue
if prevTile.x != nextTile.x and prevTile.y != nextTile.y:
raise AssertionError(f'Cannot jump diagonally between {str(prevTile)} and {str(nextTile)}')
xInc = nextTile.x - prevTile.x
if xInc < 0:
xInc = -1
elif xInc > 0:
xInc = 1
yInc = nextTile.y - prevTile.y
if yInc < 0:
yInc = -1
elif yInc > 0:
yInc = 1
while prevTile.x != nextTile.x or prevTile.y != nextTile.y:
currentTile = map.GetTile(prevTile.x + xInc, prevTile.y + yInc)
path.add_next(currentTile, moveHalf)
prevTile = currentTile
moveHalf = False
path.calculate_value(forPlayer=path.start.tile.player, teams=map.team_ids_by_player_index)
return path
def get_subsegment_excluding_trailing_visible(self) -> Path:
"""
Gets a subsegment of the path with visible tiles pruned from the end.
Does NOT modify the
@return:
"""
path = self.clone()
while path.tail.tile.visible and path.length > 1:
path.remove_end()
if path.tail.tile.visible:
logbook.warn(f'couldn\'t successfully get_subsegment_excluding_trailing_visible because even the first move in the path was visible. Returning the length 1 subsegment: {path}')
return path
@classmethod
def from_move(cls, move: Move) -> Path:
path = Path()
path.add_next(move.source)
path.add_next(move.dest, move.move_half)
return path
class MoveListPath(Path):
__slots__ = ()
# noinspection PyMissingConstructor
def __init__(self, moves: typing.List[Move | None]):
# super().__init__(0)
self.start: PathMove | None = None
self.tail: PathMove | None = None
self._pathQueue: typing.Deque[Move | None] = deque()
self._tileList: typing.List[Tile] | None = None
self._tileSet: typing.Set[Tile] | None = None
self._adjacentSet: typing.Set[Tile] | None = None
# The exact army tile number that will exist on the final tile at the end of the path run.
# So for a path that exactly kills a tile with minimum kill army, this should be 1.
self.value: float = 0.0
self._econ_value: float = 0.0
self._requiredDelay: int = 0
if moves:
for move in moves:
self.add_next_move(move)
@property
def econValue(self) -> float:
return self._econ_value
@econValue.setter
def econValue(self, val: float):
self._econ_value = val
@property
def length(self) -> int:
return max(0, len(self._pathQueue))
@property
def tileSet(self) -> typing.Set[Tile]:
if self._tileSet is None:
if self._tileList is not None:
self._tileSet = set(self._tileList)
else:
self._tileSet = set()
for t in self._pathQueue:
if t:
self._tileSet.add(t.source)
self._tileSet.add(t.dest)
return self._tileSet
@tileSet.setter
def tileSet(self, value):
raise AssertionError("NO SETTING!")
@property
def tileList(self) -> typing.List[Tile]:
if self._tileList is None:
self._tileList = []
lastDest = None
for move in self._pathQueue:
if move:
if move.source != lastDest:
self._tileList.append(move.source)
self._tileList.append(move.dest)
lastDest = move.dest
else:
lastDest = None
return self._tileList
@property
def adjacentSet(self) -> typing.Set[Tile]:
"""Includes the tileSet itself, too."""
if self._adjacentSet is None:
self._adjacentSet = set()
for t in self.tileList:
self._adjacentSet.update(t.adjacents)
return self._adjacentSet
@property
def requiredDelay(self) -> int:
return self._requiredDelay
@requiredDelay.setter
def requiredDelay(self, val: int):
self._requiredDelay = val
def get_move_list(self) -> typing.List[Move]:
return list(self._pathQueue)
def add_next(self, nextTile, move_half=False):
move = PathMove(nextTile)
prev = self.tail
move.prev = self.tail
if self.start is None:
self.start = move
if self.tail is not None:
self.tail.next = move
self.tail.move_half = move_half
if self._tileList is not None:
self._tileList.append(nextTile)
if self._tileSet is not None:
self._tileSet.add(nextTile)
if self._adjacentSet is not None:
self._adjacentSet.update(nextTile.adjacents)
self.tail = move
if prev is not None:
self._pathQueue.append(Move(prev.tile, nextTile, move_half))
def add_next_move(self, move: Move | None):
if move is None:
self._pathQueue.append(move)
return
if not self.tail:
self.add_next(move.source)
if self.tail.tile == move.source:
self.add_next(move.dest, move.move_half)
return
sourcePm = PathMove(move.source)
sourcePm.prev = self.tail
self.tail.next = sourcePm
destPm = PathMove(move.dest, move_half=move.move_half)
destPm.prev = sourcePm
sourcePm.next = destPm
if self._tileList is not None:
self._tileList.append(move.source)
self._tileList.append(move.dest)
if self._tileSet is not None:
self._tileSet.add(move.source)
self._tileSet.add(move.dest)
if self._adjacentSet is not None:
self._adjacentSet.update(move.source.adjacents)
self._adjacentSet.update(move.dest.adjacents)
self.tail = destPm
self._pathQueue.append(move)
def add_start(self, startTile: Tile):
move = PathMove(startTile)
nextNode = self.start
if self.start is not None:
move.next = self.start
self.start.prev = move
else:
self.tail = move
self.start = move
if self._tileList is not None:
self._tileList.insert(0, startTile)
if self._tileSet is not None:
self._tileSet.add(startTile)
if self._adjacentSet is not None:
self._adjacentSet.update(startTile.adjacents)
if nextNode:
self._pathQueue.appendleft(Move(startTile, nextNode.tile))
def remove_start(self):
self._remove_start()
def _remove_start(self) -> Move:
if len(self._pathQueue) == 0:
raise ", bitch? Why you tryin to remove_start when there aint no moves to made?"
self._tileSet = None
self._tileList = None
self._adjacentSet = None
self.start = self.start.next
move = self._pathQueue.popleft()
if self.start and self._pathQueue and self._pathQueue[0] and self._pathQueue[0].source != self.start.tile:
self.start = self.start.next
# this wasn't / isn't here in main path impl
if self.start is not None:
self.start.prev = None
return move
def get_first_move(self) -> Move | None:
if len(self._pathQueue) <= 0:
return None
return self._pathQueue[0]
def pop_first_move(self) -> Move:
move = self._remove_start()
return move
def _remove_end(self) -> Move | None:
if len(self._pathQueue) == 0:
logbook.info(", bitch? Removing nothing??")
return None
self._tileSet = None
self._tileList = None
self._adjacentSet = None
self.tail = self.tail.prev
move = self._pathQueue.pop()
if self.tail and self._pathQueue and self._pathQueue[-1].dest != self.tail.tile:
self.tail = self.tail.prev
if self.tail:
self.tail.next = None
return move
def remove_end(self):
self._remove_end()
def remove_end_move(self) -> Move | None:
move = self._remove_end()
return move
def calculate_value(
self,
forPlayer: int,
teams: typing.List[int],
negativeTiles: None | typing.Set[Tile] | typing.Dict[Tile, typing.Any] = None,
ignoreNonPlayerArmy: bool = False,
ignoreIncrement: bool = False,
incrementBackwards: bool = False,
doNotSaveToPath: bool = False
) -> int:
# have to offset the first [val - 1] I guess since the first tile didn't get moved to
val = 1
node = self.start
i = 0
while node is not None:
tile = node.tile
if negativeTiles is None or tile not in negativeTiles:
if tile.player != -1 and teams[tile.player] == teams[forPlayer]:
val += tile.army
if (tile.isCity or tile.isGeneral) and not ignoreIncrement:
incVal = (i - 1)
if incrementBackwards:
incVal = self.length - incVal
val += incVal // 2
elif not ignoreNonPlayerArmy:
val -= tile.army
if (tile.isCity or tile.isGeneral) and tile.player != -1 and not ignoreIncrement:
incVal = (i - 1)
if incrementBackwards:
incVal = self.length - incVal
val -= incVal // 2
if not node.move_half:
val = val - 1
else:
val = (val + 1) // 2
node = node.next
i += 1
if not doNotSaveToPath:
self.value = val
return val
def clone(self) -> MoveListPath:
newPath = MoveListPath(self.get_move_list())
newPath._requiredDelay = self._requiredDelay
newPath._econ_value = self._econ_value
newPath.value = self.value
return newPath