示例#1
0
 def __init__(self, controller="random", customFunction=None):
     # "random", "gp", "alphazero", "*anyother we're planning to implement"
     self.controller = controller
     self.customFunction = customFunction
     # add any other variables as needed
     self.stockfish = Stockfish(
         './stockfish-10-win/Windows/stockfish_10_x64.exe')
示例#2
0
class Bot():
  def __init__(self):
    self.stockfish = Stockfish()

  def acceptable_challenge(self, chall):
    if chall["variant"]["key"] != "standard":
      return False

    if chall["timeControl"]["limit"] > 60:
      return False

    if chall["timeControl"]["increment"] > 0:
      return False

    return True

  def get_move(self, moves):
    b = chess.Board()

    if moves[0] == '': moves = [] 
    for m in moves:
      b.push(chess.Move.from_uci(m))

    if len(list(b.legal_moves)) < 1: return None

    # random move
    if bool(getrandbits(1)): return choice(list(b.legal_moves))

    # stockfish move
    self.stockfish.set_position(moves)

    return self.stockfish.get_best_move()
示例#3
0
 def __initial_game(self):
     # self.parent.withdraw()
     self.parent.destroy()
     self.tabuleiro = ChessMatch.ChessMatch(self.bot_color)
     self.stockfish = Stockfish("./src/cpu/stockfish_20090216_x64")
     self.stockfish.set_skill_level(0)
     self.game_gui = Game(self.tabuleiro, self.stockfish)
示例#4
0
class RandomFish():
    def __init__(self):
        self.stockfish = Stockfish()
        self.board = chess.Board()

    def get_config(self):
        return 'rand0mfish.yml'

    def get_name(self):
        return 'rand0mfish'

    def new_game(self):
        self.board.reset()

    def set_position(self, moves):
        self.board.reset()
        for m in moves:
            self.board.push(chess.Move.from_uci(m))

    def get_move(self):
        # random move
        if bool(getrandbits(1)): return choice(list(self.board.legal_moves))

        # stockfish move
        self.stockfish.set_fen_position(self.board.fen())
        return self.stockfish.get_best_move()
示例#5
0
def Score(fen):
    stockfish = Stockfish("./stockfish_20090216_x64.exe", parameters={
                                                                        "Write Debug Log": "false",
                                                                        "Contempt": 0,
                                                                        "Min Split Depth": 30,
                                                                        "Threads": 1,
                                                                        "Ponder": "false",
                                                                        "Hash": 16,
                                                                        "MultiPV": 1,
                                                                        "Skill Level": 20,
                                                                        "Move Overhead": 30,
                                                                        "Minimum Thinking Time": 20,
                                                                        "Slow Mover": 84,
                                                                        "UCI_Chess960": "false",}
        )
    stockfish.set_fen_position(fen)
    score = stockfish.get_evaluation()
    print(score)


# fen = "2N5/8/2Q5/4k2p/1R6/7P/6P1/7K b - - 4 66"

# engine = init_stockfish_engine()
# print(StockfishScore(fen, engine))
# Score(fen)

# engine.quit()
示例#6
0
class Engine:
    def __init__(self, skill_level):
        parameters = {
            "Write Debug Log": "false",
            "Contempt": 0,
            "Min Split Depth": 0,
            "Threads": 1,
            "Ponder": "false",
            "Hash": 16,
            "MultiPV": 1,
            "Skill Level": skill_level,
            "Move Overhead": 30,
            "Minimum Thinking Time": 20,
            "Slow Mover": 80,
            "UCI_Chess960": "false",
        }
        self.engine = Stockfish("resources/stockfish.exe",
                                parameters=parameters)
        self.engine.set_depth(ENGINE_DEPTH)

    def set_position(self, fen):
        self.engine.set_fen_position(fen)

    def get_move(self, time):
        return self.engine.get_best_move_time(time)
示例#7
0
 def __init__(self, game, level):
     self.game = game
     self.engine = Stockfish('engines/stockfish',
                             parameters={
                                 "Threads": 4,
                                 "Skill Level": level
                             })
示例#8
0
 def __init__(self):
     self.best_move = ''
     self.stockfish = Stockfish(
         "stockfish_14_linux_x64_avx2/stockfish_14_x64_avx2")
     self.positions2 = ""
     self.pos_temp = 0
     self.curr_position = (Fen().start_position_list()).copy()
示例#9
0
    def __init__(self, first: bool, host: str, port: int,
                 skill_level: Optional[int], depth: Optional[int],
                 stockfish: Optional[str]):
        """
        Initialize a player.

        Args:
            first: Is the player going first.
            host: The host of the game.
            port: The port in the host of the game.
            skill_level: Still level for stockfish.
            depth: Depth to search for best move for stockfish.
            stockfish: Path to the stockfish executable to use.
        """
        self.player_turn = first
        self.host = host
        self.port = port
        self.skill_level = skill_level
        self.depth = depth
        self.moves = []
        self.socket = None

        self.stockfish = Stockfish(stockfish or "./stockfish")
        if self.skill_level is not None:
            self.stockfish.set_skill_level(self.skill_level)
        if self.depth is not None:
            self.stockfish.set_depth(self.depth)
示例#10
0
 def test_get_best_move_wrong_position(self):
     wrong_fen = "3kk3/8/8/8/8/8/8/3KK3 w - - 0 0"
     s = Stockfish()
     s.set_fen_position(wrong_fen)
     assert s.get_best_move() in (
         "d1e2",
         "d1c1",
     )
示例#11
0
class GameStockfish(Game):
    """ Represents a game agaisnt a Stockfish Agent."""
    def __init__(self,
                 stockfish,
                 player_color=Game.WHITE,
                 board=None,
                 date=None,
                 stockfish_depth=10):
        super().__init__(board=board, player_color=player_color, date=date)
        if stockfish is None:
            raise ValueError('A Stockfish object or a path is needed.')

        self.stockfish = stockfish
        stockfish_color = not self.player_color

        if type(stockfish) == str:
            self.stockfish = Stockfish(stockfish_color,
                                       stockfish,
                                       search_depth=stockfish_depth)
        elif type(stockfish) == Stockfish:
            self.stockfish = stockfish

    def move(self, movement):
        """ Makes a move. If it's not your turn, Stockfish will play and if
    the move is illegal, it will be ignored.
        Params:
            movement: str, Movement in UCI notation (f2f3, g8f6...)
        """
        # If stockfish moves first
        if self.stockfish.color and len(self.board.move_stack) == 0:
            stockfish_best_move = self.stockfish.best_move(self)
            self.board.push(chess.Move.from_uci(stockfish_best_move))
        else:
            made_movement = super().move(movement)
            if made_movement and self.get_result() is None:
                stockfish_best_move = self.stockfish.best_move(self)
                self.board.push(chess.Move.from_uci(stockfish_best_move))

    def get_copy(self):
        return GameStockfish(board=self.board.copy(), stockfish=self.stockfish)

    def tearup(self):
        """ Free resources. This cannot be done in __del__ as the instances
        will be intensivily cloned but maintaining the same stockfish AI
        engine. We don't want it deleted. Should only be called on the end of
        the program.
        """
        self.stockfish.kill()

    def free(self):
        """ Unlinks the game from the stockfish engine. """
        self.stockfish = None

    def __del__(self):
        #self.free()
        #del(self.board)
        pass
示例#12
0
文件: ai.py 项目: AyushAryal/chess
def get_best_move(board):
    stockfish = Stockfish()
    move_list = []

    for move in board.moves:
        move_list.append(move.to_long_algebraic())

    stockfish.set_position(move_list)
    return long_algebraic_to_coordinate(stockfish.get_best_move())
示例#13
0
 def initEngine(self):
     self.moves = []
     self.stockfish = Stockfish(None, 10, {
         'Skill Level': 2500,
         'Threads': 4
     })
     self.stockfish.set_position([])
     self.fetchBoard()
     self.printBoard()
示例#14
0
    def __init__(self):
        self.stockfish = Stockfish("./stockfish")
        self.knn_clf = joblib.load("train/model.pkl")

        #The board size. Should be 320 because thats what the model has been trained on
        self.board_size = 320

        self.checking = False
        self.bot_turn = True
示例#15
0
 def test_stockfish_easy_mate(self):
     # Test that it finds mate in 2
     stockfish_engine = Stockfish("/usr/games/stockfish")
     position_mate_in_two = "r2qb1rk/ppb2p1p/2n1pPp1/B3N3/2B1P2Q/2P2R2/1P4PP/7K w - - 0 1"
     stockfish_engine.set_fen_position(position_mate_in_two)
     proposed_moves = stockfish_engine.get_top_moves()
     self.assertEqual({
         'Move': 'h4h7',
         'Centipawn': None,
         'Mate': 2
     }, proposed_moves[0])
示例#16
0
 def __init__(self):
     abs_path = os.path.dirname(__file__)  # local path
     rel_path = 'stockfish-10-win/stockfish-10-win/stockfish_x86-64-modern.exe'
     self.sf = Stockfish(os.path.join(
         abs_path, rel_path))  # pull the engine from compiled file
     self.m_skill_level = 0  # skill level of engine
     self.m_cur_turn = 0  # 0 for player turn, 1 for computer turn
     self.m_in_game = False  # see if we're still in game
     self.m_move_his = []  # move history to update position in stockfish
     self.num_moves = 0  # number of moves (extraneous, may remove)
     self.set_skill_level(
         self.request_skill_level())  # request a skill level for engine
     self.choose_side(self.request_side())  # request a starting side
     self.m_starting_side = 0
     self.m_board = Board(self.m_cur_turn)
示例#17
0
文件: DB.py 项目: pemo0000/playground
 def insertFEN(self, fen):
     """Is inserting FEN into sqlite
     :param fen: chess position in Forsyth-Edwards-Notation (FEN), e.g. r4rnk/1pp4p/3p4/3P1b2/1PPbpBPq/8/2QNB1KP/1R3R2 w KQkq - 0 25
     """
     self.cursor.execute("select count(*) from FEN where fen = ?;", [fen])
     data = self.cursor.fetchone()[0]
     if data == 0:
         stockfish = Stockfish('/usr/games/stockfish')
         stockfish.set_fen_position(fen)
         bestmove = stockfish.get_best_move()
     try:
         self.cursor.execute("insert into FEN(fen, bestmove) values(?,?);",
                             (str([fen]), bestmove))
     except sqlite3.IntegrityError:
         pass
 def __init__(self, stockfishpath):
     conf = {
         "Write Debug Log": "false",
         "Contempt": 0,
         "Min Split Depth": 0,
         "Threads": 1,
         "Ponder": "false",
         "Hash": 16,
         "MultiPV": 1,
         "Skill Level": 20,
         "Move Overhead": 30,
         "Minimum Thinking Time": 20,
         "Slow Mover": 80,
         "UCI_Chess960": "false",
     }
     self.stockfish = Stockfish(stockfishpath, parameters=conf)
示例#19
0
 def test_stockfish_constructor_with_custom_params(self):
     stockfish = Stockfish(parameters={"Skill Level": 1})
     assert stockfish.get_parameters() == {
         "Write Debug Log": "false",
         "Contempt": 0,
         "Min Split Depth": 0,
         "Threads": 1,
         "Ponder": "false",
         "Hash": 16,
         "MultiPV": 1,
         "Skill Level": 1,
         "Move Overhead": 30,
         "Minimum Thinking Time": 20,
         "Slow Mover": 80,
         "UCI_Chess960": "false",
     }
示例#20
0
class Moves:
    def __init__(self):
        self.best_move = ''
        self.stockfish = Stockfish(
            "stockfish_14_linux_x64_avx2/stockfish_14_x64_avx2")
        self.positions2 = ""
        self.pos_temp = 0
        self.curr_position = (Fen().start_position_list()).copy()

    def current_position(self):
        return self.curr_position

    def change_position(self, position):
        start_pos = position[0:2].lower()
        stop_pos = position[2:4].lower()

        for key, value in self.curr_position.items():
            if key == start_pos:
                moved_obj = value
        self.curr_position[start_pos] = None
        self.curr_position[stop_pos] = moved_obj
        return self.curr_position

    def curr_fen(self):
        self.positions2 = ''
        for ix, value in enumerate(self.curr_position.values()):
            # import ipdb
            # ipdb.set_trace()
            if ix % 8 == 0 and ix != 0:
                if self.pos_temp > 0:
                    self.positions2 += str(self.pos_temp)
                self.positions2 += "/"
                self.pos_temp = 0
            if not value:
                self.pos_temp += 1
            else:
                if self.pos_temp > 0:
                    self.positions2 += str(self.pos_temp)
                    self.pos_temp = 0
                self.positions2 += value
                print(self.positions2)
        return self.positions2 + ' b KQkq - 0 1'

    def stock_best(self):
        self.stockfish.set_fen_position(self.curr_fen())
        self.best_move = self.stockfish.get_best_move_time(10)
        return self.best_move
示例#21
0
class ChessGame:
    def __init__(self, fen):
        """ constructor taking initial FEN position"""
        self.d_engine = Stockfish()
        self.setFen(fen)

    def setFen(self, fen):
        """ set board in fen notation """
        self.d_engine.set_fen(fen)

    def move(self, algMove):
        """ move in long algebraic notation, send to stockfish """
        if self.d_engine.is_move_correct(algMove):
            print("correct")

    def bestMove(self):
        return self.d_engine.get_best_move()
示例#22
0
class ChessGame:
    def __init__(self, fen):
        """ constructor taking initial FEN position""" 
        self.d_engine = Stockfish()
        self.setFen(fen)

    def setFen(self, fen):
        """ set board in fen notation """
        self.d_engine.set_fen(fen)

    def move(self, algMove):
        """ move in long algebraic notation, send to stockfish """
        if self.d_engine.is_move_correct(algMove):
            print("correct")

    def bestMove(self):
        return self.d_engine.get_best_move()
示例#23
0
def evaluation_from_board(board: chess.Board,
                          evaluation_depth: int = 22) -> Dict:
    board_fen = board.fen()
    stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish")
    stockfish.set_depth(evaluation_depth)  # set engine depth
    stockfish.set_fen_position(board_fen)
    return stockfish.get_evaluation()
示例#24
0
class Brain:
    def __init__(self):
        self.sf = Stockfish()
        self.ucim = []
        self.tablero = chess.Board()
        print(self.tablero)

    def legal(self, mv):
        mov = self.to_move(mv)
        return (mov in self.tablero.legal_moves)

    def mover_uci(self, mv):
        self.ucim.append(mv)
        self.sf.set_position(self.ucim)
        self.tablero.push_uci(mv)
        print(self.tablero)

    def auto(self):
        mv = self.sf.get_best_move()
        print(mv)
        return (mv)

    def to_move(self, mv):
        return chess.Move.from_uci(mv)

    def is_over(self):
        return self.tablero.is_game_over()

    def capturo(self, mv):
        if self.tablero.is_capture(mv):
            if self.tablero.is_en_passant(mv):
                return (True, True)
            else:
                return (True, False)
        else:
            return (False, False)
        return

    def enroque(self, mv):
        if self.tablero.is_kingside_castling(mv):
            return (True, True)
        elif self.tablero.is_queenside_castling(mv):
            return (True, False)
        else:
            return (False, False)
示例#25
0
 def __init__(self, skill_level):
     parameters = {
         "Write Debug Log": "false",
         "Contempt": 0,
         "Min Split Depth": 0,
         "Threads": 1,
         "Ponder": "false",
         "Hash": 16,
         "MultiPV": 1,
         "Skill Level": skill_level,
         "Move Overhead": 30,
         "Minimum Thinking Time": 20,
         "Slow Mover": 80,
         "UCI_Chess960": "false",
     }
     self.engine = Stockfish("resources/stockfish.exe",
                             parameters=parameters)
     self.engine.set_depth(ENGINE_DEPTH)
示例#26
0
 def __init__(self) -> None:
     self.path = "stockfish.exe" if sys.platform == "win32" else "stockfish"
     try:
         Stockfish(self.path)
     except FileNotFoundError:
         print(
             f"cannot find stockfish executable. try putting one as `{self.path}` in the path"
         )
         exit(-1)
示例#27
0
 def start_game(self, uid: UUID, opts: GameOptions) -> ChessGame:
     if opts.ai_is_white is None:
         raise NotImplementedError(
             "not using stockfish is not currently implimented")
     self.games[uid] = ChessGame(
         stockfish=Stockfish(self.path),
         timer=asyncio.get_event_loop().create_task(
             delete_match_in(self, uid)),
     )
     return self.games[uid]
示例#28
0
    def __init__(self,
                 stockfish,
                 player_color=Game.WHITE,
                 board=None,
                 date=None,
                 stockfish_depth=10):
        super().__init__(board=board, player_color=player_color, date=date)
        if stockfish is None:
            raise ValueError('A Stockfish object or a path is needed.')

        self.stockfish = stockfish
        stockfish_color = not self.player_color

        if type(stockfish) == str:
            self.stockfish = Stockfish(stockfish_color,
                                       stockfish,
                                       search_depth=stockfish_depth)
        elif type(stockfish) == Stockfish:
            self.stockfish = stockfish
示例#29
0
class Player:
    def __init__(self, controller="random", customFunction=None):
        # "random", "gp", "alphazero", "*anyother we're planning to implement"
        self.controller = controller
        self.customFunction = customFunction
        # add any other variables as needed
        self.stockfish = Stockfish(
            './stockfish-10-win/Windows/stockfish_10_x64.exe')

    def choose_move(self, board, moves):
        if self.controller == "random":
            chosenMoveIndex = random.randint(0, len(moves) - 1)
            chosenMove = moves[chosenMoveIndex]
            return chosenMove
        elif self.controller == "custom":
            return self.customFunction(board, moves)
        elif self.controller == "stockfish":
            self.stockfish.set_fen_position(board.fen())
            uciStr = self.stockfish.get_best_move()
            move = chess.Move.from_uci(uciStr)
            return move
        elif self.controller == "player":
            while True:
                print(board)
                move = input(
                    "Input a move, or input m for a list of possible moves: ")
                if move == 'm':
                    for move in moves:
                        print(move)
                    continue
                try:
                    move = chess.Move.from_uci(move)
                    if move in moves:
                        return move
                    else:
                        print("Invalid move")
                except:
                    print("Invalid move")
                    continue
        else:
            # implement controller's movement choice
            pass
示例#30
0
 def bot_move(self):
     stfish = Stockfish('stockfish')
     stfish.set_fen_position(self.fen())
     if self.board.turn:
         stfish.depth = self.white_bot_power
     else:
         stfish.depth = self.black_bot_power
     move = stfish.get_best_move()
     return self.make_move(move)
示例#31
0
    def get_groundtruth(self):
        feature_batch = []
        targets_batch = []
        board_positions = self.get_board_position()
        shuffle(board_positions)
        print("done shuffling")
        print("generating evaluations on {} board positions...".format(
            len(board_positions)))
        # stockfish = Stockfish()

        for index, board_position in enumerate(board_positions):
            print(index)
            stockfish = Stockfish()
            feature_batch.append(board_to_feature(board_position))
            targets_batch.append(stockfish.stockfish_eval(board_position, 10))
            stockfish.kill_me()
        feature_arr = np.asarray(feature_batch)
        targets_arr = np.asarray(targets_batch)
        np.save('features.txt', feature_arr)
        np.save('values.txt', targets_arr)
示例#32
0
""" Before running do
    pip install stockfish
    to get the stockfish python interface """

from stockfish import Stockfish

stockfish = Stockfish()
stockfish.set_position(['e2e4', 'e7e6'])
stockfish.depth = 20
print(stockfish.get_best_move())
print(stockfish.is_move_correct('a2a3'))
示例#33
0
 def setUp(self):
     self.stockfish = Stockfish()
示例#34
0
class TestStockfish(unittest.TestCase):

    def setUp(self):
        self.stockfish = Stockfish()

    def test_get_best_move(self):
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, ('e2e4', 'g1f3',))

        self.stockfish.set_position(['e2e4', 'e7e6'])
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, ('d2d4', 'g1f3',))

        # mate
        self.stockfish.set_position(['f2f3', 'e7e5', 'g2g4', 'd8h4'])
        self.assertFalse(self.stockfish.get_best_move())

    def test_is_move_correct(self):
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
        self.stockfish.set_position(['e2e4', 'e7e6'])
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
示例#35
0
 def __init__(self, fen):
     """ constructor taking initial FEN position""" 
     self.d_engine = Stockfish()
     self.setFen(fen)