def _cursor_to_position(self, coordinates=None): # WARN: bool((0, 0)) == False, # therefore coordinates or self.cursor == self.cursor y, x = coordinates or self.cursor col, row = (x - self.top_x) // self.step_x, (y - self.top_y) // self.step_y rank = chr(7 - row + ord('0') + 1) file = chr(col + ord('a')) return Position.from_str(file + rank)
def rotate_position(position: Position, times=1): new_pos = deepcopy(position) for _ in range(times): rank, file = new_pos.coordinates new_rank, new_file = 7 - rank, file new_rank, new_file = new_file, new_rank # new_rank, new_file = 7 - file, rank # new_rank = 7 - new_rank new_rank, new_file = chr(7 - new_rank + ord('1')), chr(new_file + ord('a')) new_pos = Position.from_str(new_file + new_rank) return new_pos
def from_fen(cls, fen: str): fen_board, active_side, castling, en_passant, _, _ = fen.split() board = cls() board.player = Color.WHITE if active_side.lower() == 'w' else Color.BLACK board.enemy = Color.BLACK if active_side.lower() == 'w' else Color.WHITE for rank, row in zip(reversed(Rank), fen_board.split('/')): col_i = 0 for char in row: if char.upper() in cls.fen_lookup_table: piece_class = cls.fen_lookup_table[char.upper()] color = Color.WHITE if char.isupper() else Color.BLACK p_file = File.from_str(chr(col_i + ord('a'))) piece = piece_class(color) board[rank][p_file] = piece if char.upper() == 'K': board.kings[color] = Position(rank, p_file) col_i += 1 else: count_empty = int(char) col_i += count_empty board.castling_perms[Color.WHITE] = CastlingPerm.NONE board.castling_perms[Color.BLACK] = CastlingPerm.NONE board.castling_perms[Color.WHITE] |= int('K' in castling) << int(math.log2(CastlingPerm.KING_SIDE)) board.castling_perms[Color.WHITE] |= int('Q' in castling) << int(math.log2(CastlingPerm.QUEEN_SIDE)) board.castling_perms[Color.BLACK] |= int('k' in castling) << int(math.log2(CastlingPerm.KING_SIDE)) board.castling_perms[Color.BLACK] |= int('q' in castling) << int(math.log2(CastlingPerm.QUEEN_SIDE)) if en_passant != '-': board.en_passant_pos = Position.from_str(en_passant) return board
def test_from_str_equal_as_with_normal_init(self): self.assertEqual(Position(Rank.ONE, File.A), Position.from_str('A1')) self.assertEqual(Position(Rank.TWO, File.H), Position.from_str('H2')) self.assertEqual(Position(Rank.EIGHT, File.H), Position.from_str('H8'))