-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarbles.py
executable file
·2338 lines (2003 loc) · 73.4 KB
/
marbles.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
#!/usr/bin/env python3
"""
usage: marbles.py [-h] [--speed SPEED] [--max-speed] [--fps FPS] [--input INPUT] [--output OUTPUT] [--ignore-cache] [--no-display] [--quiet] file
Run a marble simulation. Install `tqdm` for better progress bars and `msgpack` for caching the analysis results.
positional arguments:
file path to the marble program to run
options:
-h, --help show this help message and exit
--speed SPEED simulation speed in ticks/seconds (default is 10)
--max-speed run the simulation at maximum speed
--fps FPS the display refresh rate in frame/seconds (default is 60)
--input INPUT path to the file to use as input bit stream (default is stdin if it is not a tty)
--output OUTPUT path to the file to use as output bit stream (default is stdout if it is not a tty)
--ignore-cache ignore the cache even if it exists (enabled by default when msgpack is not installed)
--no-display run the simulation without the display at maximum speed (enabled by default when stdout is not a tty)
--quiet do not output any information about the analysis
During the simulation, the following key bindings are used:
- arrows: move around the simulation
- page up / page down: scroll faster up and down
- i: increase simulation speed (use 5 times for a 10x factor)
- d: decrease simulation speed (use 5 times for a 10x factor)
- p: pause the simulation
- q: exit the simulation before it terminates
Check the simulation rules at: https://github.com/vxgmichel/marbles
"""
from __future__ import annotations
import gzip
import bisect
import contextlib
import hashlib
from collections import deque
import io
import enum
import heapq
import math
import os
import random
import pathlib
import select
import string
import argparse
import itertools
import functools
import sys
import termios
import time
import tty
from typing import (
IO,
Callable,
Iterator,
Iterable,
NamedTuple,
TYPE_CHECKING,
MutableSequence,
TypeVar,
)
try:
import tqdm # type: ignore
except ImportError:
tqdm = None
try:
import msgpack # type: ignore
except ImportError:
msgpack = None
# Compatibility
try:
math.lcm
except AttributeError:
def lcm(a, b):
return abs(a * b) // math.gcd(a, b)
math.lcm = lambda *args: functools.reduce(lcm, args)
# Progress bar
QUIET = False
if TYPE_CHECKING:
T = TypeVar("T")
@contextlib.contextmanager
def progress_context(desc: str, unit: str, **kwargs):
class Dummy:
def __init__(self) -> None:
self.n = 0
def update(self, x: int) -> None:
self.n += x
if QUIET:
yield Dummy()
return
if tqdm is None:
dummy = Dummy()
try:
print(f"{desc}: ...", end="", flush=True, file=sys.stderr)
yield dummy
except BaseException as exc:
print(
f"\b\b\bstopped with {exc.__class__.__name__} ({dummy.n}{unit})",
flush=True,
file=sys.stderr,
)
raise
else:
print(f"\b\b\bdone ({dummy.n}{unit})", flush=True, file=sys.stderr)
return
with tqdm.tqdm(desc=desc, unit=unit, colour="green", **kwargs) as context:
yield context
def show_progress(arg: Iterable[T], desc: str, unit: str, **kwargs) -> Iterable[T]:
if QUIET:
return arg
if tqdm is None:
def gen():
with progress_context(desc=desc, unit=unit, **kwargs) as progress_bar:
for item in arg:
progress_bar.update(1)
yield item
return gen()
return tqdm.tqdm(arg, desc=desc, unit=unit, colour="green", **kwargs)
# Types
if TYPE_CHECKING:
Grid = list[dict[int, str]]
# Data structures
class Depth(enum.IntEnum):
LOWER = 0
UPPER = 1
@property
def inverse(self):
return Depth(not self.value)
class Direction(enum.Enum):
EAST = (0, 1)
SOUTH = (1, 0)
NORTH = (-1, 0)
WEST = (0, -1)
@property
def x(self) -> int:
return self.value[0]
@property
def y(self) -> int:
return self.value[1]
@property
def opposite(self) -> Direction:
return OPPOSITES[self]
OPPOSITES = {
Direction.NORTH: Direction.SOUTH,
Direction.EAST: Direction.WEST,
Direction.SOUTH: Direction.NORTH,
Direction.WEST: Direction.EAST,
}
class Position(NamedTuple):
x: int
y: int
def then(self, d: Direction):
return Position(self.x + d.x, self.y + d.y)
class Marble(NamedTuple):
p: Position
z: Depth
d: Direction
@property
def upper(self) -> bool:
return self.z == Depth.UPPER
@property
def lower(self) -> bool:
return self.z == Depth.LOWER
class EventType(enum.Enum):
START = enum.auto()
UNCONDITIONAL_CLEAR = enum.auto()
CONDITIONAL_CLEAR = enum.auto()
CONTROL = enum.auto()
DISPLAY = enum.auto()
EXIT = enum.auto()
READ_BIT = enum.auto()
WRITE_ZERO = enum.auto()
WRITE_ONE = enum.auto()
class Event:
def __init__(
self,
event_type: EventType,
index: int,
inverted: bool,
neighbor: Position | None = None,
):
self.index = index
self.event_type = event_type
self.inverted = inverted
self.neighbor = neighbor
class Display:
def __init__(
self, positions: set[Position], off_char: str, on_char: str, initial_value: bool
):
self.id: int | None = None
self.initial_value = initial_value
self.positions = positions
self.off_char = off_char
self.on_char = on_char
# X positioning
self.min_x = min(p.x for p in positions)
self.max_x = max(p.x for p in positions)
def extract_info(self):
x_positions: list[int] = [position.x for position in self.positions]
y_positions: list[int] = [position.y for position in self.positions]
assert self.id is not None
return DisplayInfo(
self.id,
self.min_x,
self.max_x,
x_positions,
y_positions,
self.off_char,
self.on_char,
)
class Circuit:
def __init__(
self,
circuit_id: int,
marble: Marble,
positions: list[Position],
events: list[Event],
invertors: list[int],
displays: dict[Position, Display],
replaced_char: str,
):
self.id = circuit_id
self.init_marble = marble
self.positions = positions
self.events = events
self.length = len(self.positions)
self.displays = displays
self.invertors = invertors
self.replaced_char = replaced_char
# X positioning
self.min_x = min(p.x for p in self.positions)
self.max_x = max(p.x for p in positions)
def extract_info(
self,
cycle_start: int,
cycle_length: int,
ticks_to_event_indexes: list[tuple[int, int, bool]],
):
position_indexes: list[int] = [event.index for event in self.events]
event_inverted: list[int] = [event.inverted for event in self.events]
invertors: list[int] = self.invertors
x_positions: list[int] = [position.x for position in self.positions]
y_positions: list[int] = [position.y for position in self.positions]
event_ticks: list[int] = [tick for tick, _, _ in ticks_to_event_indexes]
event_indexes: list[int] = [
event_index for _, event_index, _ in ticks_to_event_indexes
]
event_waiting: list[int] = [waiting for _, _, waiting in ticks_to_event_indexes]
return CircuitInfo(
self.id,
cycle_start,
cycle_length,
self.min_x,
self.max_x,
self.replaced_char,
position_indexes,
event_inverted,
invertors,
x_positions,
y_positions,
event_ticks,
event_indexes,
event_waiting,
)
class Group:
def __init__(
self,
circuits: list[Circuit],
displays: list[Display],
cycle_start: int,
cycle_length: int,
ticks_to_event_indexes: dict[Circuit, list[tuple[int, int, bool]]],
actions: list[tuple[int, Action]],
):
self.circuits = circuits
self.displays = displays
self.cycle_start = cycle_start
self.cycle_length = cycle_length
self.ticks_to_event_indexes = ticks_to_event_indexes
self.actions = actions
def extract_info(self):
return GroupInfo(
self.cycle_start,
self.cycle_length,
self.actions,
)
class ActionType(enum.IntEnum):
START = 0
CLEAR = 1
EXIT = 2
DISPLAY = 3
READ = 4
WRITE = 5
AND = 6
class Action:
def __init__(
self,
action_type: int,
circuit_id: int,
inverted: bool,
extra: int = 0,
extra2: int = 0,
):
self.action_type = action_type
self.circuit_id = circuit_id
self.inverted = inverted
self.extra = extra
self.extra2 = extra2
def dump(self):
return [
self.action_type,
self.circuit_id,
self.inverted,
self.extra,
self.extra2,
]
@classmethod
def load(cls, args: list):
return cls(*args)
@classmethod
def make_start_action(cls, circuit: Circuit, event: Event):
return cls(ActionType.START, circuit.id, event.inverted)
@classmethod
def make_clear_action(cls, circuit: Circuit, event: Event):
return cls(ActionType.CLEAR, circuit.id, event.inverted)
@classmethod
def make_exit_action(cls, circuit: Circuit, event: Event):
return cls(ActionType.EXIT, circuit.id, event.inverted)
@classmethod
def make_display_action(cls, circuit: Circuit, event: Event):
assert event.neighbor is not None
display_id = circuit.displays[event.neighbor].id
assert display_id is not None
return cls(ActionType.DISPLAY, circuit.id, event.inverted, extra=display_id)
@classmethod
def make_read_action(cls, circuit: Circuit, event: Event):
return cls(ActionType.READ, circuit.id, event.inverted)
@classmethod
def make_write_action(cls, circuit: Circuit, event: Event):
value = 1 if event.event_type == EventType.WRITE_ONE else 0
return cls(ActionType.WRITE, circuit.id, event.inverted, extra=value)
@classmethod
def make_and_action(
cls,
circuit: Circuit,
event: Event,
control_circuit: Circuit,
control_event: Event,
):
return cls(
ActionType.AND,
circuit.id,
event.inverted,
extra=control_circuit.id,
extra2=control_event.inverted,
)
def make_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
cache: dict = {},
) -> Callable:
if not cache:
cache.update(
{
ActionType.START: type(self).make_start_callback,
ActionType.CLEAR: type(self).make_clear_callback,
ActionType.EXIT: type(self).make_exit_callback,
ActionType.DISPLAY: type(self).make_display_callback,
ActionType.READ: type(self).make_read_callback,
ActionType.WRITE: type(self).make_write_callback,
ActionType.AND: type(self).make_and_callback,
}
)
return cache[self.action_type](
self, values, display_values, read_bit, write_bit
)
def make_start_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable:
circuit_id = self.circuit_id
if self.inverted:
def callback():
values[circuit_id] ^= 1
else:
def callback():
pass
return callback
def make_clear_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
def callback():
values[circuit_id] = 0
return callback
def make_exit_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
def callback():
if values[circuit_id]:
exit()
return callback
def make_display_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
display_id = self.extra
if self.inverted:
def callback():
values[circuit_id] ^= 1
display_values[display_id] = values[circuit_id]
else:
def callback():
display_values[display_id] = values[circuit_id]
return callback
def make_read_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
if self.inverted:
def callback():
values[circuit_id] ^= 1
if values[circuit_id]:
values[circuit_id] = read_bit()
else:
def callback():
if values[circuit_id]:
values[circuit_id] = read_bit()
return callback
def make_write_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
value = self.extra
if self.inverted:
def callback():
values[circuit_id] ^= 1
if values[circuit_id]:
write_bit(value)
else:
def callback():
if values[circuit_id]:
write_bit(value)
return callback
def make_and_callback(
self,
values: MutableSequence[int],
display_values: MutableSequence[int],
read_bit: Callable[[], int],
write_bit: Callable[[int], None],
) -> Callable | None:
circuit_id = self.circuit_id
control_circuit_id = self.extra
control_circuit_inverted = self.extra2
if self.inverted and control_circuit_inverted:
def callback():
values[circuit_id] ^= 1
values[control_circuit_id] ^= 1
values[circuit_id] &= values[control_circuit_id]
elif self.inverted and not control_circuit_inverted:
def callback():
values[circuit_id] ^= 1
values[circuit_id] &= values[control_circuit_id]
elif not self.inverted and control_circuit_inverted:
def callback():
values[control_circuit_id] ^= 1
values[circuit_id] &= values[control_circuit_id]
elif not self.inverted and not control_circuit_inverted:
def callback():
values[circuit_id] &= values[control_circuit_id]
else:
assert False
return callback
# Characters
MARBLE_UPPER = "●"
MARBLE_LOWER = "○"
MARBLES = MARBLE_LOWER + MARBLE_UPPER
GRID_ON = "█"
GRID_OFF = "┼"
GRIDS = GRID_ON + GRID_OFF
DISPLAY_ON = "▣"
DISPLAY_OFF = "□"
DISPLAYS = DISPLAY_ON + DISPLAY_OFF
DISPLAYS_OR_GRIDS = GRIDS + DISPLAYS
EXIT = "☒"
IO_0 = "◇"
IO_1 = "◆"
IOS = IO_0 + IO_1
TRACKS = {
# 2-connector horizontal
"═": {Direction.EAST, Direction.WEST},
"━": {Direction.EAST, Direction.WEST},
"╒": {Direction.EAST, Direction.WEST},
"╕": {Direction.EAST, Direction.WEST},
"╘": {Direction.EAST, Direction.WEST},
"╛": {Direction.EAST, Direction.WEST},
"╤": {Direction.EAST, Direction.WEST},
"╧": {Direction.EAST, Direction.WEST},
# 2-connector vertical
"║": {Direction.NORTH, Direction.SOUTH},
"┃": {Direction.NORTH, Direction.SOUTH},
"╓": {Direction.NORTH, Direction.SOUTH},
"╖": {Direction.NORTH, Direction.SOUTH},
"╙": {Direction.NORTH, Direction.SOUTH},
"╜": {Direction.NORTH, Direction.SOUTH},
"╟": {Direction.NORTH, Direction.SOUTH},
"╢": {Direction.NORTH, Direction.SOUTH},
# 2-connector 90° turn
"╚": {Direction.NORTH, Direction.EAST},
"╔": {Direction.EAST, Direction.SOUTH},
"╗": {Direction.SOUTH, Direction.WEST},
"╝": {Direction.WEST, Direction.NORTH},
# 4-connector
"╬": {Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST},
}
DIRECTIONS_TO_TRACKS: dict[tuple[Direction, ...], str] = {}
for char, directions in TRACKS.items():
key = tuple(sorted(directions, key=list(Direction).index))
DIRECTIONS_TO_TRACKS.setdefault(key, char)
INVERTORS = "━┃"
CONDITIONAL_CLEAR = {
"╒": Direction.SOUTH,
"╕": Direction.SOUTH,
"╘": Direction.NORTH,
"╛": Direction.NORTH,
"╓": Direction.EAST,
"╖": Direction.WEST,
"╙": Direction.EAST,
"╜": Direction.WEST,
}
CONTROL = {
"╤": Direction.SOUTH,
"╧": Direction.NORTH,
"╟": Direction.EAST,
"╢": Direction.WEST,
}
# Helpers
def get_character(grid: list[dict[int, str]], p: Position) -> str:
if not 0 <= p.x < len(grid):
return " "
return grid[p.x].get(p.y, " ")
def get_directions(grid: Grid, p: Position) -> set[Direction]:
return TRACKS.get(get_character(grid, p), set())
def guess_directions(grid: Grid, p: Position) -> set[Direction]:
result = set(get_directions(grid, p))
for d in Direction:
if d.opposite in get_directions(grid, p.then(d)):
result |= {d}
return result
# Analysis
def create_grid(path: pathlib.Path) -> Grid:
with open(path, "rb") as binary_file:
zipped = binary_file.read(2) == b"\x1f\x8b"
with gzip.open(path, mode="rt") if zipped else open(path) as file:
return [
{i: char for i, char in enumerate(line) if char not in string.whitespace}
for line in show_progress(file, desc="Creating grid", unit=" lines")
]
def extract_marbles(grid: Grid) -> list[Marble]:
with progress_context(desc="Extracting marbles", unit=" marbles") as progress_bar:
marbles = []
# Loop over rows
for i, row in enumerate(grid):
# Loop over columns
for j, char in row.items():
# Not a marble
if char not in MARBLES:
continue
# Get info
p = Position(i, j)
depth = Depth.UPPER if char == MARBLE_UPPER else Depth.LOWER
directions = guess_directions(grid, p)
# Check directions
if len(directions) == 0:
pass
elif len(directions) == 1:
assert False
elif len(directions) == 2:
d1, d2 = sorted(directions, key=list(Direction).index)
marbles.append(Marble(p, depth, d2.opposite))
grid[i][j] = DIRECTIONS_TO_TRACKS[(d1, d2)]
progress_bar.update(1)
elif len(directions) == 3:
assert False
elif len(directions) == 4:
direction = list(Direction)[0]
marbles.append(Marble(p, depth, direction))
progress_bar.update(1)
grid[i][j] = "╬"
return marbles
def build_display_info(grid: list[dict[int, str]], position: Position) -> Display:
c = get_character(grid, position)
if c in DISPLAYS:
initial_value = c == DISPLAY_ON
return Display({position}, DISPLAY_OFF, DISPLAY_ON, initial_value)
assert c in GRID_ON + GRID_OFF
initial_value = c == GRID_ON
queue: list[Position] = [position]
positions = set()
while queue:
p = queue.pop()
if p in positions:
continue
c = get_character(grid, p)
if c not in GRIDS:
continue
positions.add(p)
queue.extend(p.then(d) for d in Direction)
return Display(positions, GRID_OFF, GRID_ON, initial_value)
def build_circuit(
grid: list[dict[int, str]], marble: Marble, circuit_id: int
) -> Circuit:
current_p = marble.p
current_d = marble.d
positions: list[Position] = []
invertors: list[int] = []
events: list[Event] = [Event(EventType.START, 0, False)]
displays: dict[Position, Display] = {}
inverted: bool = False
# Loop over steps
for i in itertools.count():
positions.append(current_p)
# Check character
c = get_character(grid, current_p)
# Get new direction
directions = get_directions(grid, current_p)
if len(directions) == 2:
d1, d2 = directions
assert current_d.opposite in (d1, d2)
new_d = d2 if current_d.opposite == d1 else d1
elif len(directions) == 4 or c in GRIDS:
new_d = current_d
else:
assert False
# Invertors
if c in INVERTORS:
inverted = not inverted
invertors.append(i)
# Conditional clear
if c in CONDITIONAL_CLEAR:
d = CONDITIONAL_CLEAR[c]
neighbor = current_p.then(d)
neighbor_char = get_character(grid, neighbor)
# Connected to control
if neighbor_char in CONTROL:
assert CONTROL[neighbor_char] == d.opposite
events.append(Event(EventType.CONDITIONAL_CLEAR, i, inverted, neighbor))
inverted = False
# Connected to static marble
elif neighbor_char == MARBLE_LOWER:
events.append(
Event(EventType.UNCONDITIONAL_CLEAR, i, inverted, neighbor)
)
inverted = False
elif neighbor_char == MARBLE_UPPER:
pass
# Connected to input
elif neighbor_char in IOS:
events.append(Event(EventType.READ_BIT, i, inverted, neighbor))
inverted = False
# Unsupported
else:
assert False, f"`{c}` + `{neighbor_char}` not supported"
# Control
if c in CONTROL:
d = CONTROL[c]
neighbor = current_p.then(d)
neighbor_char = get_character(grid, neighbor)
# To conditional clear
if neighbor_char in CONDITIONAL_CLEAR:
assert CONDITIONAL_CLEAR[neighbor_char] == d.opposite
events.append(Event(EventType.CONTROL, i, inverted, neighbor))
inverted = False
# To display
elif neighbor_char in DISPLAYS_OR_GRIDS:
events.append(Event(EventType.DISPLAY, i, inverted, neighbor))
displays[neighbor] = build_display_info(grid, neighbor)
inverted = False
# To exit
elif neighbor_char in EXIT:
events.append(Event(EventType.EXIT, i, inverted, neighbor))
inverted = False
# To output
elif neighbor_char in IO_0:
events.append(Event(EventType.WRITE_ZERO, i, inverted, neighbor))
inverted = False
elif neighbor_char == IO_1:
events.append(Event(EventType.WRITE_ONE, i, inverted, neighbor))
inverted = False
# Unrecognized pattern
else:
assert False, f"`{c}` + `{neighbor_char}` not supported"
# Get new position
new_p = current_p.then(new_d)
# Check for stop condition
if new_p == marble.p:
break
current_p = new_p
current_d = new_d
events[0].inverted = inverted
replaced_char = get_character(grid, marble.p)
return Circuit(
circuit_id, marble, positions, events, invertors, displays, replaced_char
)
def build_circuits(grid: Grid, marbles: list[Marble]) -> list[Circuit]:
random.shuffle(marbles)
return [
build_circuit(grid, marble, circuit_id)
for circuit_id, marble in enumerate(
show_progress(marbles, desc="Building circuits", unit=" circuit")
)
]
def build_groups(circuits: list[Circuit]) -> list[list[Circuit]]:
# Build a mapping
mapping: dict[Position, Circuit] = {}
for circuit in show_progress(
circuits,
desc="Prepare mapping for group detection",
unit=" circuit",
):
for event in circuit.events:
if event.neighbor is None:
continue
position = circuit.positions[event.index]
mapping[position] = circuit
# Prepare groups
with progress_context(desc="Detecting groups", unit=" group") as progress_bar:
groups = []
unseen = set(circuits)
# Loop over groups
while unseen:
# Prepare group
current_group = [unseen.pop()]
todo = set(current_group)
# Loop over circuit
while todo:
circuit = todo.pop()
for event in circuit.events:
if event.neighbor is None:
continue
other = mapping.get(event.neighbor)
if other is not None and other in unseen:
todo.add(other)
unseen.discard(other)
current_group.append(other)
# Sort and add group
current_group.sort(key=lambda x: x.id)
groups.append(current_group)
progress_bar.update(1)
return groups
def process_event(
circuit: Circuit,
event_index: int,
waiting_circuits: dict[Position, tuple[Circuit, int]],
) -> tuple[bool, bool, Action | None,]:
event = circuit.events[event_index]
event_type = event.event_type
if event_type == EventType.START:
return False, False, Action.make_start_action(circuit, event)
elif event_type == EventType.UNCONDITIONAL_CLEAR:
return False, False, Action.make_clear_action(circuit, event)
elif event_type == EventType.EXIT:
return False, False, Action.make_exit_action(circuit, event)
elif event_type == EventType.DISPLAY:
return False, False, Action.make_display_action(circuit, event)
elif event_type == EventType.READ_BIT:
return False, False, Action.make_read_action(circuit, event)
elif event_type in (EventType.WRITE_ZERO, EventType.WRITE_ONE):
return False, False, Action.make_write_action(circuit, event)
elif event_type in (EventType.CONDITIONAL_CLEAR, EventType.CONTROL):
assert event.neighbor is not None
if event.neighbor in waiting_circuits:
other_circuit, other_event_index = waiting_circuits[event.neighbor]
other_event = other_circuit.events[other_event_index]
if event_type == EventType.CONTROL:
circuit, other_circuit = other_circuit, circuit
event, other_event = other_event, event
return (
False,
True,
Action.make_and_action(circuit, event, other_circuit, other_event),
)
else:
return True, False, None
else:
assert False
class TickInfo:
def __init__(self, last_tick_info: TickInfo | None, tick_enter: int, waiting: bool):
self.waiting = waiting
self.tick_enter = tick_enter
self.last_tick_info = last_tick_info
self.tick_exit = tick_enter + 1 if not waiting else None
def get_cycle(self) -> int | None:
if self.tick_exit is None:
return None
if self.last_tick_info is None:
return None