def choose_move(self, board):
        # In order to check visits over duration of function
        start_num = self.num_alphabeta
        start_time = time.time()

        # Query opening book if option set
        if self.use_book:
            with open_reader("data/performance.bin") as reader:
                try:
                    entry = reader.weighted_choice(board)
                    time.sleep(1)

                    print(
                        "After considering {} options from the entry book, {} was selected by {} AlphaBetaAI."
                        .format(sum(1 for _ in reader.find_all(board)),
                                entry.move,
                                "White" if self.is_white else "Black"))
                    self.time += time.time() - start_time
                    reader.close()

                    return entry.move

                except IndexError:
                    reader.close()

        # init
        values = []
        best_value = float('-inf')
        alpha = float('-inf')
        beta = float('inf')

        # I am not sure if clearing maintains optimality
        self.transposition_table.clear()

        # randomize moves to allow variance
        moves = list(board.legal_moves)
        random.seed()
        random.shuffle(moves)

        for move in moves:
            board.push(move)

            # Get move value and add to list
            new_val = self.min_value(board, self.depth, alpha, beta)
            values.append(new_val)

            # Update if new max
            best_value = max(best_value, new_val)
            alpha = max(alpha, new_val)

            board.pop()

        # Print and return results
        print("After searching {} nodes, {} was selected by {} AlphaBetaAI.".
              format(self.num_alphabeta - start_num,
                     moves[values.index(best_value)],
                     "White" if self.is_white else "Black"))
        self.time += time.time() - start_time
        return moves[values.index(best_value)]
Beispiel #2
0
    def __init__(self, board, is_player_white):
        self.board = board
        self.is_ai_white = not is_player_white

        with open_reader('data/opening.bin') as reader:
            self.opening_moves = [
                str(entry.move()) for entry in reader.find_all(board)
            ]
    def __init__(self, board, is_player_white):
        self.board = board
        self.is_ai_white = not is_player_white

        with open_reader('C:/Users/vinit/PycharmProjects/CHESSAIPROJECT/ai project/data/opening.bin') as reader:
            self.opening_moves = [
                str(entry.move) for entry in reader.find_all(board)
            ]
Beispiel #4
0
 def get_move_from_opennings(self, board):
     if not ENABLE_OPENING_BOOK:
         return
     with open_reader("data/opennings/bookfish.bin") as reader:
         try:
             entry = reader.choice(board)
             print(entry.move(), entry.weight, entry.learn)
             return entry.move()
         except:
             return None
Beispiel #5
0
    def __init__(self, board, is_player_white):
        self.board = board
        self.is_ai_white = not is_player_white

        with open_reader(
                './data/opening.bin'
        ) as reader:  #here for given board states reader.find_all(board) gives the opening moves
            self.opening_moves = [
                str(entry.move) for entry in reader.find_all(board)
            ]
        print(self.opening_moves)
Beispiel #6
0
    def _get_book_move(self, step):
        bfp = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data',
                           'polyglot', 'Performance.bin')

        with book.open_reader(bfp) as reader:
            es = reader.find_all(self.env.board)
            actions = np.asarray([e.move().uci() for e in es])
            action = None
            if len(actions) > 0:
                if step == 1:
                    action = np.random.choice(actions)
                else:
                    action = actions[0]
            return action
Beispiel #7
0
    async def move(self, ctx, move=''):
        player = self.white if self.white.turn == True else self.black
        if str(ctx.message.author) == str(player.username):
            try:
                move = ctx.message.content[9:]
                self.board.push_san(move)
                self.genBoardImg()
                await ctx.message.channel.send(file=discord.File("board.png"))
                self.swapTurns()
                if self.black.username == "engine":
                    with open_reader('gamebook/games.bin') as reader:
                        opening_moves = [
                            str(entry.move)
                            for entry in reader.find_all(self.board)
                        ]
                    if opening_moves:
                        choice = random.randint(0, len(opening_moves) // 2)
                        move = chess.Move.from_uci(opening_moves[choice])
                        move = chess.Move.from_uci(str(move))
                        self.board.push(move)
                        self.genBoardImg()
                        self.swapTurns()
                        await ctx.message.channel.send(
                            file=discord.File("board.png"))
                    else:
                        print("\n I am thinking...\n")
                        pool = multiprocessing.Pool()
                        #move = pool.map(chessai.alphaBetaRoot(3,self.board,True), range(23))
                        move = chessai.alphaBetaRoot(3, self.board, True)
                        move = chess.Move.from_uci(str(move))
                        self.board.push(move)
                        self.genBoardImg()
                        self.swapTurns()
                        await ctx.message.channel.send(
                            file=discord.File("board.png"))

                if self.board.is_game_over() or self.board.is_checkmate():
                    await ctx.message.channel.send("[*] Game Over.")
                    self.white = None
                    self.black = None
                    self.board = chess.Board()

            except ValueError:
                await ctx.message.channel.send("[!] WARNING: Invalid move!")

        else:
            await ctx.message.channel.send("Not {}'s turn!".format(
                ctx.message.author))
Beispiel #8
0
 def recommend_move():
     """
     Recommend move using by looking up polyglot opening book. If not in book then use stockfish engine.
     """
     try:
         with polyglot.open_reader(
                 "./data/polyglot/performance.bin") as reader:
             main_entry = reader.find(board)
         recom_move = main_entry.move()
     except IndexError:
         engine = uci.popen_engine("./Stockfish/src/stockfish")
         engine.uci()
         engine.position(board)
         # Gets tuple of bestmove and ponder move.
         best_move = engine.go(movetime=ENGINE_MOVETIME)
         recom_move = best_move[0]
         engine.quit()
     return recom_move
Beispiel #9
0
    def __init__(self, call_if_ready, call_to_inform, opening_book):
        super(Analyzer, self).__init__()
        if opening_book:
            self.opening_book = polyglot.open_reader(opening_book)
        else:
            self.opening_book = None
        self.debug = False
        self.set_default_values()
        self.board = chess.Board()

        self.is_working = threading.Event()
        self.is_working.clear()
        self.is_conscious = threading.Condition()
        self.termination = threading.Event()
        self.termination.clear()

        self._call_if_ready = call_if_ready
        self._call_to_inform = call_to_inform
        self._bestmove = chess.Move.null()
Beispiel #10
0
    def __init__(self, call_if_ready, call_to_inform, opening_book):
        super(Analyzer, self).__init__()
        if opening_book:
            self.opening_book = polyglot.open_reader(opening_book)
        else:
            self.opening_book = None
        self.debug = False
        self.set_default_values()
        self.board = chess.Board()

        self.is_working = threading.Event()
        self.is_working.clear()
        self.is_conscious = threading.Condition()
        self.termination = threading.Event()
        self.termination.clear()

        self._call_if_ready = call_if_ready
        self._call_to_inform = call_to_inform
        self._bestmove = chess.Move.null()
Beispiel #11
0
    def __call__(self):
        with opening.open_reader("data/performance.bin") as book:
            moves = [entry.move for entry in book.find_all(self.chess.board)]
            if moves and self.opening_book:
                if self.variation:
                    shuffle(moves)
                phi = lambda x: 1 / (1 + exp(-x)) - 0.5
                move = moves[0]
                self.chess(move)
                sleep(1)
                print(f"""
OPENING MODE
MOVE: {move}
""")
                return move, phi(self.chess.util)
        t = time()
        moves = self.chess.legal_moves()
        if len(list(moves)) == 1:
            move = list(moves)[0]
            self.chess(move)
            return move, self.chess.utility()

        alpha = float('-inf')
        beta = float('inf')
        result = None
        boards = sorted(
            ((copy(self.chess)(move), False, move) for move in moves),
            key=lambda x: x[0].util,
            reverse=self.chess.turn())
        self.count = 0
        if self.chess.turn():
            value = float('-inf')
            for board, urgent, move in boards:
                self.count += 1
                alphabeta_result = self.alphabeta(board, urgent, 1, alpha,
                                                  beta)
                if value <= alphabeta_result:
                    value = alphabeta_result
                    result = move
                alpha = max(value, alpha)
                if alpha >= beta:
                    break
        else:
            value = float('inf')
            for board, urgent, move in boards:
                self.count += 1
                alphabeta_result = self.alphabeta(board, urgent, 1, alpha,
                                                  beta)
                if value >= alphabeta_result:
                    value = alphabeta_result
                    result = move
                beta = min(value, beta)
                if alpha >= beta:
                    break
        if result is None:
            move = 'RESIGN'
        else:
            move = result.uci().upper()
        timer = round(time() - t, 1)
        print(f"""
MOVE: {move}
UTIL: {round(value, 3)}
TIME: {timer} s
NODE: {self.count}
ONCE: {round(timer/self.count*1e3, 3)} ms""")
        self.chess(result)
        return result, value
Beispiel #12
0
def opening_move(board, book_path):
    try:
        return bookloader.open_reader(book_path).find(board).move
    except IndexError:
        return None
    def choose_move(self, board):

        # Query opening book if option set
        if self.use_book:
            with open_reader("data/performance.bin") as reader:
                try:
                    entry = reader.weighted_choice(board)
                    time.sleep(1)

                    print(
                        "After considering {} options from the entry book, {} was selected by {} MinimaxAI."
                        .format(sum(1 for _ in reader.find_all(board)),
                                entry.move,
                                "White" if self.is_white else "Black"))
                    reader.close()

                    return entry.move

                except IndexError:
                    reader.close()

        self.moves += 1

        moves = list(board.legal_moves)
        random.seed()
        random.shuffle(moves)

        # init
        best_move = moves[0]
        self.start = time.time()
        self.transposition_max.clear()
        self.transposition_min.clear()
        print("---------------------------------")

        # iterate through depths, likely will not be surpassed
        for i in range(1, 20):

            # iteration init
            values = []
            best_value = float('-inf')
            alpha = float('-inf')
            beta = float('inf')

            for move in moves:
                board.push(move)

                # Get move value and add to list
                new_val = self.min_value(board, i, alpha, beta)
                values.append(new_val)

                # Update if new max
                best_value = max(best_value, new_val)
                alpha = max(alpha, new_val)

                board.pop()

            # If time limit reached, return
            if time.time() - self.start > self.time_limit:
                print("---------------------------------")
                self.total_depth += i - 1
                return best_move

            # If not reached, update best move
            best_move = moves[values.index(best_value)]
            print("At depth {}, the best move is {}".format(i, best_move))

        print("---------------------------------")
        return best_move