-
Notifications
You must be signed in to change notification settings - Fork 0
/
palette.py
306 lines (219 loc) · 7.8 KB
/
palette.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
from typing import Optional
def clamp(val, lo=-1, hi=1):
return min(max(val, lo), hi)
# advance functions
def forward(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return direction
def backward(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (-dr, -dc)
def right(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (dc, -dr)
def left(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (-dc, dr)
def forward_left(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
fr, fc = forward(direction)
lr, lc = left(direction)
return (clamp(fr + lr), clamp(fc + lc))
def forward_right(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
fr, fc = forward(direction)
rr, rc = right(direction)
return (clamp(fr + rr), clamp(fc + rc))
def backward_left(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
fr, fc = backward(direction)
lr, lc = left(direction)
return (clamp(br + lr), clamp(bc + lc))
def backward_right(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
br, bc = backward(direction)
rr, rc = right(direction)
return (clamp(br + rr), clamp(bc + rc))
def vertical(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (dr, 0)
def horizontal(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (0, dc)
def north_polarize(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (-1, 0) if dr < 0 else (0, 0)
def south_polarize(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (1, 0) if dr > 0 else (0, 0)
def east_polarize(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (0, 1) if dc > 0 else (0, 0)
def west_polarize(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
dr, dc = direction
return (0, -1) if dc < 0 else (0, 0)
def north(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (-1, 0)
def south(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (1, 0)
def east(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (0, 1)
def west(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (0, -1)
def northeast(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (-1, 1)
def northwest(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (-1, -1)
def southeast(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (1, 1)
def southwest(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (1, -1)
def stay(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return (0, 0)
def die(direction: Optional[tuple[int, int]]) -> Optional[tuple[int, int]]:
return None
ADV_MAP = {
"f": forward,
"b": backward,
"r": right,
"l": left,
"fr": forward_right,
"fl": forward_left,
"br": backward_right,
"bl": backward_left,
"v": vertical,
"h": horizontal,
"np": north_polarize,
"sp": south_polarize,
"ep": east_polarize,
"wp": west_polarize,
"n": north,
"s": south,
"e": east,
"w": west,
"ne": northeast,
"nw": northwest,
"se": southeast,
"sw": southwest,
"-": stay,
"x": die
}
_default_palette = """\
^ n 0 ^ n
v s 0 v s
> e 0 > e
< w 0 < w
. f 0 - #
r r 0 r #
l l 0 l #
f f 0 f #
b b 0 b #
n n 0 n #
s s 0 s #
e e 0 e #
w w 0 w #
R R 1 R #
L L 1 L #
F F 1 F #
B B 1 B #
N N 1 N #
S S 1 S #
E E 1 E #
W W 1 W #
"""
class Palette:
def __init__(self, palette: list[str]):
self.chars = read_palette(palette)
@classmethod
def default(cls):
return cls(_default_palette.splitlines())
def __getitem__(self, key):
return self.chars[key]
def __contains__(self, key):
return key in self.chars
def get(self, key, default=None):
return self.chars.get(key, default)
class PaletteError(Exception):
pass
def parse_character(spec_line: str, idx: int):
return spec_line[idx], idx+1
def parse_advance(spec_line: str, idx: int):
direction = spec_line[idx].lower()
new_idx = idx + 1
if spec_line[idx + 1] != " ":
# digraph direction
direction = spec_line[idx:idx+2].lower()
new_idx = idx + 2
if direction not in ADV_MAP:
raise PaletteError(f"Invalid Advance specification in palette line '{spec_line}'")
return ADV_MAP[direction], new_idx
def parse_reproduce(spec_line: str, idx: int):
repro = spec_line[idx]
if repro not in "01":
raise PaletteError(f"Invalid Reproduce character in palette line '{spec_line}'")
return bool(int(repro)), idx + 1
def parse_transform(spec_line: str, idx: int):
stability = 1
# this is tricky, we can have something like "50 ", with a space
# character. So we really need to look for the *next* token to handle
# any weirdness
space_idx = spec_line[idx + 1:].index(" ") + idx + 1
if spec_line[space_idx + 1] == " ":
# this means that the transform character is a space
# or some other malformation
space_idx += 1
transform = spec_line[idx:space_idx]
if len(transform) > 1:
try:
stability = int(transform[:-1])
if stability < 1:
raise PaletteError(
f"Nonpositive Stability factor in palette line '{spec_line}'"
)
except Exception:
raise PaletteError(
f"Invalid Stability factor in palette line '{spec_line}'"
)
transform = transform[-1]
return (stability, transform), space_idx
def parse_spawn(spec_line: str, idx: int):
spawn = spec_line[idx]
spawn = spec_line[idx].lower()
new_idx = idx + 1
if idx + 1 < len(spec_line):
# digraph direction
spawn = spec_line[idx:idx+2].lower()
new_idx = idx + 2
if spawn not in {"n", "s", "e", "w", "ne", "nw", "se", "sw", "-", "#"}:
raise PaletteError(f"Invalid Spawn character in palette line '{spec_line}'")
spawn = None if spawn == "#" else ADV_MAP[spawn]((0, 0))
return spawn, new_idx
def parse_palette_line(spec_line: str):
def validate_space():
if spec_line[new_idx] != " ":
raise PaletteError(
f"Invalid character at position {new_idx} in palette line '{spec_line}'"
)
try:
char, new_idx = parse_character(spec_line, 0)
validate_space()
adv, new_idx = parse_advance(spec_line, new_idx + 1)
validate_space()
repro, new_idx = parse_reproduce(spec_line, new_idx + 1)
validate_space()
(stability, trans), new_idx = parse_transform(spec_line, new_idx + 1)
validate_space()
spawn, new_idx = parse_spawn(spec_line, new_idx + 1)
if new_idx != len(spec_line):
raise PaletteError(f"Unparsed characters in palette line '{spec_line}'")
except PaletteError:
raise
except Exception:
raise PaletteError(f"Unexpected error extracting fields from palette line '{spec_line}'")
return (char, (adv, repro, trans, spawn, stability))
def read_palette(spec_lines: list[str]) -> dict:
palette = {}
for spec_line in spec_lines:
line = spec_line.rstrip()
if not line:
continue
char, spec = parse_palette_line(line)
if char in palette:
raise PaletteError(f"Duplicate palette key '{char}'")
palette[char] = spec
return palette