Skip to content

Commit efd8513

Browse files
committed
Add highlighted squares feature
1 parent 5d42377 commit efd8513

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/fentoimage/boardgen.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,23 @@ def _init_image(self):
130130
self.image = Image.new(mode="RGB", size=(size, size))
131131
self.draw = ImageDraw.Draw(self.image)
132132

133-
def _render_square_background(self, x, y):
133+
def _get_square_at(self, x, y):
134+
# since chess.SQUARES starts at a1
135+
return chess.SQUARES[x + (7 - y) * 8]
136+
137+
def _render_square_background(self, x, y, highlighted_squares=()):
134138
rectx = x * self.square_size
135139
recty = y * self.square_size
136140
colors = self.square_config.color
141+
highlight_colors = self.square_config.highlight_color
142+
143+
fill_color = colors[(x + y) % 2]
144+
if self._get_square_at(x, y) in highlighted_squares:
145+
fill_color = highlight_colors[(x + y) % 2]
137146

138147
self.draw.rectangle(
139148
(rectx, recty, rectx + self.square_size, recty + self.square_size),
140-
fill=colors[(x + y) % 2],
149+
fill=fill_color,
141150
)
142151

143152
def _render_square_location(self, x, y):
@@ -171,19 +180,18 @@ def _render_piece(self, x, y):
171180
rectx = x * self.square_size
172181
recty = y * self.square_size
173182

174-
# since chess.SQUARES starts at a1
175-
square = chess.SQUARES[x + (7 - y) * 8]
183+
square = self._get_square_at(x, y)
176184
piece = self.board.piece_at(square)
177185
if piece is not None:
178186
piece_image = self.piece_drawer.render(piece)
179187
self.image.paste(piece_image, (rectx, recty), piece_image)
180188

181-
def render(self):
189+
def render(self, *highlighted_squares: chess.Square):
182190
self._init_image()
183191

184192
for x in range(8):
185193
for y in range(8):
186-
self._render_square_background(x, y)
194+
self._render_square_background(x, y, highlighted_squares)
187195
if self.text_config.enabled:
188196
self._render_square_location(x, y)
189197
self._render_piece(x, y)
@@ -192,6 +200,13 @@ def render(self):
192200

193201

194202
if __name__ == "__main__":
203+
from timeit import default_timer as timer
204+
195205
fen = "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2"
196-
image = FenToImage(fen, Config()).render()
206+
207+
start = timer()
208+
image = FenToImage(fen, Config()).render(chess.C7, chess.C5)
209+
end = timer()
210+
211+
print("rendered in", end - start, "seconds")
197212
image.show()

0 commit comments

Comments
 (0)