Esempio n. 1
0
 def get_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score, moves: str) -> None:
     board = Board(fen)
     game = Game.from_board(board)
     node = game.add_main_variation(Move.from_uci(move))
     current_eval = PovScore(current_score, not board.turn)
     result = self.gen.analyze_position(node, prev_score, current_eval, tier=10)
     self.assert_is_puzzle_with_moves(result, [Move.from_uci(x) for x in moves.split()])
    def export(puzzle, include_first_move=True):
        fen = puzzle.last_pos.fen()
        board = chess.Board(fen)
        game = Game().from_board(board)

        result = PgnExporter.determine_result_tag(board)
        moves = puzzle.positions.move_list()

        if include_first_move:
            first_move = puzzle.last_move
        else:
            # simulate the move (blunder)
            board.push(puzzle.last_move)
            board.clear_stack()
            # take resulting board and create new game
            game = Game().from_board(board)

            first_move = Move.from_uci(moves.pop(0))

        # start the line
        node = game.add_main_variation(first_move)

        # add the rest of the moves
        for m in moves:
            node = node.add_variation(Move.from_uci(m))

        # copy headers from the original game and override result tag
        for h in puzzle.game.headers:
            game.headers[h] = puzzle.game.headers[h]
        game.headers['Result'] = result
        return str(game)
Esempio n. 3
0
    def run(self):
        from chess import Board, Move

        b = Board()
        b.make_move(Move.from_uci("f2f3"))
        b.make_move(Move.from_uci("e7e6"))

        b.make_move(Move.from_uci("g2g4"))
        b.make_move(Move.from_uci("d8h4"))

        assert (b.checkmate())
Esempio n. 4
0
    def get_output(self, headers, board, real_move_uci, moves):
        output_headers = {"FEN": board.fen(), **headers}
        game = pgn.Game(headers=output_headers)

        best_move = moves[0]
        game.add_main_variation(Move.from_uci(best_move["pv"]),
                                comment=self.get_comment(
                                    best_move, real_move_uci))

        for move in moves[1:]:
            game.add_variation(Move.from_uci(move["pv"]),
                               comment=self.get_comment(move, real_move_uci))
        return str(game)
Esempio n. 5
0
 def pv_to_san(self):
     if(self.san_arr == None):
         return ""
     else:
         try:
             pv_san = []
             board = Bitboard(self.san_arr[0])
             moves = self.san_arr[1]
             for uci in moves:
                 move = Move.from_uci(uci)
                 if(move in board.pseudo_legal_moves):
                     pv_san.append(board.san(move))
                     board.push(move)
             if(len(pv_san) > 0):
                 s = ""
                 white_moves = True
                 move_no = (self.no_game_halfmoves//2)+1
                 if(self.no_game_halfmoves % 2 == 1):
                     white_moves = False
                     s += str(move_no)+". ... "
                     move_no += 1
                 for san in pv_san:
                     if(white_moves):
                         s += " "+str(move_no)+". "+san
                         move_no +=1
                     else:
                         s += " "+san
                     white_moves = not white_moves
                 return s
             else:
                 return ""
         except ValueError:
             return ""
Esempio n. 6
0
 def pv_to_san(self):
     if(self.san_arr == None):
         return ""
     else:
         try:
             pv_san = []
             board = Board(self.san_arr[0])
             moves = self.san_arr[1]
             for uci in moves:
                 move = Move.from_uci(uci)
                 if(move in board.pseudo_legal_moves):
                     pv_san.append(board.san(move))
                     board.push(move)
             if(len(pv_san) > 0):
                 s = ""
                 white_moves = True
                 move_no = (self.no_game_halfmoves//2)+1
                 if(self.no_game_halfmoves % 2 == 1):
                     white_moves = False
                     s += str(move_no)+". ... "
                     move_no += 1
                 for san in pv_san:
                     if(white_moves):
                         s += " "+str(move_no)+". "+san
                         move_no +=1
                     else:
                         s += " "+san
                     white_moves = not white_moves
                 return s
             else:
                 return ""
         except ValueError:
             return ""
Esempio n. 7
0
    def search_position(self, board: chess.Board, position: Position) -> None:
        """Recursive tree search with an already loaded position."""
        print('Searching position')
        position_id = typing.cast(int, position.position_id)

        children = self.database.get_child_positions(position_id)
        legal_moves = list(board.legal_moves)

        if len(children) == len(legal_moves):
            # This position is full, recurse on one of the children
            move = select_child_move(children)
            print(f'Making move {move}')
            board.push(Move.from_uci(move))
            self.search_position(board, children[move])
            board.pop()
            print('pop move')
            return

        unanalyzed_moves = [move for move in legal_moves if move.uci() not in children]
        move = unanalyzed_moves[0]
        print(f'Making move {move}')
        board.push(move)
        self.database.insert_position(self.analyze_board(board), ParentRelationship(position_id, move.uci()))
        print('pop move')
        board.pop()
        if len(unanalyzed_moves) == 1:
            print('Back progogate')
Esempio n. 8
0
    def button_release(self, event):
        print(event)
        if event.num == 1:
            self.buttonPressed = False

            before_x = math.floor(event.x / self.height)
            before_a = math.floor(event.y / self.height)

            [start_a,
             start_x] = self.board.get_coordinate_from_square(self.x, self.y)
            [goal_a, goal_x
             ] = self.board.get_coordinate_from_square(before_x, before_a)

            print(start_a + str(start_x) + goal_a + str(goal_x))
            move = Move.from_uci(start_a + str(start_x) + goal_a + str(goal_x))
            print(1)
            if move in self.board.board_pgn.legal_moves:
                self.board.board_pgn.push(move)
            print(2)
            self.board.make_board_to_gui()
            print(3)
            self.board.check_if_right()
            print(4)

        return
Esempio n. 9
0
def read(doc) -> Puzzle:
    board = Board(doc["fen"])
    node = Game.from_board(board)
    for uci in doc["moves"]:
        move = Move.from_uci(uci)
        node = node.add_main_variation(move)
    return Puzzle(doc["_id"], node.game())
Esempio n. 10
0
def read(doc) -> Puzzle:
    board = Board(doc["fen"])
    node: GameNode = Game.from_board(board)
    for uci in (doc["line"].split(' ') if "line" in doc else doc["moves"]):
        move = Move.from_uci(uci)
        node = node.add_main_variation(move)
    return Puzzle(doc["_id"], node.game(), int(doc["cp"]))
Esempio n. 11
0
 def not_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score) -> None:
     board = Board(fen)
     game = Game.from_board(board)
     node = game.add_main_variation(Move.from_uci(move))
     current_eval = PovScore(current_score, not board.turn)
     result = self.gen.analyze_position( node, prev_score, current_eval, tier=10)
     self.assertIsInstance(result, Score)
Esempio n. 12
0
def check_move():
    def parse_request(agrs):
        #print(request.args)
        piece = request.args.get('piece')
        piece_color = piece[0]
        piece_type = piece[1]
        src = request.args.get('from', default='')
        dst = request.args.get('to', default='')
        promotion = request.args.get('promotion', default='')
        promotion = promotion if (dst[1] == '8' and piece_type == 'P') else ''
        return piece_color, piece_type, src, dst, promotion

    piece_color, piece_type, src, dst, promotion = parse_request(request.args)
    move = Move.from_uci(src + dst + promotion)
    if piece_color != 'w' or move not in board.legal_moves:
        print('*' * 20)
        print(list(board.legal_moves))
        print(move)
        print('*' * 20, 'ilegal move')
        value = 'ilegal'
    else:
        value = 'legal'
        board.push(move)

    return json.dumps({'value': value, 'board': board.fen()})
Esempio n. 13
0
def simple_test(move, sense_square):
    hp = {
        'num_conv': 3,
        'conv_filters': 70,
        'conv_kernel': 3,
        'num_lstm': 1,
        'lstm_size': 250,
        'num_dense': 8,
        'dense_size': 1500,
        'lr': 0.1,
        'momentum': 0.3,
        'batch_size': 128
    }
    model = ChessModel(hp, True, training=False)
    board = ReconBoard()

    # Start of game
    observation = board.get_current_state(board.turn)
    print(np.round(model.get_belief_state(observation), 2))

    board.push(Move.from_uci(move))

    # Turn 1
    observation = board.get_pre_turn_observation()
    print(np.round(model.get_belief_state(observation), 2))
    observation = board.sense(sense_square)
    print(np.round(model.get_belief_state(observation), 2))
Esempio n. 14
0
    def run(self):
        """continuous game """
        pubsub = self._red.pubsub()
        pubsub.subscribe([self.opp_id])

        self.info("Entering in the pubsub")
        for move in pubsub.listen():
            self.info("Incoming message")

            if move['type'] == 'subscribe' and move['data'] == 1:
                self.info("Init message")
                if self._color:
                    while not self._red.get(self._game_id):
                        self.info("Waiting for black")

                    self.info("Black is connected, playing first move")

                    decision, _ = self._engine.go(movetime=2000)
                    self._red.publish(self.own_id, decision.uci())
                    self._board.push(decision)
                    self.info("Move played")

                else:
                    self._red.set(self._game_id, "ready")
                    self.info("Telling white we are ready")

            else:
                self.info("Receiving move")
                self._board.push(Move.from_uci(move['data'].decode('utf8')))
                decision, _ = self._engine.go(movetime=2000)
                self._red.publish(self.own_id, decision.uci())
                self.info("Playing move")
                self._board.push(decision)
Esempio n. 15
0
def async_training(params):

    global board, whose_playing, weights, current_board_features, white_castle_status, black_castle_status

    game = params[0]
    board = params[1]
    whose_playing = params[2]
    weights = params[3]
    current_board_features = params[4]
    white_castle_status = params[5]
    black_castle_status = params[6]

    for expected_move in game:

        get_current_board_features()
        actual_move = get_move_to_be_played(board, whose_playing)
        update_weights(expected_move,
                       board.san(Move.from_uci(str(actual_move))))
        board.push_san(expected_move)

        if whose_playing == chess.WHITE:
            whose_playing = chess.BLACK
        else:
            whose_playing = chess.WHITE

    return [
        weights, current_board_features, white_castle_status,
        black_castle_status
    ]
Esempio n. 16
0
    def on_move(self, data):
        game_id = data.get('game_id', None)
        move_uci = data.get('move', None)

        if game_id is None or move_uci is None:
            raise KeyError('invalid move')

        move = Move.from_uci(move_uci)
Esempio n. 17
0
 def make_move(self, to_cell: Cell):
     promotion = "q" if self.is_promotion(to_cell) else ""
     uci_move = f"{self.gui_board.selected_cell}{to_cell}{promotion}"
     move = Move.from_uci(uci_move)
     if self.board.is_legal(move):
         self.board.push(move)
     self.gui_board.selected_cell.selected = False
     self.gui_board.selected_cell = None
     self.gui_board.update_piece_positions(self.board.board_fen())
Esempio n. 18
0
def get_root(fen, moves):
    board = Board(fen)
    root = Node(fen)
    if moves is not None:
        for move in moves:
            fen = board.fen().split(' ')
            root.previous.append(' '.join(fen[:2]))
            board.push(Move.from_uci(move))
    root.position = board.fen()
    return root
Esempio n. 19
0
    def handle_state_change(self, event):
        board = Board(fen=self.initial_fen)
        for move in event["moves"].split():
            board.push(Move.from_uci(move))
        self.node = Node(fen=board.fen())
        self.my_turn = not self.my_turn

        print(f"My turn? {self.my_turn}")

        if self.my_turn:
            self.make_move()
Esempio n. 20
0
 def __explore_leaves(self, board):
     values = defaultdict(list)
     for move in board.legal_moves:
         board.push(move)
         #score = self.__minimax(board, False, self.DEPTH)
         score = self.__alpha_beta(board, -self.MAX_VAL, self.MAX_VAL,
                                   False, self.DEPTH)
         values[score].append(move.uci())
         board.pop()
     values = sorted(values.items())
     print(values)
     return Move.from_uci(random.choice(values[0][1]))
Esempio n. 21
0
def get_move_to_be_played(board, whose_playing):

    moves_and_target_values = {}

    all_legal_moves = board.legal_moves

    for legal_move in all_legal_moves:

        moves_and_target_values[legal_move] = get_target_value(
            board.san(Move.from_uci(str(legal_move))), board, whose_playing)

    return max(moves_and_target_values,
               key=lambda i: moves_and_target_values[i])
Esempio n. 22
0
def seq_test(move, sense_square):
    model = ChessModel(True, training=True)
    board = ReconBoard()

    observations = []
    observations.append(board.get_current_state(board.turn))

    board.push(Move.from_uci(move))
    observations.append(board.get_pre_turn_observation())
    observations.append(board.sense(sense_square))

    batch = np.asarray([np.asarray(observations)])
    print(np.round(model.belief_state.predict(batch)[0][-1]), 2)
Esempio n. 23
0
    def __init__(self):

        self.castles = {
            ('K', 'e1', 'g1'): Move.from_uci('h1f1'),
            ('K', 'e1', 'c1'): Move.from_uci('a1d1'),
            ('k', 'e8', 'g8'): Move.from_uci('h8f8'),
            ('k', 'e8', 'c8'): Move.from_uci('a8d8'),
        }

        self.castles_reversed  = {
            ('K', 'g1', 'e1'): Move.from_uci('f1h1'),
            ('K', 'c1', 'e1'): Move.from_uci('d1a1'),
            ('k', 'g8', 'e8'): Move.from_uci('f8h8'),
            ('k', 'c8', 'e8'): Move.from_uci('d8a8'),
        }
        self.position = None
        self._start_name = None
Esempio n. 24
0
def is_not_best_material_gain(board, best_move):
    best_move = Move.from_uci(best_move)
    piece_at_target = board.piece_at(best_move.to_square)
    if piece_at_target is None:
        return True

    if len(list(board.legal_moves)) == 1:
        return True

    move_value = piece_at_target.piece_type
    best_legal_value = max([
        board.piece_type_at(move.to_square) or 0
        for move in board.legal_moves
        if move != best_move
    ])
    return best_legal_value >= move_value
Esempio n. 25
0
    def getMove(self, boardState: Board, selectedMove = 0)->Move:
        """
        :param Board boardState: The state of the board
        :return Move: What the AI wants to do in the format (@#@#) [we need to search that location for the piece in order to have a valid command]
        """
        self.engine.position(boardState)    #Pass in the board's current state to the game engine.
        test = self.engine.go(movetime=self.time-selectedMove) #Movetime in milliseconds to generate best move.
        print(test)
        full_move_string = str(test[selectedMove])

        #Old code left in to show what we did
        # part1 = self.findLocPiece(full_move[0:2]) #get the piece from the dictionary
        # move_for_board = part1.upper() +full_move_string
        # print("Being passed into movePiece: %s " % move_for_board)
        # self.movePiece(move_for_board)

        return Move.from_uci(full_move_string)
Esempio n. 26
0
    def _do_move(self, uci, refresh=True):
        move = Move.from_uci(uci)
        if move in self.board.legal_moves or self.edit_mode:
            if self.edit_mode:
                piece = self.get_piece_at_pos(uci)
                if ((piece.isupper() and not self.board.turn)
                        or (piece.islower() and self.board.turn)):
                    self.board.turn = not self.board.turn
                    self.board.push(move)
                    self.board.turn = not self.board.turn
            else:
                self.board.push(move)

            if refresh: self.__refresh_view()
            self.check_status()
        else:
            logger.info('Illegal move!')
Esempio n. 27
0
 def uci(self):
     start = input()
     while start != "uci":
         start = input()
     print("id", end="")
     while True:
         command = input()
         if command == "ucinewgame":
             board = Board()
         elif command.split()[0] == "position":
             fen = command[command.index(
                 "fen") + 3: command.index("moves") - 1]
             moves = command[command.index("moves"):].split()
             if fen == "startpos":
                 fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
             board = Board(fen)
             for move in moves:
                 board.push(Move.from_uci(move))
Esempio n. 28
0
def force_play():

    global board, whose_playing

    final_move = get_move_to_be_played(board, whose_playing)

    final_move = board.san(Move.from_uci(str(final_move)))

    board.push_san(final_move)

    print(board)

    if whose_playing == chess.WHITE:
        whose_playing = chess.BLACK
    else:
        whose_playing = chess.WHITE

    return str(board.fen())
Esempio n. 29
0
def main() -> None:
    sys.setrecursionlimit(10000) # else node.deepcopy() sometimes fails?
    parser = argparse.ArgumentParser(prog='tagger.py', description='automatically tags lichess puzzles')
    parser.add_argument("--verbose", "-v", help="increase verbosity", action="count")
    args = parser.parse_args()
    if args.verbose == 1:
        logger.setLevel(logging.DEBUG)
    mongo = pymongo.MongoClient()
    db = mongo['puzzler']
    puzzle_coll = db['puzzle2']
    tag_coll = db['tag']

    for puzzle in puzzle_coll.find():
        # prev = tag_coll.find_one({"_id":puzzle._id})
        board = Board(puzzle["fen"])
        node = Game.from_board(board)
        for uci in puzzle["moves"]:
            move = Move.from_uci(uci)
            node = node.add_main_variation(move)
        puzzle = Puzzle(puzzle["_id"], node.game())
        tags = cook.cook(puzzle)
        for tag in tags:
            tag_coll.update_one({"_id":puzzle.id},{"$addToSet":{tag: "lichess"}}, upsert = True)
Esempio n. 30
0
def send_move():
    global board, whose_playing

    if len(re.findall('\\bO-O-O\\b', str(request.form['move']))) != 0:

        if whose_playing == chess.WHITE:
            white_castle_status = 'long_castle'
        if whose_playing == chess.BLACK:
            black_castle_status = 'long_castle'

    if len(re.findall('\\bO-O\\b', str(request.form['move']))) != 0 and len(
            re.findall('\\bO-O-O\\b', str(request.form['move']))) == 0:

        if whose_playing == chess.WHITE:
            white_castle_status = 'short_castle'
        if whose_playing == chess.BLACK:
            black_castle_status = 'short_castle'

    board.push_san(str(request.form['move']))

    print(board)
    print('----------------------------------------------')

    final_move = get_move_to_be_played(board, whose_playing)

    final_move = board.san(Move.from_uci(str(final_move)))

    board.push_san(final_move)

    print(board)

    if whose_playing == chess.WHITE:
        whose_playing = chess.BLACK
    else:
        whose_playing = chess.WHITE

    return str(board.fen())
Esempio n. 31
0
    def run(self):
        from chess import Board, Move

        b = Board()
        assert b.to_fen() == "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
        assert len(list(b.gen_pseudo_legal_moves())) == 20
        b.make_move(Move.from_uci("e2e4"))
        assert b.move_number == 1
        assert b.half_move_clock == 1
        assert not b.active_player
        assert b.to_fen() == 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 1 1'
        assert len(list(b.gen_pseudo_legal_moves())) == 20
        b.make_move(Move.from_uci("d7d5"))
        assert b.move_number == 2
        assert b.half_move_clock == 2
        assert b.active_player

        # EN PASSANT
        b = Board("rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3")
        b.make_move(Move.from_uci("e5f6"))
        assert b.to_fen() == "rnbqkbnr/ppp1p1pp/5P2/3p4/8/8/PPPP1PPP/RNBQKBNR b KQkq - 0 3"

        b = Board("rnbqk2r/ppp3pp/3bpP1n/3p4/8/BP3Q2/P1PP1PPP/RN2KBNR b KQkq - 2 6")
        assert Move.from_uci("e8g8") in b.gen_pseudo_legal_moves()
        b.make_move(Move.from_uci("e8g8"))
        assert b.to_fen() == "rnbq1rk1/ppp3pp/3bpP1n/3p4/8/BP3Q2/P1PP1PPP/RN2KBNR w KQ - 3 7"

        b = Board("rnbq1rk1/p1p3pp/3bpP1n/1p1p4/8/BPN2Q2/P1PP1PPP/R3KBNR w KQ b6 0 8")
        b.make_move(Move.from_uci("e1c1"))
        assert b.to_fen() == "rnbq1rk1/p1p3pp/3bpP1n/1p1p4/8/BPN2Q2/P1PP1PPP/2KR1BNR b - - 1 8"

        try:
            b.make_move(Move.from_uci("e1c1"))
        except ValueError:
            pass
        finally:
            assert b.to_fen() == "rnbq1rk1/p1p3pp/3bpP1n/1p1p4/8/BPN2Q2/P1PP1PPP/2KR1BNR b - - 1 8"
Esempio n. 32
0
 def push_uci(self, uci):
     # don't check for legality - it takes much longer to run...
     # self.pc_board.push_uci(uci)
     self.pc_board.push(Move.from_uci(uci))
     self._lcz_push()
Esempio n. 33
0
        return BoardString(str(self.position.fen))

    def initialMove(self):
        '''Special game move to hold starting position.'''

        # FIXME: use iswhite
        start = GameMove(
            self._start_name,
            self.position.fen.full_move,
            self.position.fen.turn == 'w',
            None,
            self.fen,
            None,
            None,
            None,
            None
        )
        return start


if __name__ == '__main__':

    fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
    engine = ChessLibGameEngine()
    engine.newGame(fen)
    move = Move.from_uci('e2e4')
    engine.makeMove(move)

    b = BoardString()
    print b.toFen()