-
Notifications
You must be signed in to change notification settings - Fork 1
/
player.py
1264 lines (967 loc) · 36.5 KB
/
player.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
from __future__ import annotations
import functools
import time
from collections import deque
from contextlib import contextmanager
from dataclasses import dataclass
from enum import Enum, IntEnum
from itertools import chain, count, islice, product
from random import choice
from typing import Any, Iterator
from base import Board
TEST = False
# Player template for HIVE --- ALP semestral work
# Vojta Vonasek, 2023
# PUT ALL YOUR IMPLEMENTATION INTO THIS FILE
type BoardData = dict[Cell, list[Piece]]
type BoardDataBrute = dict[int, dict[int, str]]
type Cell = tuple[int, int]
type Direction = tuple[int, int]
# list[str, int, int, int, int] | list[str, None, None, int, int]
type MoveBrute = list[Any]
DIRECTIONS = [(1, 0), (0, 1), (-1, 1), (-1, 0), (0, -1), (1, -1)]
def length_of_iter[T](iterator: Iterator[T]) -> int:
"""Count the number of elements in an iterator."""
return len(tuple(iterator))
def parse_board(string: str) -> BoardDataBrute:
"""Parse board from string."""
board: BoardDataBrute = {}
lines = string.splitlines()
for q, line in enumerate(lines):
for p, char in enumerate(line.split(), start=-(q // 2)):
board.setdefault(p, {})
board[p][q] = char if char != "." else ""
return board
def convert_board(board: BoardDataBrute) -> BoardData:
"""
Convert board to internal representation.
Utilizes lists instead of strings for faster manipulations.
"""
return {
(p, q): list(map(Piece.from_str, value))
for p, row in board.items()
for q, value in row.items()
if value
}
def rotate_left(direction: Direction) -> Direction:
"""Return direction rotated one tile to left."""
p, q = direction
return p + q, -p
def rotate_right(direction: Direction) -> Direction:
"""Return direction rotated one tile to right."""
p, q = direction
return -q, p + q
class Criteria(IntEnum):
"""
Criteria for the evaluation function.
Used to index the evaluation tables.
"""
BASE = 0
"""Base points for every piece on the board"""
BLOCKING_RIVAL = 1
"""Piece (other than queen and beetle) has only one neighbor - rival"""
BEETLE_BLOCKING = 2
"""Beetle is on top of a rival's piece"""
BEETLE_BLOCKING_QUEEN_BONUS = 3
"""Beetle is on top of the rival's queen (adds to `BEETLE_BLOCKING`)"""
QUEEN_NEIGHBOR = 4
"""Penalty for the every neighbor of queen"""
QUEEN_SURROUNDED = 5
"""Penalty if the queen is completely surrounded"""
QUEEN_BLOCKED = 6
"""Penalty if the queen can't move"""
BLOCKING_FRIEND = 7
"""Piece (other than queen and beetle) has only one neighbor - friend"""
EVAL_TABLE_MY = [-1, -500, 200, 1000, -400, -1000000, -400, 200, -50]
EVAL_TABLE_RIVAL = [0, 600, -200, -800, 500, 1000000, 400, -100, 50]
def calculate_blocking_score(
player: Player,
cell: Cell,
table: list[int],
*,
target_player: bool,
only_my: bool = False,
) -> int:
"""Check if the given piece is blocking another piece."""
neighbors = player.neighbors(cell)
neighbor = next(neighbors, None)
if not neighbor or next(neighbors, None) is not None:
return 0
if not player.is_target_cell(neighbor, target_player):
return table[Criteria.BLOCKING_RIVAL] if not only_my else 0
return table[Criteria.BLOCKING_FRIEND]
def calculate_beetle_blocking_score(
pieces: list[Piece],
table: list[int],
*,
target_player: bool,
) -> int:
"""Check if the given cell is blocked by a beetle."""
assert len(pieces) >= 2
second_piece = pieces[-2]
if second_piece.upper == target_player:
return -table[Criteria.BEETLE_BLOCKING]
score = table[Criteria.BEETLE_BLOCKING]
if second_piece.kind == PieceKind.Queen:
score += table[Criteria.BEETLE_BLOCKING_QUEEN_BONUS]
return score
def evaluate_cell(
player: Player,
cell: Cell,
pieces: list[Piece],
*,
target_player: bool,
rivals_queen: Cell | None = None,
) -> tuple[int, State]:
"""
Evaluate the given cell from the POV of the given player.
Uses the evaluation tables `EVAL_TABLE_MY` and `EVAL_TABLE_RIVAL`,
following the evaluation criteria in `Criteria`
"""
piece = pieces[-1]
piece_is_upper = piece.upper
my = piece_is_upper == target_player
piece_kind = piece.kind
table = EVAL_TABLE_MY if my else EVAL_TABLE_RIVAL
score = table[Criteria.BASE]
blocking_score = calculate_blocking_score(
player,
cell,
table,
target_player=target_player,
only_my=piece_kind in {PieceKind.Beetle, PieceKind.Queen},
)
score += blocking_score * 2 if piece_kind == PieceKind.Ant else 1
if rivals_queen:
score -= 20 * player.distance(*cell, *rivals_queen)
if piece_kind == PieceKind.Beetle and len(pieces) > 1:
score += calculate_beetle_blocking_score(
pieces,
table,
target_player=target_player,
)
return score, State.RUNNING
if piece_kind == PieceKind.Queen:
c = length_of_iter(player.neighbors(cell))
if c == 6:
return table[Criteria.QUEEN_SURROUNDED], State.LOSS if my else State.WIN
if c == 1:
return -table[Criteria.QUEEN_NEIGHBOR], State.RUNNING
score += table[Criteria.QUEEN_NEIGHBOR] * (c - 1)
if player.neighbor_groups(cell) != 1:
score += table[Criteria.QUEEN_BLOCKED]
return score, State.RUNNING
evaluated = 0
updates = 0
cache_hits = 0
found_cycles = 0
duplicates = 0
removed = 0
def evaluate_position(player: Player, *, target_player: bool) -> tuple[int, State]:
"""Evaluate the position from the POV of the given player."""
global evaluated
evaluated += 1
score = 0
rivals_queen_str = (
PieceKind.Queen.lower() if target_player else PieceKind.Queen.upper()
)
rivals_queen = next(
(c for c, p in player._board.items() if rivals_queen_str in p),
None,
)
for cell, pieces in player._board.items():
is_target_cell = player.is_target_cell(cell, target_player)
if is_target_cell and rivals_queen:
score -= player.distance(*cell, *rivals_queen)
piece_score, game_state = evaluate_cell(
player,
cell,
pieces,
target_player=target_player,
rivals_queen=rivals_queen if is_target_cell else None,
)
if game_state.is_end():
return piece_score, game_state
score += piece_score
return score, State.RUNNING
class PieceKind(str, Enum):
"""Kind of a game piece."""
Queen = "Q"
Spider = "S"
Beetle = "B"
Ant = "A"
Grasshopper = "G"
@staticmethod
def from_str(string: str) -> PieceKind:
"""Convert a string to a `Piece`."""
return PieceKind(string.upper())
# overrides str for little speed bonus, since all are already upper
def upper(self) -> str:
"""Return the string representation in upper case."""
return self.value
def lower(self) -> str:
"""Return the string representation in lower case."""
return self.value.lower()
@dataclass
class Piece:
"""Game piece."""
__slots__ = ("kind", "upper")
kind: PieceKind
upper: bool
@staticmethod
def from_str(string: str) -> Piece:
"""Convert a string to a `Piece`."""
return Piece(PieceKind.from_str(string), string.isupper())
def __str__(self) -> str:
"""Return the string representation of the piece."""
return self.kind.upper() if self.upper else self.kind.lower()
@dataclass
class Move:
"""
Holds a move, defined by a piece, start cell and end cell.
Start is `None` when placing a new piece from reserve.
"""
__slots__ = ("piece", "start", "end")
piece: PieceKind
start: Cell | None
end: Cell
def to_brute(self, upper: bool) -> MoveBrute:
"""Convert the move to brute representation."""
piece = self.piece_str(upper)
if self.start is None:
return [piece, None, None, *self.end]
return [piece, *self.start, *self.end]
def piece_str(self, upper: bool) -> str:
"""Return the string representation of the used piece."""
return self.piece.upper() if upper else self.piece.lower()
def __str__(self) -> str:
"""Return the string representation of the move."""
return f"{self.piece_str(True)}: {self.start} -> {self.end}"
class State(IntEnum):
"""State of the game."""
RUNNING = 0
WIN = 1
LOSS = 2
DRAW = 3
def is_end(self) -> bool:
"""
Check if the state represents the end of the game.
That is WIN, LOSS or DRAW.
"""
return self > 0
def inverse(self) -> State: # sourcery skip: assign-if-exp, reintroduce-else
"""
Return the inverse state.
Swaps the WIN and LOSS states, every other state is unchanged.
"""
if self == State.WIN:
return State.LOSS
if self == State.LOSS:
return State.WIN
return self
class Node:
"""Node in the minimax tree."""
__slots__ = (
"move",
"player",
"score",
"children",
"depth",
"state",
)
move: Move
player: Player
score: int
children: list[Node]
depth: int
state: State
def __init__(
self,
move: Move,
player: Player,
) -> None:
"""
Initialize the node.
`player` is the one holding the board, not the evaluation target. That is
specified when calling `next_depth`.
"""
self.move = move
self.player = player
self.score = 0
self.children = []
self.depth = 0
self.state = State.RUNNING
def next_depth(self, player: Player, end: float, *, target_player: bool) -> bool:
"""
Compute the next depth using the minimax algorithm.
First call evaluates the current position, second call creates
the children of the current node and all next calls, call
this function recursively on the children.
Returns True if it finished computing the next depth before
time specified in `end`, otherwise returns False. When that happens,
the results should be discarded, since they are only half done and
thus not accurate.
"""
if self.state.is_end():
return True
if time.perf_counter() > end:
return False
self.depth += 1
with play_move(player, self.move):
if self.depth == 1:
self.score, self.state = evaluate_position(
self.player,
target_player=target_player,
)
return True
if self.depth == 2:
self.children = [Node(move, player) for move in player.valid_moves]
for child in self.children:
if not child.next_depth(
player,
end,
target_player=not target_player,
):
return False
self.score, self.state = self.evaluate_children()
return True
def evaluate_children(self) -> tuple[int, State]:
"""Evaluate the children of the current node."""
if not self.children:
return 0, State.DRAW
children = self.children
children.sort(reverse=True)
depth = self.depth
if depth <= 2:
limit = 8
elif depth <= 3:
limit = 5
elif depth <= 5:
limit = 3
else:
limit = 2
self.children = children[:limit]
best = self.children[0]
return -best.score, best.state.inverse()
def __gt__(self, other: Node) -> bool:
"""Compare nodes by score."""
return self.score > other.score
def __str__(self) -> str:
"""Return a string representation of the node."""
if self.state.is_end():
return f"{self.move}: {self.score} {self.state}"
return f"{self.move}: {self.score}"
@contextmanager
def lift_piece(player: Player, cell: Cell) -> Iterator[Piece]:
"""Lifts a piece from the board for the duration of the context."""
piece = player.remove_piece_from_board(cell)
yield piece
player.add_piece_to_board(cell, piece)
@contextmanager
def play_move(player: Player, move: Move) -> Iterator[None]:
"""Plays a move for the duration of the context."""
player.play_move(move)
yield
player.reverse_move(move)
class Player(Board):
"""
A player for the hive game. Public API includes the constructor and the move method.
## State:
Inner state consists of a set of cells that together create the hive. This is done
in order to speed up lot of the calculations inside and thus all of the methods
implicitly depends on it. The properties should be independent and stateless,
unless explicitly specified otherwise in their docstrings.
"""
__slots__ = (
"__board",
"cycles",
"__cached_cycles",
"__cycles_need_update",
"size",
"myColorIsUpper",
"myPieces",
"rivalPieces",
"playerName",
"algorithmName",
)
_board: BoardData
cycles: set[Cell]
__cached_cycles: dict[int, set[Cell]]
__cycles_need_update: bool
def __init__(
self,
player_name: str,
my_is_upper: bool,
size: int,
my_pieces: dict[str, int],
rival_pieces: dict[str, int],
) -> None:
"""
Create a new player.
*Note: the API has to stay this way to be compatible with Brute*
"""
super().__init__(my_is_upper, size, my_pieces, rival_pieces)
self.playerName = player_name
self.algorithmName = "Maneren v1.1"
self._board = convert_board(self.board)
self.cycles = set()
self.__cached_cycles = {}
self.__cycles_need_update = True
@property
def upper(self) -> bool:
"""The player uses uppercased pieces."""
return self.myColorIsUpper
@property
def cells(self) -> Iterator[Cell]:
"""Iterator over all cells."""
return (
(p, q)
for q in range(self.size)
for p in range(-(q // 2), self.size - q // 2)
)
@property
def empty_cells(self) -> Iterator[Cell]:
"""Iterator over all empty cells."""
return (cell for cell in self.cells if self.is_empty(cell))
@property
def nonempty_cells(self) -> Iterator[Cell]:
"""Iterator over all nonempty cells."""
return iter(self._board.keys())
@property
def my_pieces_on_board(self) -> Iterator[tuple[Cell, Piece]]:
"""Iterator over all my pieces on the board."""
board_contents = [
(cell, pieces)
for cell, pieces in self._board.items()
if self.is_my_cell(cell)
]
return ((cell, pieces[-1]) for cell, pieces in board_contents)
@property
def my_placable_pieces(self) -> Iterator[PieceKind]:
"""Iterator over all my placable pieces."""
return (
PieceKind.from_str(piece)
for piece, count in self.myPieces.items()
if count > 0
)
@property
def my_movable_pieces(self) -> Iterator[tuple[Cell, Piece]]:
"""Iterator over all my movable pieces."""
return (
(cell, piece)
for cell, piece in self.my_pieces_on_board
if not self.moving_breaks_hive(cell)
)
@property
def valid_placements(self) -> Iterator[Cell]:
"""
Iterator over all valid placements.
Expects at least one piece to be already placed
"""
return (
cell
for cell in self.cells_around_hive
if self.neighbors_only_my_pieces(cell)
)
@property
def valid_moves(self) -> Iterator[Move]:
"""Iterator over all valid moves."""
mapping = {
PieceKind.Ant: self.ants_moves,
PieceKind.Queen: self.queens_moves,
PieceKind.Beetle: self.beetles_moves,
PieceKind.Grasshopper: self.grasshoppers_moves,
PieceKind.Spider: self.spiders_moves,
}
if self.myMove == 1:
return map(
functools.partial(Move, PieceKind.Queen, None),
self.valid_placements,
)
if 2 <= self.myMove <= 3:
return map(
functools.partial(Move, PieceKind.Ant, None),
self.valid_placements,
)
place_iter = (
Move(piece, None, cell)
for cell, piece in product(self.valid_placements, self.my_placable_pieces)
)
move_iter = (
move
for cell, piece in self.my_movable_pieces
for move in mapping[piece.kind](cell)
)
return chain(place_iter, move_iter) if self.myMove >= 4 else place_iter
@property
def cells_around_hive(self) -> set[Cell]:
"""Set of all cells around the hive."""
return {
neighbor
for cell in self._board
for neighbor in self.empty_neighboring_cells(cell)
}
def move(self) -> MoveBrute:
"""
Return a best move for the current self.board.
Has to first properly initialize self._board.
Format:
[piece, oldP, oldQ, newP, newQ] - move from (oldP, oldQ) to (newP, newQ)
[piece, None, None, newP, newQ] - place new at (newP, newQ)
[] - no move is possible
*Note: the API has to stay this way to be compatible with Brute*
"""
end = time.perf_counter() + 0.95
self._board = convert_board(self.board)
self.__cycles_need_update = True
if self.myMove == 0:
if not self._board:
return Move(PieceKind.Spider, None, (3, 6)).to_brute(self.upper)
placement = choice(list(self.cells_around_hive))
return Move(PieceKind.Spider, None, placement).to_brute(self.upper)
if TEST or not self.tournament:
possible_moves = list(self.valid_moves)
return choice(possible_moves).to_brute(self.upper) if possible_moves else []
nodes = [Node(move, self) for move in self.valid_moves]
if not nodes:
return []
best, depth = self.minimax(nodes, end)
global evaluated, cache_hits, updates, found_cycles, duplicates, removed
print(f"Searched to depth {depth} ({evaluated} pos): {best.score}")
evaluated = 0
print(f"Cache size: {len(self.__cached_cycles)}")
print(f"Cache hits: {cache_hits} of {updates}")
print(f"Found cycles: {found_cycles}")
print(f"Duplicates: {duplicates}")
print(f"Removed: {removed}")
return best.move.to_brute(self.upper)
def minimax(self, nodes: list[Node], end: float) -> tuple[Node, int]:
"""Run the minimax algorithm on the list of nodes return the best move."""
best = nodes[0]
depth = 0
for depth in count():
if time.perf_counter() > end:
break
for node in nodes:
if not node.next_depth(self, end, target_player=self.upper):
return max(nodes), depth
if depth <= 2:
limit = len(nodes)
elif depth <= 5:
limit = 5
else:
limit = 2
win_moves = (node for node in nodes if node.state == State.WIN)
win = next(win_moves, None)
if win:
return win, depth
nodes.sort(reverse=True)
nodes = list(
islice((node for node in nodes if node.state != State.LOSS), limit),
)
if not nodes:
break
best = max(nodes)
return best, depth
def moving_breaks_hive(self, cell: Cell) -> bool:
"""Check if moving the given piece breaks the hive into parts."""
if len(self[cell]) > 1:
return False
neighbor_groups = self.neighbor_groups(cell)
if neighbor_groups == 1:
return False
in_cycle = self.is_in_cycle(cell)
return neighbor_groups != 2 if in_cycle else True
def queens_moves(self, queen: Cell) -> Iterator[Move]:
"""
Return iterator over all valid moves for the queen.
Queen can move one step in any direction.
"""
with lift_piece(self, queen) as piece:
assert piece.kind == PieceKind.Queen, f"{piece} at {queen} is not a Queen"
move = functools.partial(Move, PieceKind.Queen, queen)
yield from map(move, self.valid_steps(queen, can_leave_hive=True))
def ants_moves(self, ant: Cell) -> Iterator[Move]:
"""
Return an iterator over all valid moves for the ant.
Ant can move any number of steps, but always has to stay right next
to the hive.
"""
with lift_piece(self, ant) as piece:
assert piece.kind == PieceKind.Ant, f"{piece} at {ant} is not an Ant"
def next_cells(cell: Cell) -> Iterator[Cell]:
return (
neighbor
for neighbor in self.empty_neighboring_cells(cell)
if self.can_move_to(cell, neighbor)
)
move = functools.partial(Move, PieceKind.Ant, ant)
visited = {ant}
queue = deque(next_cells(ant))
while queue:
current = queue.popleft()
if current in visited:
continue
visited.add(current)
yield move(current)
queue.extend(next_cells(current))
def beetles_moves(self, beetle: Cell) -> Iterator[Move]:
"""
Return an iterator over all valid moves for the beetle.
Beetle can make one step in any direction, while also being able to climb
on top of other pieces.
"""
with lift_piece(self, beetle) as piece:
assert (
piece.kind == PieceKind.Beetle
), f"{piece} at {beetle} is not a Beetle"
move = functools.partial(Move, PieceKind.Beetle, beetle)
yield from map(move, filter(self.has_neighbor, self.neighbors(beetle)))
def grasshoppers_moves(self, grasshopper: Cell) -> Iterator[Move]:
"""
Return an iterator over all valid moves for the grasshopper.
Grasshopper can jump in any direction in straght line, but always has to
jump over at least one other piece.
"""
with lift_piece(self, grasshopper) as piece:
assert (
piece.kind == PieceKind.Grasshopper
), f"{piece} at {grasshopper} is not a Grasshopper"
move = functools.partial(Move, PieceKind.Grasshopper, grasshopper)
# for each direction
for dp, dq in DIRECTIONS:
# start at grasshopper's position
current_cell = grasshopper
skipped = False
# move in that direction until edge of board
while True:
p, q = current_cell
current_cell = (p + dp, q + dq)
if not self.in_board(current_cell):
break
# if tile is empty and
# if something was skipped, yield move
# else try different direction
if self.is_empty(current_cell):
if skipped:
yield move(current_cell)
break
# if tile is not empty, skip the piece
skipped = True
def spiders_moves(self, spider: Cell) -> Iterator[Move]:
"""
Return an iterator over all valid moves for the spider.
Spider can move only exactly three steps, while staying right next
to the hive.
"""
with lift_piece(self, spider) as piece:
assert (
piece.kind == PieceKind.Spider
), f"{piece} at {spider} is not a Spider"
move = functools.partial(Move, PieceKind.Spider, spider)
visited: set[Cell] = set()
stack = [spider]
for _ in range(3):
next_stack: list[Cell] = []
for item in stack:
visited.add(item)
next_stack.extend(
neighbor
for neighbor in self.valid_steps(item)
if neighbor not in visited
)
stack = next_stack
if not stack:
break
yield from map(move, stack)
def neighboring_cells_unchecked(self, cell: Cell) -> Iterator[Cell]:
"""Return an iterator over cells neighboring (p,q), without bound checking."""
p, q = cell
return ((p + dp, q + dq) for dp, dq in DIRECTIONS)
def neighboring_cells(self, cell: Cell) -> Iterator[Cell]:
"""Return an iterator over all cells neighboring (p,q)."""
return filter(self.in_board, self.neighboring_cells_unchecked(cell))
def empty_neighboring_cells(self, cell: Cell) -> Iterator[Cell]:
"""Return an iterator over all cells neighboring (p,q) that are empty."""
return filter(self.is_empty, self.neighboring_cells(cell))
def neighbors(self, cell: Cell) -> Iterator[Cell]:
"""Return an iterator over all cells neighboring (p,q) that aren't empty."""
return filter(self.isnt_empty, self.neighboring_cells_unchecked(cell))
def valid_steps(
self,
cell: Cell,
*,
can_leave_hive: bool = False,
) -> Iterator[Cell]:
"""
Return an iterator over all cells reachable from (p,q).
For more details see `can_move_to`.
"""
return (
neighbor
for neighbor in self.empty_neighboring_cells(cell)
if self.can_move_to(
cell,
neighbor,
can_leave_hive=can_leave_hive,
)
)
def neighbor_groups(self, cell: Cell) -> int:
"""Return the number of groups around the given cell."""
neighbors = self.neighboring_cells_unchecked(cell)
first = next(neighbors)
groups = 0
in_group = first in self._board
for neighbor in neighbors:
if neighbor in self._board:
in_group = True
elif in_group:
in_group = False
groups += 1
if in_group and first not in self._board:
groups += 1
return groups
def update_cycles(self) -> None:
"""
Find all cycles in the hive.
Runs a DFS from the given cell marking the cells visited. When already
cell is encountered second time, a cycle is detected. If the length of the cycle
is more than 2 (trio of neighboring cells), the cycle is returned.
"""
def collect_path(
cell: Cell, visited_from: dict[Cell, Cell | None]
) -> list[Cell]:
"""Collect a path from the given cell."""
path = [cell]
while path[-1] in visited_from:
new = visited_from[path[-1]]
if not new:
break
path.append(new)
return path
def find_cycle(start: Cell) -> set[Cell] | None:
"""Try find a cycle in the hive."""
stack = [start]
visited_from: dict[Cell, Cell | None] = {start: None}
while stack:
new_stack = []
for cell in stack:
for neighbor in self.neighbors(cell):
if neighbor not in visited_from:
new_stack.append(neighbor)
visited_from[neighbor] = cell
continue
cell_visited_from = visited_from[cell]
if not cell_visited_from or cell_visited_from == neighbor:
continue
part1 = collect_path(neighbor, visited_from)
part2 = collect_path(cell, visited_from)
last = None
while part1[-1] == part2[-1]:
part1.pop()
last = part2.pop()