-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_jack_drawing.py
305 lines (249 loc) · 8.95 KB
/
generate_jack_drawing.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
#!/usr/bin/env python
import os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
OUTPUT_CLASS = 'DrawSprites'
PIECES = ['Pawn', 'Bishop', 'Knight', 'Rook', 'Queen', 'King']
SPRITES_DIR = os.path.join(CURRENT_DIR, "sprites/")
WHITE = '0'
BLACK = '1'
def strTo16bitInt(number, big_endian=True):
"""
>>> strTo16bitInt('0000000000000011', big_endian=False)
-16384
>>> strTo16bitInt('0000000000000001', big_endian=False)
-32768
>>> strTo16bitInt('1000000000000010', big_endian=False)
16385
>>> strTo16bitInt('0100000000000000')
16384
"""
assert len(number) == 16, "Number given is >16 characters: %s" % number
if not big_endian:
number = number[::-1]
negative = True if number[0] == '1' else False
num = int(number, 2)
if negative:
num = num - 2**16
return num
BITMAP_TEMPLATE = """
%s void %s(int location) {
var int memAddress;
let memAddress = 16384 + location;
do Memory.poke(memAddress+0, %d);
do Memory.poke(memAddress+32, %d);
do Memory.poke(memAddress+64, %d);
do Memory.poke(memAddress+96, %d);
do Memory.poke(memAddress+128, %d);
do Memory.poke(memAddress+160, %d);
do Memory.poke(memAddress+192, %d);
do Memory.poke(memAddress+224, %d);
do Memory.poke(memAddress+256, %d);
do Memory.poke(memAddress+288, %d);
do Memory.poke(memAddress+320, %d);
do Memory.poke(memAddress+352, %d);
do Memory.poke(memAddress+384, %d);
do Memory.poke(memAddress+416, %d);
do Memory.poke(memAddress+448, %d);
do Memory.poke(memAddress+480, %d);
return;
}
"""
CLASS_TEMPLATE = """/* File generated by generate_jack_drawing.py script. */
class %(name)s {
%(body)s
}
"""
def generateJackFunction(path, funcName="draw", typeName="function"):
numbers = []
with open(path) as f:
for line in f:
line = line.rstrip()
if line:
numbers.append(strTo16bitInt(line, big_endian=False))
return BITMAP_TEMPLATE % tuple([typeName, funcName] + numbers)
def generateJackDrawingClass():
filepaths = (
os.path.join(SPRITES_DIR, name)
for name in os.listdir(SPRITES_DIR)
if name.endswith(".gen")
)
def _gen(path):
filename = os.path.split(path)[-1]
# drops extension; eg. drawBishopWhite
funcName = "draw" + filename.rsplit('.')[0]
return generateJackFunction(path, funcName)
body = ''.join(map(_gen, filepaths))
output = CLASS_TEMPLATE % {'name': OUTPUT_CLASS, 'body': body}
output_filepath = os.path.join(CURRENT_DIR, OUTPUT_CLASS + '.jack')
with open(output_filepath, 'w') as f:
f.write(output)
class Piece:
"""
Receives a string representing an M x N grid,
where the piece is delimited by 1s; e.g.:
00000
01110
01010 -> notice how 1s form a box around one zero.
01110
00000
In that case, we want the piece to detect that the outside
zeros are the "outside", and the zeros enclosed inside a
contour of 1s (in this case just one zero) represent the
"inside".
And additionally options to query the grid by coordinates
and give it a type if that cell is on the inside or on
the outside.
"""
# Assumes that there's exactly one inside and one outside
# of the piece, for simplicity..
INSIDE = 'i'
OUTSIDE = 'o'
CONTOUR = 'c'
INVERT_MAP = {
WHITE: BLACK,
BLACK: WHITE,
}
def __init__(self, name, contentWW):
self.name = name
self.grid = self._make_grid(contentWW)
self.M = len(self.grid)
self.N = len(self.grid[0])
# A map from a grid cell to its parent.
# You can use this to see if two elements are
# in the same connected component by checking if they
# have the same parent.
self.contour = set()
self.parent = {}
self.visited = set()
self.stack = []
self._detectInsideOutside()
def copy(self):
from copy import deepcopy
return deepcopy(self)
@property
def content(self):
return '\n'.join(map(lambda l: ''.join(l), self.grid))
def flip(self):
# Flips grid, White becomes black and viceversa.
for i in range(self.M):
for j in range(self.N):
x = self.grid[i][j]
self.grid[i][j] = self.INVERT_MAP.get(x, x)
# Enables chaining commands
return self
def paint_inside(self, color):
return self._paint(color, self.INSIDE)
def paint_outside(self, color):
return self._paint(color, self.OUTSIDE)
def _paint(self, color, loc):
for i in range(self.M):
for j in range(self.N):
if self._getPointLocation(i, j) == loc:
self.grid[i][j] = color
return self
def piece_contour(self, i, j):
return (i, j) in self.contour
def is_frontier(self, i, j):
locations = {
self._getPointLocation(*neigh)
for neigh in self._get_neighbours(i, j)
}
# If the point is a neighbour of both inside
# and outside, then it's a frontier point, bridging the
# two sides.
return self.INSIDE in locations and self.OUTSIDE in locations
def _getPointLocation(self, i, j):
# Returns INSIDE / OUTSIDE / CONTOUR location
if i >= self.M or i < 0 or j >= self.N or j < 0:
raise Exception("getPointLocation: Point(%d, %d) required outside "
"(%d, %d)" % (i, j, self.M, self.N))
if self.piece_contour(i, j):
return self.CONTOUR
p = self.parent[(i, j)]
# Assumes that (0, 0) is outside, trivial logic :)
return self.OUTSIDE if p == (0, 0) else self.INSIDE
def __str__(self):
return f'{self.name}'
def _make_grid(self, content):
# Remove empty lines and strip '\n's
return list(
filter(None,
map(
lambda line: list(line.rstrip()),
content.split('\n'))
)
)
def _detectInsideOutside(self):
for i in range(self.M):
for j in range(self.N):
if self.grid[i][j] == BLACK:
self.contour.add((i,j))
else:
self._dfs((i, j))
def _dfs(self, start):
def visit(i, j):
self.visited.add((i, j))
if start in self.visited:
return
# Ignore points on the contour
i, j = start
if self.grid[i][j] == BLACK:
self.contour.add(start)
return
self.stack.append(start)
# Root, he's the parent.
self.parent[start] = start
while len(self.stack):
node = self.stack.pop()
visit(*node)
for neigh in self._get_neighbours(*node):
i, j = neigh
if self.grid[i][j] == BLACK:
self.contour.add(neigh)
elif neigh not in self.visited:
self.stack.append(neigh)
self.parent[neigh] = self.parent[node]
def _get_neighbours(self, i, j):
if i > 0: yield i - 1, j
if i < self.M - 1: yield i + 1, j
if j > 0: yield i, j - 1
if j < self.N - 1: yield i, j + 1
def generateSprite(path, content):
filename = os.path.split(path)[-1]
stem = filename.rsplit('.')[0]
dirname = os.path.dirname(path)
# If it's not a piece, don't do any transformations to the
# content, just send for output.
if stem not in PIECES:
newPath = os.path.join(dirname, f'{stem}.gen')
yield newPath, content
else:
# White piece on white background
yield os.path.join(dirname, f'{stem}WW.gen'), content
# Parses the piece and figures out the contour, its
# inside and its outside part.
piece = Piece(stem, content)
# Black piece on black background
contentBB = piece.copy().flip().content
yield os.path.join(dirname, f'{stem}BB.gen'), contentBB
# White piece on black background
contentWB = piece.copy().flip().paint_inside(WHITE).content
yield os.path.join(dirname, f'{stem}WB.gen'), contentWB
# Black piece on white background
contentBW = piece.copy().paint_inside(BLACK).content
yield os.path.join(dirname, f'{stem}BW.gen'), contentBW
def generateSpritesFromRaw():
filepaths = (
os.path.join(SPRITES_DIR, name)
for name in os.listdir(SPRITES_DIR)
if name.endswith(".raw")
)
for path in filepaths:
with open(path) as f:
content = f.read()
for newPath, newContent in generateSprite(path, content):
with open(newPath, 'w') as f:
f.write(newContent)
if __name__ == "__main__":
generateSpritesFromRaw()
generateJackDrawingClass()