Exemplo n.º 1
0
 def __init__(
     self,
     human: bool = False,
     fen: str = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
     pgn: str = '',
     time_limit: float = 15,
     fun: bool = False,
     contempt: int = 3000,
     book: bool = True,
     advancedTC: list = [],
 ):
     if pgn == '':
         self.node = Board(fen)
     else:
         self.node = Board()
         for move in pgn.split():
             try:
                 self.node.push_san(move)
             except Exception:
                 continue
     self.time_limit = time_limit
     if advancedTC:
         self.endpoint = time.time()+advancedTC[0]*60
         self.increment = advancedTC[1]
     else:
         self.endpoint = 0
         self.increment = 0
     self.fun = fun
     self.contempt = contempt
     self.human = human
     self.nodes = 0
     self.advancedTC = advancedTC
     self.hashtable: dict[Hashable, TTEntry] = dict()
     self.inbook = book
Exemplo n.º 2
0
 def find_random_child(self) -> Node:
     """
     Get a random move
     """
     random_move = random.choice(list(Board(self.fen).legal_moves))
     new_board = Board(fen=self.fen)
     new_board.push(random_move)
     return Node(fen=new_board.fen())
Exemplo n.º 3
0
    def __init__(self, fen, moves):
        if fen and fen != "startpos":
            self.board = Board(fen)
        else:
            self.board = Board()

        if moves:
            for move in moves:
                self.board.push_uci(move)
Exemplo n.º 4
0
    def run(self):
        from chess import Board, Move

        b = Board("rnbqkbnr/ppp1pppp/8/1B1p4/4P3/8/PPPP1PPP/RNBQK1NR b KQkq - 1 2")
        assert b.stalemate()
        assert not b.checkmate()

        b = Board("rnb1kbnr/pppp1ppp/4p3/8/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3")
        assert b.stalemate()
        assert b.checkmate()
Exemplo n.º 5
0
def children(fen: str) -> FrozenSet[Node]:
    """
    Get children of a given game state
    """
    board = Board(fen=fen)
    next_moves = []
    for move in board.legal_moves:
        new_board = Board(fen=fen)
        new_board.push(move)
        next_moves.append(Node(fen=new_board.fen()))
    return frozenset(next_moves)
Exemplo n.º 6
0
def get_move(old_node: Node, new_node: Node) -> str:
    """
    Get the UCI of a move given an old and new state
    """
    old_board = Board(fen=old_node.fen)
    for move in old_board.legal_moves:
        temp_board = Board(fen=old_node.fen)
        temp_board.push(move)
        if temp_board.fen() == new_node.fen:
            return move.uci()
    else:
        raise RuntimeError(
            "Trying to make illegal move! " f"{old_node.fen} -> {new_node.fen}"
        )
Exemplo n.º 7
0
	def position(self, inp):
		self.br.write(inp)
		self.board = Board()
		for token in inp.split():
			if token in {'startpos', 'position', 'moves'}:
				continue
			self.board.push_san(token)
Exemplo n.º 8
0
def next_move(count):
    count = int(count) // 2
    fen = request.form['fen']
    if count <= 5:
        move = opening_book_next_move(fen, 'performance.bin')
        if move is not None:
            return move

    # use the c version one
    b = Board(fen)
    if is_endgame(b):
        move = query_end_game_move(b.fen())
        if move != None:
            return move

    if b.turn:
        side = '0'  # white
    else:
        side = '1'
    result = s.run(['./ai/c_modules/main', fen, side], stdout=s.PIPE)
    move = result.stdout.decode('utf-8').split("\n")[-2]

    # board = Board(fen)
    # move = min_f_root(board, -10001, 10001, 4)[1]		# black is the ai, so call min_f
    return move
Exemplo n.º 9
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 ""
Exemplo n.º 10
0
def main(pgn=None):
    times = list()
    wins = losses = draws = 0

    for i in range(10):
        try:
            with open(pgn) as pgn:
                game = pgn_reader.read_game(pgn)
                board = game.board()
        except Exception:
            board = Board()

        white_player = EnginePlayer("White", depth=.01)
        black_player = EnginePlayer("Black", depth=.1)

        start = time.time()
        print("Starting game", i + 1)

        while True:
            # print(board)

            if board.is_game_over():
                if is_white_win(board.result()):
                    wins = wins + 1
                elif is_black_win(board.result()):
                    losses = losses + 1
                else:
                    draws = draws + 1

                handle_score(board)
                break

            white_turn = board.turn

            if white_turn:
                move = white_player.get_next_move(board)
            else:
                move = black_player.get_next_move(board)

            if move is "-":
                exit()

            board.push(move)

        white_player.clean()
        black_player.clean()

        end = time.time()

        diff = (end - start)

        print("Game lasted {:.0f} seconds\n".format(diff))
        times.append(diff)

    engines.clean_all()
    print("Average time per game", numpy.average(times))
    print("Standard deviation for all games", numpy.std(times))
    print("Total wins", wins)
    print("Total losses", losses)
    print("Total draws", draws)
Exemplo n.º 11
0
def foo():
    col = True
    bo = Board('7K/8/k1P5/7p/8/8/8/8 w - -')
    end = True
    while end:
        start = time()
        if col:
            mov = mover(bo, 3, col)
        else:
            mov = move2(bo, 3, col)

            #print(_move)
        if mov == None:
            break
        bo.push(mov)
        print('_______________', col, str(round(time() - start, 4)))
        print('Score ', minimax_score(bo))
        print(bo)

        if bo.is_checkmate():
            print('Checkmate ', col, ' Wins')
            end = False
        elif bo.is_stalemate():
            print('Stalemate')
            end = False

        col = not col
Exemplo n.º 12
0
def better_choice(bo, best_index, moves, col, runs, depth):
    n = int(runs / len(best_index))
    start = time()
    state = Board(bo.fen())
    if col:  #we are maxing
        foo = -np.inf
        for i in best_index:
            move = moves[i]
            state.push(move)
            val = simple_monte(state, depth, n, col)
            print(val)
            if val >= foo:
                best = move
                foo = val
            state.pop()

    else:  # we are min
        foo = np.inf
        for i in best_index:
            move = moves[i]
            state.push(move)
            val = simple_monte(state, depth, n, col)
            print(val)
            if val <= foo:
                best = move
                foo = val
            state.pop()

    print('Monte took :', round(time() - start, 3), ' Seconds - Runs: ', n)

    return best
Exemplo n.º 13
0
def _generate_svg(x, y, previous_positions):
    """
    Generate a single svg for one frame of the animation

    Parameters
    ----------
    x: int
        the current x position of the knight starting from the top left (zero-indexed)
    y: int
        the current y position of the knight starting from the top left (zero-indexed)
    previous_positions: list
        a list of previous positions of the knight, which will be marked with an 'x' symbol in the animation

    Returns
    -------
    str
        the SVG of the current position of the knight with previous steps shown

    """

    # represent the knight on the board
    board = Board(_convert_coord_to_fen(x, y))

    # represent the previous positions of the knight
    squares = SquareSet(
        [square(prev_x, 7 - prev_y) for prev_x, prev_y in previous_positions])

    # generate SVG
    return svg_board(board=board, squares=squares)
Exemplo n.º 14
0
    def get_san(self, message, is_xl=False):
        """Create a chess.board plus a text ready to display on clock."""
        def move(text: str, language: str, capital: bool, short: bool):
            """Return move text for clock display."""
            if short:
                directory = {}
                if language == 'de':
                    directory = {'R': 'T', 'N': 'S', 'B': 'L', 'Q': 'D'}
                if language == 'nl':
                    directory = {'R': 'T', 'N': 'P', 'B': 'L', 'Q': 'D'}
                if language == 'fr':
                    directory = {
                        'R': 'T',
                        'N': 'C',
                        'B': 'F',
                        'Q': 'D',
                        'K': '@'
                    }
                if language == 'es':
                    directory = {
                        'R': 'T',
                        'N': 'C',
                        'B': 'A',
                        'Q': 'D',
                        'K': '@'
                    }
                if language == 'it':
                    directory = {
                        'R': 'T',
                        'N': 'C',
                        'B': 'A',
                        'Q': 'D',
                        'K': '@'
                    }
                for i, j in directory.items():
                    text = text.replace(i, j)
                text = text.replace(
                    '@', 'R')  # replace the King "@" from fr, es, it languages
            if capital:
                return text.upper()
            else:
                return text

        bit_board = Board(message.fen, message.uci960)
        if bit_board.is_legal(message.move):
            if message.long:
                move_text = message.move.uci()
            else:
                move_text = bit_board.san(message.move)
        else:
            logging.warning('[%s] illegal move %s found - uci960: %s fen: %s',
                            self.get_name(), message.move, message.uci960,
                            message.fen)
            move_text = 'er{}' if is_xl else 'err {}'
            move_text = move_text.format(message.move.uci()[:4])

        if message.side == ClockSide.RIGHT:
            move_text = move_text.rjust(6 if is_xl else 8)
        return bit_board, move(move_text, message.lang, message.capital
                               and not is_xl, not message.long)
Exemplo n.º 15
0
 def __init__(self, name):
     self.name = name
     self.visits = 0
     self.total_score = 0
     self.children = []
     self.state = Board()
     self.parent = None
Exemplo n.º 16
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())
Exemplo n.º 17
0
def test_bo(n=20):
    bo = Board()

    for i in range(n):
        bo.push(random_move(bo))

    return bo
Exemplo n.º 18
0
def main():
    c = Board()

    c.set_standard()

    c.set_verbose()

    while True:
        print(c)
        if c.turn:
            print("White, it's your turn.")
        else:
            print("Black, it's your turn.")

        command = input("Enter your move: ")

        if command == 'exit':
            return 0

        elif command == 'log':
            print(c.log())

        elif command == '':
            pass

        else:
            c.parse(command, True)
Exemplo n.º 19
0
def simple_monte(bo, dep, runs, col):
    out = 0
    for k in range(runs):
        state = Board(bo.fen())

        for i in range(dep):
            if state.outcome() == None:
                state.push(choice(list(state.legal_moves)))
            else:
                break

        if state.outcome() == None:
            add = minimax_score(state)
        else:
            if state.outcome() != None:
                if state.outcome().winner == True:
                    add = 100
                elif state.outcome().winner == False:
                    add = -100

            else:
                add = 0

        out += add

    return out / runs
Exemplo n.º 20
0
 def set_current(self):
     fen = self.current.fen()
     board = Board(fen)
     self.displayBoard.board = board
     self.set_castling_rights()
     self.set_turn()
     self.update()
Exemplo n.º 21
0
def board_conv(bo, flip):
    if flip == False:
        bo = np.flip(bo)

    str_bo = ''
    for row in bo:
        zeros = 0
        for num in row:
            if num == 0:
                zeros = zeros + 1
            else:
                if zeros > 0:
                    str_bo = str_bo + str(zeros)
                    zeros = 0

                str_bo = str_bo + conv(num)

        if zeros > 0:
            str_bo = str_bo + str(zeros)

        str_bo = str_bo + '/'

    str_bo = str_bo[:-1]

    return Board(str_bo)
Exemplo n.º 22
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)
Exemplo n.º 23
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"]))
Exemplo n.º 24
0
    def __init__(self):
        super().__init__()
        self.stop_flag = False
        self.halt_flag = False
        self.auto_play = False
        self.edit_mode = False
        self.command_queue = queue.Queue(maxsize=1)

        self.board = Board()
        self.board_view = None
        self.stockfish = StockfishAPI(
            path=f'{os.getcwd()}/stockfish-10-linux/stockfish_10_x64_modern',
            depth=5)

        # Command map
        self.commands = dict(sf=self._play_stockfish_move,
                             rr=self._play_random_move,
                             ff=self._auto_play_fast_forward,
                             psf=self._auto_play_stockfish,
                             pr=self._auto_play_random,
                             re=self._reset_board,
                             rev=self._reverse_move,
                             tt=self._test,
                             ai=self._play_against_ai,
                             si=(lambda: logger.info(self.stockfish.info)))
Exemplo n.º 25
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 test_player_play(player_type):
    board = Board()
    player = get_player(player_type)
    move = player.play(board)
    assert isinstance(move, str)
    assert move in [str(m) for m in list(board.legal_moves)
                    ]  #  Check if move is legal
Exemplo n.º 27
0
def test_n_games(p1: Player,
                 p2: Player,
                 n_games: int,
                 verbose: bool = False) -> List[str]:
    t0 = time()
    results = list()
    for i in range(n_games):
        board = Board()
        game = (Game(p1, p2, board, verbose=verbose) if i %
                2 == 0 else Game(p2, p1, board, verbose=verbose))
        game.play_game()
        outcome = board.outcome().winner
        if outcome is None:
            winner = "tie"
        elif i % 2 == 0 and outcome is True:
            winner = "p1"
        else:
            winner = "p2"
        if verbose and (i + 1) % 2 == 0:
            print(
                f"Finished with {i + 1} games in {(time() - t0) / 60:.3f} mins"
            )
            print(
                f"Player 1: {results.count('p1')} Tied games: {results.count('tie')}\n"
            )
        results.append(winner)
    if verbose:
        print(f"Finished in {(time() - t0)/60:.3f} mins")
    return results
Exemplo n.º 28
0
    def test_get_highest_ranked_move(self):

        random_evaluator = SimpleCNNEvaluator()
        player = ShallowPlayer(random_evaluator)
        board = Board()
        move, score = player.get_highest_ranked_move(board)
        self.assertIsInstance(score, float)
        self.assertIsInstance(move, Move)
Exemplo n.º 29
0
def opening_book_next_move(fen, path):
	b = Board(fen)
	with chess.polyglot.open_reader(path) as reader:
		try:
			entry = reader.choice(b)
			return str(entry.move())
		except IndexError:
			return None
Exemplo n.º 30
0
def create_board(situation: str = "initial") -> Board:
    board = Board()
    if situation == "one_move":
        board = Board(
            fen=
            "r1bqkbnr/1pp1pQpp/p1np4/8/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4")
    elif situation == "mate_in_two":
        board = Board(
            fen=
            "r1bqkbnr/1pp1p1pp/p1np4/8/2B1P3/5Q2/PPPP1PPP/RNB1K1NR w KQkq - 0 4"
        )
    elif situation == "mate_in_one":
        board = Board(
            fen=
            "r1bqkbnr/p1pp1ppp/1pn5/4p3/2B1P3/5Q2/PPPP1PPP/RNB1K1NR w KQkq - 0 4"
        )
    elif situation == "mate_in_two_or_promote":
        board = Board(fen="8/3P2K1/p7/8/7R/6R1/1k6/8 w - - 0 1")
    elif situation == "capture_rook_loses":
        board = Board(fen="2r5/3r2k1/8/8/8/8/5PPP/2R3K1 w - - 0 1")
    elif situation == "ended_game":
        board = Board(
            fen=
            "r1bqkbnr/p1pp1Qpp/1pn5/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4"
        )
    return board