Esempio n. 1
0
    def from_fen(cls, fen_str):
        # Separate the 6 components
        board_str, active_colour_str, castling_str, en_passant_str,\
           half_move_str, full_move_str = fen_str.strip().split(' ')

        position = Position()

        # Construct the board
        board = tuple()
        for rank_str in board_str.split('/'):
            rank = tuple()
            for piece_str in rank_str:
                if piece_str in '12345678':
                    # Blanks
                    rank += (None,) * int(piece_str)
                else:
                    # Piece
                    piece_colour = WHITE if piece_str.isupper() else BLACK
                    rank += (cls.mappings[piece_str.upper()](piece_colour),)
            board = (rank,) + board

        # Rest of Properties
        position.board = board
        position.active_colour = WHITE if active_colour_str=='w' else BLACK
        position.castling = '' if castling_str is '-' else castling_str
        position.en_passant = None if en_passant_str=='-' else get_coord_from_rank_file(en_passant_str)
        position.half_move = int(half_move_str)
        position.full_move = int(full_move_str)

        return position
Esempio n. 2
0
def new_game(board_str = None):
    """Creates a new game based on text representation"""
    mappings = {'R': Rook, 'N': Knight, 'B': Bishop, 'Q': Queen, 'K': King, 'P': Pawn}

    position = Position()
    if board_str is None:
        # White plays North
        board_str = (' rnbqkbnr\n' #8
                     ' pppppppp\n' #7
                     ' ........\n' #6
                     ' ........\n' #5
                     ' ........\n' #4
                     ' ........\n' #3
                     ' PPPPPPPP\n' #2
                     ' RNBQKBNR')  #1
                     # abcdefgh

    # Permute the board so that Top left become bottom left
    board_str = board_str.replace(' ', '').replace('\n','')
    ranks = reversed([board_str[i:i+8] for i in range(0, 64, 8)])
    board_str = ''.join(ranks)

    board = ()
    rank = ()
    for piece in board_str:
        if piece == '.':
            rank += (None,)
        elif piece.isupper():
            rank += (mappings[piece.upper()](WHITE), )
        elif piece.islower():
            rank += (mappings[piece.upper()](BLACK), )
        if len(rank) == 8:
            board += (rank,)
            rank = ()

    position.board=board
    return position