Я хочу перевести этот код, чтобы он был более читабельным, но когда я попробовал, он не работает. Он работает в оригинальной версии, но не работает во второй.
Я пытался таким образом.
down, up = [(+1, -1), (+1, +1)], [(-1, -1), (-1, +1)]
length = board.get_length()
piece = board.get(row, col)
if piece:
for (x, y) in down:
if (0 <= (row + x) < length) and (0 <= (col + y) < length) and board.is_free(row + x, col + y):
bottom = [main.deindexify(row + x, col + y)]
# bottom = [main.deindexify(row + x, col + y) for (x, y) in down \
# if (0 <= (row + x) < length)
# and (0 <= (col + y) < length) \
# and board.is_free(row + x, col + y)]
for (x, y) in up:
if (0 <= (row + x) < length) and (0 <= (col + y) < length) and board.is_free(row + x, col + y):
top = [main.deindexify(row + x, col + y)]
# top = [main.deindexify(row + x, col + y) for (x, y) in up \
# if (0 <= (row + x) < length) \
# and (0 <= (col + y) < length) \
# and board.is_free(row + x, col + y)]
if piece.is_king():
return sorted(bottom + top)
else:
if piece.is_black():
return sorted(bottom)
else:
if is_sorted:
return sorted(top)
else:
if piece.is_king():
return bottom + top
else:
if piece.is_black():
return bottom
else:
return top
# return (sorted(bottom + top) if piece.is_king() else \
# (sorted(bottom) if piece.is_black() else sorted(top))) \
# if is_sorted else (bottom + top if piece.is_king() else \
# (bottom if piece.is_black() else top))
return []
И это ошибка:
line 61, in get_moves
return sorted(bottom)
UnboundLocalError: local variable 'bottom' referenced before assignment
Это оригинальная версия.
down, up = [(+1, -1), (+1, +1)], [(-1, -1), (-1, +1)]
length = board.get_length()
piece = board.get(row, col)
if piece:
bottom = [main.deindexify(row + x, col + y) for (x, y) in down \
if (0 <= (row + x) < length) \
and (0 <= (col + y) < length) \
and board.is_free(row + x, col + y)]
top = [main.deindexify(row + x, col + y) for (x, y) in up \
if (0 <= (row + x) < length) \
and (0 <= (col + y) < length) \
and board.is_free(row + x, col + y)]
return (sorted(bottom + top) if piece.is_king() else \
(sorted(bottom) if piece.is_black() else sorted(top))) \
if is_sorted else (bottom + top if piece.is_king() else \
(bottom if piece.is_black() else top))
return []
Может кто-нибудь объяснить мне, как читать этот код и переводить его, чтобы я мог рефакторизовать остальную часть кода?