-
Notifications
You must be signed in to change notification settings - Fork 4
/
domino_puzzle.py
1472 lines (1293 loc) · 52.5 KB
/
domino_puzzle.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
import math
import re
import typing
from operator import itemgetter
from collections import defaultdict, deque
from concurrent.futures import Future
from concurrent.futures.process import ProcessPoolExecutor
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import partial
from itertools import chain
from multiprocessing import Pool, Manager
from queue import Empty
from random import Random
from sys import maxsize
from threading import Thread
from deap import base, creator, tools
from deap.algorithms import eaSimple
from deap.tools.support import Statistics
import matplotlib
from networkx.classes.digraph import DiGraph
from networkx.algorithms.shortest_paths.generic import shortest_path
import numpy as np
import hall_of_fame
# Avoid loading Tkinter back end when we won't use it.
from priority import PriorityQueue
matplotlib.use('Agg')
import matplotlib.pyplot as plt # @IgnorePep8
class Cell(object):
def __init__(self, pips):
self.pips = pips
self.domino = None
self.board = None
self.x = None
self.y = None
self.visited = False
def __repr__(self):
return 'Cell({})'.format(self.pips)
def find_neighbour_cells(self, dx, dy, exclude_sibling=True):
x = self.x + dx
y = self.y + dy
board = self.board
if 0 <= x < board.width and 0 <= y < board.height:
neighbour = board[x][y]
if (exclude_sibling and
neighbour is not None and
neighbour.domino is self.domino):
pass
elif neighbour is not None:
yield neighbour
def find_neighbours(self, exclude_sibling=True):
return chain(
self.find_neighbour_cells(0, 1, exclude_sibling=exclude_sibling),
self.find_neighbour_cells(1, 0, exclude_sibling=exclude_sibling),
self.find_neighbour_cells(0, -1, exclude_sibling=exclude_sibling),
self.find_neighbour_cells(-1, 0, exclude_sibling=exclude_sibling))
@property
def partner(self):
domino = self.domino
if domino.head is self:
return domino.tail
return domino.head
def dominates_neighbours(self):
return all(self.pips >= neighbour.pips
for neighbour in self.find_neighbours())
class BoardError(Exception):
pass
class BadPositionError(BoardError):
pass
class MarkerSet:
def __init__(self, marker_text: str, border: int):
self.border = border
self.marker_locations = {} # {(x, y): marker}
if not marker_text.startswith('('):
markers = iter(marker_text.rstrip())
self.marker_pips = dict(zip(markers, markers)) # {marker: pips}
else:
self.marker_pips = {}
for match in re.finditer(r'\((\d+),(\d+)\)(.)', marker_text):
row = int(match.group(1))
column = int(match.group(2))
marker = match.group(3)
self.marker_locations[row+border, column+border] = marker
def check_markers(self, pips_or_marker: str, x: int, y: int) -> str:
new_pips = self.marker_pips.get(pips_or_marker)
if new_pips is None:
return pips_or_marker
self.marker_locations[(x+self.border, y+self.border)] = pips_or_marker
return new_pips
class DiceSet:
def __init__(self, dice_text: str = '', border: int = 0):
self.dice = {} # {(x, y): pips}
for match in re.finditer(r'\((\d+),(\d+)\)(\d+)', dice_text):
row = int(match.group(1))
column = int(match.group(2))
die_pips = int(match.group(3))
self.dice[row+border, column+border] = die_pips
def __repr__(self):
return f'DiceSet({self.text!r})'
@property
def text(self):
return self.crop_text(0, 0)
def crop_text(self, left_border: int, top_border: int):
sorted_dice = sorted(self.dice.items(), key=itemgetter(1))
return ','.join(f'({x-left_border},{y-top_border}){die_pips}'
for (x, y), die_pips in sorted_dice)
def items(self):
return self.dice.items()
def move(self, *positions, show_length=True) -> str:
""" Move a die through a list of positions.
:param positions: ((x, y), ...) the starting position of the die,
followed by one or more positions for it to turn on or stop at.
:param show_length: True if move lengths are included in text
:return: a description of the move described by the positions
"""
move_parts = []
move_count = len(positions)
pips = prev_x = prev_y = 0
for i, (x, y) in enumerate(positions):
if i == 0:
pips = self.dice.pop((x, y))
else:
dx = x - prev_x
dy = y - prev_y
if 0 < dx:
move_part = f'R{dx}'
elif dx < 0:
move_part = f'L{-dx}'
elif 0 < dy:
move_part = f'U{dy}'
else:
move_part = f'D{-dy}'
if not show_length:
move_part = move_part[0]
if i == 1:
move_part = f'{pips}{move_part}'
if i == move_count - 1:
self.dice[x, y] = pips
move_parts.append(move_part)
prev_x = x
prev_y = y
return ''.join(move_parts)
def __getitem__(self, coordinates):
x, y = coordinates
return self.dice.get((x, y))
def __contains__(self, coordinates):
return coordinates in self.dice
class ArrowSet:
directions = dict(r=(1, 0),
u=(0, 1),
l=(-1, 0),
d=(0, -1))
def __init__(self, text: str):
self.text = text
self.positions = [] # [[(x1, y1), (x2, y2), ...], ...]
for match in re.finditer(r'\((\d+),(\d+)\)(([UDLR]\d+)+)', text):
x = int(match.group(1))
y = int(match.group(2))
position = [(x, y)]
moves = match.group(3)
for move_match in re.finditer(r'([UDLR])(\d+)', moves):
direction = move_match.group(1)
distance = int(move_match.group(2))
dx, dy = self.directions[direction.lower()]
x += dx*distance
y += dy*distance
position.append((x, y))
self.positions.append(position)
def __repr__(self):
return f'ArrowSet({self.text!r})'
class Board(object):
@classmethod
def create(cls, state, border=0, max_pips=None):
sections = state.split('\n---\n')
dice_set = arrows = None
marker_text = ''
if len(sections) > 1:
for line in sections[1].splitlines():
if line.startswith('dice:'):
dice_text = line[5:].rstrip()
dice_set = DiceSet(dice_text, border)
elif line.startswith('arrows:'):
arrows_text = line[7:].rstrip()
arrows = ArrowSet(arrows_text)
else:
marker_text = line
marker_set = MarkerSet(marker_text, border)
lines = sections[0].splitlines(False)
lines.reverse()
height = (len(lines)+1) // 2
line_length = height and max(map(len, lines))
width = height and (line_length+1) // 2
lines = [line + ((line_length-len(line)) * ' ') for line in lines]
board = cls(width + 2*border,
height + 2*border,
max_pips=max_pips,
dice_set=dice_set,
arrows=arrows)
degrees = None
for x in range(width):
for y in range(height):
head = lines[y*2][x*2]
head = marker_set.check_markers(head, x, y)
if head not in ' x#':
right_joint = board.get_joint(x, y, x+1, y, border, lines)
upper_joint = board.get_joint(x, y, x, y+1, border, lines)
if right_joint != ' ':
tail = lines[y*2][x*2+2]
tail = marker_set.check_markers(tail, x+1, y)
degrees = 0
elif upper_joint != ' ':
tail = lines[y*2+2][x*2]
tail = marker_set.check_markers(tail, x, y+1)
degrees = 90
else:
tail = None
if tail:
domino = Domino(int(head), int(tail))
domino.rotate(degrees)
board.add(domino, x+border, y+border)
elif board[x+border][y+border] is None:
cell = Cell(int(head))
board.add(cell, x+border, y+border)
board.place_markers(line_length, lines, marker_set)
return board
def __init__(self,
width: int,
height: int,
max_pips: int = None,
dice_set: DiceSet = None,
arrows: ArrowSet = None):
self.width = width
self.height = height
self.dominoes = []
self.max_pips = max_pips
self.dice_set = dice_set
self.arrows = arrows
self.add_count = 0
if max_pips is None:
self.extra_dominoes = []
else:
self.extra_dominoes = Domino.create(max_pips)
self.cells: typing.List[typing.List[typing.Optional[Cell]]] = []
for _ in range(width):
self.cells.append([None] * height)
# Track dominoes that aren't on the regular grid.
self.offset_dominoes = [] # [(domino, x, y)]
self.markers = {}
self.cycles_remaining = 0
def __eq__(self, other):
for x in range(self.width):
for y in range(self.height):
cell1 = self[x][y]
cell2 = other[x][y]
if cell1 is None or cell2 is None:
if cell1 is not cell2:
return False
elif cell1.pips != cell2.pips or cell1.domino != cell2.domino:
return False
return True
def __ne__(self, other):
return not (self == other)
def add(self, item: typing.Union['Domino', Cell], x: int, y: int):
try:
dx, dy = item.direction
self.add(item.head, x, y)
try:
self.add(item.tail, x+dx, y+dy)
except BadPositionError:
# noinspection PyTypeChecker
self.remove(item.head)
raise
self.dominoes.append(item)
if self.extra_dominoes:
self.extra_dominoes.remove(item)
except AttributeError:
if item.x is not None:
# noinspection PyTypeChecker
self.cells[item.x][item.y] = None
if not (0 <= x < self.width and 0 <= y < self.height):
raise BadPositionError(
'Position {}, {} is off the board.'.format(x, y))
if self.cells[x][y] is not None:
raise BadPositionError(
'Position {}, {} is occupied.'.format(x, y))
self.cells[x][y] = item
item.board = self
item.x = x
item.y = y
def get_joint(self,
x1: int,
y1: int,
x2: int,
y2: int,
border: int,
lines: typing.List[str]) -> str:
if y1 == y2:
return ((0 < x2 < self.width-2*border) and
lines[y1 * 2][x1 * 2 + 1] or ' ')
return ((0 < y2 < self.height-2*border) and
lines[y1 * 2 + 1][x1 * 2] or ' ')
def place_markers(self, line_length, lines, marker_set):
self.markers = marker_set.marker_locations
for i, line in enumerate(lines):
for j, c in enumerate(line):
if c != '#':
if not ('0' <= c <= '9'):
continue
if i % 2 == 0 and j % 2 == 0:
continue
head = c if c == '#' else int(c)
right_joint = j + 1 < line_length and lines[i][j + 1] or ' '
upper_joint = i + 1 < len(lines) and lines[i + 1][j] or ' '
neighbours = [] # [(tail, degrees)]
if right_joint != ' ':
tail = lines[i][j + 2]
degrees = 0
neighbours.append((tail, degrees))
if upper_joint != ' ':
tail = lines[i + 2][j]
degrees = 90
neighbours.append((tail, degrees))
for tail, degrees in neighbours:
tail = tail if tail == '#' else int(tail)
domino = Domino(head, tail)
domino.rotate(degrees)
self.offset_dominoes.append((domino, j / 2, i / 2))
# noinspection PyUnusedLocal
@staticmethod
def add_joint(joint: str, x1: int, y1: int, x2: int, y2: int) -> str:
""" Record the joint character between a pair of cells.
:return: an adjusted joint character, in '|- '.
"""
return joint
def remove(self, item):
try:
self.remove(item.head)
self.remove(item.tail)
self.dominoes.remove(item)
self.extra_dominoes.append(item)
except AttributeError:
# noinspection PyTypeChecker
self.cells[item.x][item.y] = None
item.x = item.y = item.board = None
def join(self, cell1, cell2):
domino = Domino(cell1, cell2)
self.dominoes.append(domino)
return domino
def split(self, domino):
self.dominoes.remove(domino)
if self.max_pips is not None:
self.extra_dominoes.append(domino)
domino.head.domino = None
domino.tail.domino = None
def split_all(self):
""" Split all dominoes into separate cells. Useful for Dominosa. """
for domino in self.dominoes[:]:
self.split(domino)
def mutate(self, random, board_type=None, matches_allowed=True):
# Choose number of mutations: 1 is most common, n is least common
max_mutations = len(self.dominoes)
mutation_count = self.pick_mutation_count(max_mutations, random)
is_successful = False
new_board = None
while not is_successful:
# mutation_count = min(mutation_count, 3)
board_type = board_type or Board
neighbours = []
removed = set()
for _ in range(mutation_count):
if neighbours:
domino = random.choice(neighbours)
else:
domino = random.choice(self.dominoes)
removed.add(domino)
neighbours = list(domino.find_neighbours())
new_board = board_type(self.width,
self.height,
max_pips=self.max_pips)
old_dominoes = set(self.dominoes)
old_dominoes.update(self.extra_dominoes)
new_board.extra_dominoes = [domino
for domino in new_board.extra_dominoes
if domino in old_dominoes]
for domino in self.dominoes:
if domino not in removed:
i = new_board.extra_dominoes.index(domino)
new_domino = new_board.extra_dominoes[i]
new_domino.rotate_to(domino.degrees)
new_board.add(new_domino, domino.head.x, domino.head.y)
is_successful = new_board.fill(random,
matches_allowed=matches_allowed)
return new_board
@staticmethod
def pick_mutation_count(max_mutations, random):
n = random.randint(1, (max_mutations + 1) * max_mutations / 2)
mutation_count = 0
dn = max_mutations
while n > 0:
mutation_count += 1
n -= dn
dn -= 1
return mutation_count
def __getitem__(self, x):
return self.cells[x]
def __repr__(self):
return f'{self.__class__.__name__}({self.width}, {self.height})'
def display(self, cropped=False, cropping_bounds=None):
""" Build a display string for the board's current state.
@param cropped: True if blank rows and columns around the outside
should be cropped out of the display.
@param cropping_bounds: a list that will be cleared and then have
[xmin, ymin, xmax, ymax] appended to it. Ignored if it is None.
"""
xmin, xmax, ymin, ymax = self.get_bounds(cropped)
if cropping_bounds is not None:
cropping_bounds[:] = [xmin, ymin, xmax, ymax]
width = xmax-xmin+1
height = ymax-ymin+1
marker_display = self.display_markers()
are_markers_unique = not marker_display.startswith('(')
display = [[' '] * (width*2-1) for _ in range(height*2-1)]
for y in range(height):
for x in range(width):
row = (height - y - 1)*2
col = x*2
cell = self[x+xmin][y+ymin]
cell_display = self.display_cell(cell,
x+xmin,
y+ymin,
are_markers_unique)
display[row][col] = cell_display
if (cell is not None and
cell.domino is not None and
cell.domino.head == cell):
dx, dy = cell.domino.direction
divider = '|' if dx else '-'
display[row-dy][col+dx] = divider
self.adjust_display(display)
main_display = ''.join(''.join(row).rstrip() + '\n' for row in display)
if marker_display:
main_display = f'{main_display}---\n{marker_display}\n'
if self.dice_set:
dice_text = self.dice_set.crop_text(xmin, ymin)
main_display = f'{main_display}---\ndice:{dice_text}\n'
return main_display
def display_markers(self):
if not self.markers:
return ''
marker_values = set(self.markers.values())
if len(marker_values) != len(self.markers):
sorted_markers = sorted(self.markers.items(), key=itemgetter(1, 0))
marker_display = ','.join(f'({x},{y}){die_pips}'
for (x, y), die_pips in sorted_markers)
else:
marker_items = sorted((y, x, name)
for (x, y), name in self.markers.items())
marker_display = ''
for y, x, name in marker_items:
cell = self[x][y]
pips = cell.pips if cell else 'x'
marker_display += f'{name}{pips}'
return marker_display
def display_cell(self, cell, x, y, are_markers_unique):
if cell is None:
display = 'x'
else:
display = str(cell.pips)
if are_markers_unique:
return self.markers.get((x, y), display)
return display
def adjust_display(self, display: typing.List[typing.List[str]]):
""" Adjust the display grid before it gets assembled. """
def get_bounds(self, cropped):
if not cropped:
xmin = ymin = 0
xmax, ymax = self.width - 1, self.height - 1
else:
xmin = self.width + 1
ymin = self.height + 1
xmax = ymax = 0
positions = chain(((cell.x, cell.y)
for domino in self.dominoes
for cell in (domino.head, domino.tail)),
self.markers)
for x, y in positions:
xmin = min(xmin, x)
xmax = max(xmax, x)
ymin = min(ymin, y)
ymax = max(ymax, y)
return xmin, xmax, ymin, ymax
def choose_extra_dominoes(self, random):
""" Iterate through self.extra_dominoes, start at random position.
@return a generator of dominoes.
"""
dominoes = self.extra_dominoes[:]
count = len(dominoes)
start = random.randrange(count)
for i in range(count):
yield dominoes[(i + start) % count]
def choose_and_flip_extra_dominoes(self, random):
""" Iterate through self.extra_dominoes, start at random position.
@return a generator of (domino, is_flipped) pairs. Each domino
is returned twice, with True or False in random order.
"""
for domino in self.choose_extra_dominoes(random):
if domino.head.pips == domino.tail.pips:
yield domino, False
else:
flip_first = random.randint(0, 1)
for j in range(2):
yield domino, flip_first + j == 1
def fill(self, random, matches_allowed=True, reset_cycles=True):
""" Fill any remaining holes in a board with random dominoes.
@param random: random number generator for choosing dominoes
@param matches_allowed: True if neighbouring dominoes can match
@param reset_cycles: True if the infinite loop detection should start
again.
@return: True if the board is now filled.
"""
if reset_cycles:
self.cycles_remaining = 10000
for y in range(self.height):
for x in range(self.width):
if self[x][y] is None:
return self.fill_space(x,
y,
random,
matches_allowed)
return True
def fill_space(self, x, y, random, matches_allowed):
""" Try all possible dominoes and positions starting at x, y. """
rotation = random.randint(0, 3) * 90
for _ in range(4):
try:
choices = self.choose_and_flip_extra_dominoes(
random)
for domino, is_flipped in choices:
if self.cycles_remaining <= 0:
return False
self.cycles_remaining -= 1
domino.rotate_to(rotation)
self.add(domino, x, y)
self.add_count += 1
has_even_gaps = self.hasEvenGaps()
if not has_even_gaps:
self.remove(domino)
break
else:
if is_flipped:
domino.flip()
if not matches_allowed and domino.hasMatch():
pass
else:
if self.fill(random,
matches_allowed,
reset_cycles=False):
return True
self.remove(domino)
except BadPositionError:
pass
rotation = (rotation + 90) % 360
return False
def visit_connected(self, cell):
cell.visited = True
for dx, dy in Domino.directions:
x = cell.x + dx
y = cell.y + dy
if 0 <= x < self.width and 0 <= y < self.height:
neighbour = self[x][y]
if neighbour is not None and not neighbour.visited:
self.visit_connected(neighbour)
def is_connected(self):
domino = None
for domino in self.dominoes:
domino.head.visited = False
domino.tail.visited = False
if domino is None:
return True
self.visit_connected(domino.head)
return all(domino.head.visited and domino.tail.visited
for domino in self.dominoes)
@property
def are_markers_connected(self):
unvisited_markers = set(self.markers)
if not unvisited_markers:
return False
x, y = unvisited_markers.pop()
self.visit_connected_markers(x, y, unvisited_markers)
return not unvisited_markers
def visit_connected_markers(self, x: int, y: int, unvisited_markers: set):
for dx, dy in Domino.directions:
x2 = x + dx
y2 = y + dy
try:
unvisited_markers.remove((x2, y2))
self.visit_connected_markers(x2, y2, unvisited_markers)
except KeyError:
pass
@property
def marker_area(self):
if not self.markers:
return 0
min_x = min_y = max_x = max_y = None
for x, y in self.markers:
if min_x is None:
min_x = max_x = x
min_y = max_y = y
else:
min_x = min(x, min_x)
max_x = max(x, max_x)
min_y = min(y, min_y)
max_y = max(y, max_y)
return (max_x - min_x + 1) * (max_y - min_y + 1)
def has_loner(self):
for domino in self.dominoes:
neighbours = domino.find_neighbours()
has_matching_neighbour = any(domino.isMatch(neighbour)
for neighbour in neighbours)
if not has_matching_neighbour:
return True
return False
def hasMatch(self):
for domino in self.dominoes:
for cell in (domino.head, domino.tail):
for neighbour in cell.find_neighbours():
if neighbour.pips == cell.pips:
return True
return False
def findMatches(self):
matches = {}
for domino in self.dominoes:
for match in domino.findMatches():
matches[(match.x, match.y)] = match
match_coordinates = sorted(matches.keys())
return [matches[coord] for coord in match_coordinates]
def hasEvenGaps(self):
empty_spaces = set()
to_visit = set()
for y in range(self.height):
for x in range(self.width):
if self[x][y] is None:
empty_spaces.add((x, y))
while empty_spaces:
if len(empty_spaces) % 2 != 0:
return False
to_visit.add(empty_spaces.pop())
while to_visit:
x, y = to_visit.pop()
for dx, dy in Domino.directions:
neighbour = (x+dx, y+dy)
try:
empty_spaces.remove(neighbour)
to_visit.add(neighbour)
except KeyError:
pass
return True
class Domino(object):
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
direction_names = 'ruld'
alignment_names = 'hvhv'
@classmethod
def create(cls, max_pips):
dominoes = []
for head_pips in range(max_pips+1):
for tail_pips in range(head_pips, max_pips+1):
dominoes.append(Domino(head_pips, tail_pips))
return dominoes
@classmethod
def get_direction(self, name):
""" Get a direction by name.
@return: dx, dy
"""
index = Domino.direction_names.find(name)
return Domino.directions[index]
def __init__(self, head, tail):
if hasattr(head, 'domino'):
self.check_available(head)
self.check_available(tail)
self.head = head
self.tail = tail
self.direction = (tail.x - head.x, tail.y - head.y)
try:
direction_index = self.directions.index(self.direction)
except ValueError:
msg = (f'Cells are not neighbours: {head.x},{head.y} and '
f'{tail.x},{tail.y}.')
raise ValueError(msg) from None
self.degrees = direction_index*90
else:
self.head = Cell(head)
self.tail = Cell(tail)
self.degrees = 0 # 0, 90, 180, or 270
self.direction = None
self.calculateDirection()
self.head.domino = self
self.tail.domino = self
@staticmethod
def check_available(cell):
if cell.domino is not None:
raise ValueError(f'Cell is not available: {cell.x},{cell.y}.')
def __repr__(self):
return f"Domino({self.head.pips!r}, {self.tail.pips!r})"
def __eq__(self, other):
if not isinstance(other, Domino):
return False
return ((self.head.pips == other.head.pips and
self.tail.pips == other.tail.pips) or
(self.head.pips == other.tail.pips and
self.tail.pips == other.head.pips))
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self.head.pips) ^ hash(self.tail.pips)
def display(self):
return '{}|{}'.format(self.head.pips, self.tail.pips)
def rotate(self, degrees):
self.rotate_to((self.degrees + degrees) % 360)
def rotate_to(self, degrees):
self.degrees = degrees
self.calculateDirection()
if self.head.board:
dx, dy = self.direction
self.head.board.add(self.tail, self.head.x+dx, self.head.y+dy)
def move(self, dx, dy):
x = self.head.x
y = self.head.y
board = self.head.board
board.remove(self)
try:
board.add(self, x+dx, y+dy)
except Exception:
board.add(self, x, y)
raise
def describe_move(self, dx, dy):
direction_name = Domino.describe_direction(dx, dy)
return self.get_name() + direction_name
@staticmethod
def describe_direction(dx, dy):
direction_index = Domino.directions.index((dx, dy))
direction_name = Domino.direction_names[direction_index]
return direction_name
def describe_add(self, x, y):
head, tail = self.head, self.tail
if self.direction[0]:
direction_name = 'h'
if self.direction[0] < 0:
head, tail = tail, head
x -= 1
else:
direction_name = 'v'
if self.direction[1] > 0:
head, tail = tail, head
y += 1
return f'{head.pips}{tail.pips}{direction_name}{x+1}{y+1}'
def describe_remove(self):
dx, dy = self.direction
direction_index = Domino.directions.index((dx, dy))
alignment_name = Domino.alignment_names[direction_index]
return self.get_name() + alignment_name
def get_name(self):
name = '{}{}'.format(self.head.pips, self.tail.pips)
if 90 <= self.degrees <= 180:
name = name[::-1] # reverse
return name
def dominates_neighbours(self):
return (self.head.dominates_neighbours() and
self.tail.dominates_neighbours())
def flip(self):
board = self.tail.board
x, y = self.tail.x, self.tail.y
board.remove(self)
self.rotate(180)
board.add(self, x, y)
pass
def calculateDirection(self):
self.direction = Domino.directions[self.degrees//90]
def find_neighbours(self):
neighbour_cells = self.find_neighbour_cells()
neighbour_dominoes = set(cell.domino for cell in neighbour_cells)
return neighbour_dominoes
def find_neighbour_cells(self):
return chain(self.head.find_neighbours(),
self.tail.find_neighbours())
def isMatch(self, other):
return (self.head.pips == other.head.pips or
self.tail.pips == other.tail.pips or
self.head.pips == other.tail.pips or
self.tail.pips == other.head.pips)
def hasMatch(self):
""" True if either cell matches one of its neighbours.
Slightly different type of matching from isMatch().
"""
for cell in (self.head, self.tail):
for neighbour in cell.find_neighbours():
if neighbour.pips == cell.pips:
return True
return False
def findMatches(self):
matches = []
for cell in (self.head, self.tail):
is_match = False
for neighbour in cell.find_neighbours():
if neighbour.pips == cell.pips:
is_match = True
matches.append(neighbour)
if is_match:
matches.append(cell)
return matches
class GraphLimitExceeded(RuntimeError):
def __init__(self, limit):
super(GraphLimitExceeded, self).__init__(
'Graph size limit of {} exceeded.'.format(limit))
self.limit = limit
@dataclass(frozen=True)
class MoveDescription:
move: str
new_state: str
edge_attrs: dict = None
heuristic: float = 0 # Drive search using A*, leave at zero for Dyjkstra.
# Similar to heuristic, but doesn't control search. Zero iff new_state is solved.
remaining: float = 0
@dataclass
class MoveRequest:
start_state: str
future: Future
class BoardGraph(object):
def __init__(self, board_class=Board, process_count: int = 0):
self.graph = self.start = self.last = self.closest = None
self.min_remaining = None # Minimum steps remaining to find a solution.
self.board_class = board_class
self.process_count = process_count
if process_count > 0:
self.executor = ProcessPoolExecutor(process_count)
else:
self.executor: typing.Optional[ProcessPoolExecutor] = None
self.closest = None
self.is_debugging = False
def walk(self, board, size_limit=maxsize) -> typing.Set[str]:
self.graph = DiGraph()
self.start = board.display(cropped=True)
self.graph.add_node(self.start)
if self.executor is not None:
walker = self.clone()
else:
walker = None
# len of shortest path known from start to a state.
g_score = defaultdict(lambda: math.inf)
max_pips = board.max_pips
start_h = self.calculate_heuristic(board)
g_score[self.start] = 0
pending_nodes = PriorityQueue()
pending_nodes.add(self.start, start_h)
requests: typing.Deque[MoveRequest] = deque()
while pending_nodes:
if size_limit is not None and len(self.graph) >= size_limit:
raise GraphLimitExceeded(size_limit)
state = pending_nodes.pop()
if not self.executor:
moves = self.find_moves(state, max_pips)
self.add_moves(state, moves, pending_nodes, g_score)
else:
request = MoveRequest(
state,
self.executor.submit(walker.find_moves, state, max_pips))
requests.append(request)
while ((not pending_nodes and requests) or
len(requests) > 2*self.process_count):
request = requests.popleft()
state = request.start_state
moves = request.future.result()
self.add_moves(state, moves, pending_nodes, g_score)
return set(self.graph.nodes())
def clone(self) -> 'BoardGraph':
""" Create a smaller copy of this object to pass to worker process. """
return self.__class__(self.board_class)
def find_moves(self, state, max_pips):
board = self.board_class.create(state, border=1, max_pips=max_pips)
moves = list(self.generate_moves(board))
return moves