Skip to content

Commit 59b60ea

Browse files
committed
Add square_manhattan_distance and square_knight_distance
1 parent 2f7ada0 commit 59b60ea

1 file changed

Lines changed: 32 additions & 1 deletion

File tree

chess/__init__.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,41 @@ def square_rank(square: Square) -> int:
218218

219219
def square_distance(a: Square, b: Square) -> int:
220220
"""
221-
Gets the distance (i.e., the number of king steps) from square *a* to *b*.
221+
Gets the Chebyshev distance (i.e., the number of king steps) from square *a* to *b*.
222222
"""
223+
if a == b:
224+
return 0;
223225
return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b)))
224226

227+
def square_manhattan_distance(a: Square, b: Square) -> int:
228+
"""
229+
Gets the Manhattan/Taxicab distance (i.e., the number of orthogonal king steps) from square *a* to *b*.
230+
"""
231+
if a == b:
232+
return 0;
233+
return abs(square_file(a) - square_file(b)) + abs(square_rank(a) - square_rank(b))
234+
235+
def square_knight_distance(a: Square, b: Square) -> int:
236+
"""
237+
Gets the Knight distance (i.e., the number of knight moves) from square *a* to *b*.
238+
"""
239+
if a == b:
240+
return 0;
241+
242+
dx = abs(square_file(a) - square_file(b))
243+
dy = abs(square_rank(a) - square_rank(b))
244+
245+
if dx + dy == 1:
246+
return 3
247+
elif dx == dy == 2:
248+
return 4
249+
elif dx == dy == 1:
250+
if 1 << a & BB_CORNERS or 1 << b & BB_CORNERS: # Special case only for corner squares
251+
return 4
252+
253+
m = math.ceil(max(dx / 2, dy / 2, (dx + dy) / 3))
254+
return m + ((m + dx + dy) % 2)
255+
225256
def square_mirror(square: Square) -> Square:
226257
"""Mirrors the square vertically."""
227258
return square ^ 0x38

0 commit comments

Comments
 (0)