示例#1
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()
示例#2
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()
示例#3
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',
            'b1c3',
        ))

        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_set_fen_position(self):
        self.stockfish.set_fen_position(
            "7r/1pr1kppb/2n1p2p/2NpP2P/5PP1/1P6/P6K/R1R2B2 w - - 1 27")
        self.assertTrue(self.stockfish.is_move_correct('f4f5'))
        self.assertFalse(self.stockfish.is_move_correct('a1c1'))

    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'))
示例#4
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()
示例#5
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)
示例#6
0
def stockFish_init(request):
    stockfish = Stockfish(parameters={
        "Threads": 2,
        "Minimum Thinking Time": 30
    })
    stockfish.set_position(["e2e4", "e7e6"])
    #posición de Forsyth–Edwards Notation (FEN)
    stockfish.set_fen_position(
        "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")
    #coge el mejor movimiento
    stockfish.get_best_move(
    )  #stockfish.get_best_move_time(1000) en base al tiempo
    #nivel del motor
    stockfish.set_skill_level(15)
    #parámetros por defecto
    stockfish.get_parameters()
    #coge la posición FEN
    stockfish.get_fen_position()
    #coge el tablero por defecto del usuario
    stockfish.get_board_visual()
    #evalua jugada
    stockfish.get_evaluation()
    p = subprocess.Popen('stockfish-x64.exe',
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    p.stdin.write("position startpos moves e2e4 e7e5\n")
    p.stdin.write("go infinite\n")
    p.stdin.flush()
    time.sleep(1)
    print(p.communicate())
示例#7
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",
     )
示例#8
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)
示例#9
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])
示例#10
0
def generate_random_advantage_position(evaluation_depth: int):
    stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish")
    stockfish.set_depth(evaluation_depth)  # set engine depth
    while True:
        board = chess.Board()
        end_game = False
        for i in range(random.randint(10, 200)):
            move = random.choice(list(board.legal_moves))
            board.push(move)
            if board.is_game_over():
                end_game = True
                print("Final position")
                break

        if not end_game:
            board_fen = board.fen()
            stockfish.set_fen_position(board_fen)
            position_evaluation = stockfish.get_evaluation()
            print(
                f"Position_evaluation: {position_evaluation}, fen = {board_fen}"
            )

            if position_evaluation['type'] == 'cp' and abs(
                    position_evaluation["value"]) < 300 and abs(
                        position_evaluation["value"]
                    ) > 1000:  # rule out when no big advantage
                print(
                    f"position_evaluation: {position_evaluation}. Passing: rule out when no big advantage"
                )
                pass
            elif position_evaluation['type'] == 'mate' and position_evaluation[
                    'value'] <= 1:  # rule out mate in 1
                print(
                    f"position_evaluation: {position_evaluation}. Passing: rule out mate in 1"
                )
                pass
            else:
                if board.turn == chess.WHITE and position_evaluation[
                        "value"] <= 0:  # not an advantage white
                    print(f"Turn: {board.turn}")
                    print(
                        f"position_evaluation: {position_evaluation}. Passing: not an advantage for white"
                    )
                    pass
                elif board.turn == chess.BLACK and position_evaluation[
                        "value"] >= 0:  # not an advantage black
                    print(f"Turn: {board.turn}")
                    print(
                        f"position_evaluation: {position_evaluation}. Passing: not an advantage for black"
                    )
                    pass
                else:
                    yield board, board_fen, position_evaluation
示例#11
0
 def play(self):
     dirname = os.path.dirname(__file__)
     filename = os.path.join(dirname, 'stockfish-9-win\Windows\stockfish_9_x64')
     stockfish = Stockfish(filename)
     stockfish.set_skill_level(15)
     if not self.chessboard.is_game_over() and not self.chessboard.is_stalemate():
         board = self.chessboard.fen()
         stockfish.set_fen_position(board)
         ai_move = stockfish.get_best_move()
         move = chess.Move.from_uci(ai_move)
         print(move)
         self.chessboard.push(move)
         self.update()
示例#12
0
def main():
    #Deteremine start
    random.seed(datetime.now())
    white = random.randint(0, 1)

    #initialize board and stockfish
    board = chess.Board()
    fishy = Stockfish(
        '/Users/vishalaiely/Downloads/stockfish-11-mac/Mac/stockfish-11-64')

    if white:
        #playsound.playsound('audio/WhiteStart.mp3')
        speak('Hello, you have the white pieces')
    else:
        #playsound.playsound('audio/BlackStart.mp3')
        speak('Hello, you have the black pieces')

    #Game executes and breaks when over
    while not board.is_game_over():
        if white:
            board.push_uci(playermove(board))

            fishy.set_fen_position(board.fen())
            compMove = fishy.get_best_move()
            board.push_uci(compMove)

            speak(compMove)

        else:
            fishy.set_fen_position(board.fen())
            compMove = fishy.get_best_move()
            board.push_uci(compMove)

            speak(compMove)

            board.push_uci(playermove(board))

    #Determines end state of game
    if board.result() is '1-0':
        #playsound.playsound('audio/WhiteWin.mp3')
        speak('White wins')
    elif board.reset() is '0-1':
        #playsound.playsound('audio/BlackWin.mp3')
        speak('Black wins')
    elif board.is_stalemate():
        speak('Stalemate')
    else:
        speak('Draw')

    speak('Thank you for playing!')
示例#13
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
示例#14
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
示例#15
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
class StockfishPlayer:
    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)

    def get_best_move(self, fen):
        self.stockfish.set_fen_position(fen)
        return self.stockfish.get_best_move()
示例#17
0
class StockfishPlayer:
    def __init__(self, game, level):
        self.game = game
        self.engine = Stockfish('engines/stockfish',
                                parameters={
                                    "Threads": 4,
                                    "Skill Level": level
                                })

    def play(self, board):
        fen = board.fen()
        self.engine.set_fen_position(fen)

        move_uci = chess.Move.from_uci(self.engine.get_best_move_time(100))
        if move_uci not in list(board.legal_moves):
            log.error("Wrong move chosen by Stockfish! Check code")
            move_uci = random.choice(list(board.legal_moves))

        action = move_uci.from_square * 64 + move_uci.to_square

        return action
示例#18
0
    def get_from_to_move(maxtrix, image):
        move = input("Чей ход?[w/b]: ").lower()

        board = chess.Board(Detector.mat_to_fen(matrix, move))
        fen = board.fen()

        stockfish = Stockfish(
            "./Engines/stockfish_13_win_x64/stockfish_13_win_x64.exe",
            parameters={
                "Threads": os.cpu_count(),
                "Minimum Thinking Time": 30
            })

        stockfish.set_fen_position(fen)
        best_move = stockfish.get_best_move_time(1000)

        print("best move", best_move)
        x1, y1, x2, y2 = Detector.get_from_to(best_move, move)

        # print(x1, y1, x2, y2)
        cv2.rectangle(image, (x1, y1), (x1 + 100, y1 + 100), (0, 0, 255), 2)
        cv2.rectangle(image, (x2, y2), (x2 + 100, y2 + 100), (255, 0, 0), 2)
示例#19
0
 def calculate_suggestions(self, gui):
     for _ in range(5):
         stockfish = Stockfish("./src/cpu/stockfish_20090216_x64", 3)
         new_chess_match = copy.deepcopy(self.__chess_match)
         stockfish.set_fen_position(new_chess_match.get_fen_notation())
         new_chess_match.match_moves.limpa_pilha()
         rounds = 0 
         while rounds < 18 and (not new_chess_match.checkmate and not new_chess_match.draw):
             if self.__stop_thread:
                 return
             moviment = stockfish.get_best_move()
             new_chess_match.perform_chess_move(
                 ChessPosition(moviment[0], int(moviment[1])), 
                 ChessPosition(moviment[2], int(moviment[3]))
             )
             stockfish.set_fen_position(new_chess_match.get_fen_notation())
             rounds += 1
         self.__moviment_tree.add(self.get_eval(stockfish, new_chess_match), new_chess_match.match_moves)
     if self.__stop_thread:
             return
     moviments = self.__moviment_tree.max3() if new_chess_match.current_player == 'WHITE' else self.__moviment_tree.min3()
     gui.show_suggestions(moviments)
示例#20
0
def main(player1="Player 1",
         player2="Player 2",
         mode="STANDARD",
         bot_bool=False,
         bot_difficulty=6):

    # resetting the variables in the .json file#
    json_file = open(r'components\constants.json', 'r')
    json_content = json.load(json_file)
    json_content["round_int"] = 0
    json_file.close()
    json_file = open(r'components\constants.json', 'w')
    json_file.writelines(json.dumps(json_content))
    json_file.close()

    Pieces.white_is_checked = False
    Pieces.black_is_checked = False
    Pieces.checking_piece = None

    #initiating pygame#
    pygame.init()

    player1 = "Spieler 1" if player1 == "" else player1
    player2 = "Spieler 2" if player2 == "" else player2

    #Constants#
    BLACK = (0, 0, 0)
    GREY = (50, 50, 50)
    WHITE = (255, 255, 255)
    BG_COLOR_1 = (0, 152, 163)
    BG_COLOR_2 = (2, 112, 120)

    #reading the constants from the json file#
    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    tile_size = json_content["tile_size"]
    anchor_point_s = (json_content["anchor_point_s_x"] * tile_size,
                      json_content["anchor_point_s_y"] * tile_size)
    anchor_point_h = (json_content["anchor_point_h_x"] * tile_size,
                      json_content["anchor_point_h_y"] * tile_size)
    anchor_point_hud = (json_content["anchor_point_hud_x"] * tile_size,
                        json_content["anchor_point_hud_y"] * tile_size)
    json_file.close()

    #setting up the variables for a new and fresh game#
    screen_size = (11 * tile_size, 11 * tile_size)
    font = pygame.font.SysFont("DejaVu Sans", int(tile_size * 0.2))
    font_titles = pygame.font.SysFont("DejaVu Sans", int(tile_size * 0.25))
    go = True
    timer = Clock(time=5)

    #creating the surfaces#
    screen = pygame.display.set_mode(screen_size, 0, 0)
    s = pygame.Surface((8 * tile_size, 8 * tile_size))
    hud = pygame.Surface((10.25 * tile_size, 2 * tile_size))
    p1 = pygame.Surface((3 * tile_size, 1.5 * tile_size))
    p2 = pygame.Surface((3 * tile_size, 1.5 * tile_size))
    h = Hud((2 * tile_size, 8 * tile_size))
    screen.fill(BG_COLOR_1)
    hud.fill(BG_COLOR_2)
    h.fill(BG_COLOR_2)
    h.print(pos=(0.6 * tile_size, 20), label='Spielhistorie', font=font)

    #window caption#
    pygame.display.set_caption("Chess")

    #creating a clock for the ingame ticks#
    clock = pygame.time.Clock()

    #creating the board on the subsurface#
    board = Board(master=s,
                  width=8,
                  height=8,
                  tile_size=tile_size,
                  color_a=(245, 216, 188),
                  color_b=(176, 142, 109),
                  color_t1=(240, 230, 221),
                  color_t2=(201, 181, 163),
                  anchor_point=anchor_point_s)

    #loading the images for the pieces#
    images = {
        "white_pawn_img": pygame.image.load(r'assets/white_pawn.png'),
        "white_rook_img": pygame.image.load(r'assets/white_rook.png'),
        "white_knight_img": pygame.image.load(r'assets/white_knight.png'),
        "white_bishop_img": pygame.image.load(r'assets/white_bishop.png'),
        "white_queen_img": pygame.image.load(r'assets/white_queen.png'),
        "white_king_img": pygame.image.load(r'assets/white_king.png'),
        "black_pawn_img": pygame.image.load(r'assets/black_pawn.png'),
        "black_rook_img": pygame.image.load(r'assets/black_rook.png'),
        "black_knight_img": pygame.image.load(r'assets/black_knight.png'),
        "black_bishop_img": pygame.image.load(r'assets/black_bishop.png'),
        "black_queen_img": pygame.image.load(r'assets/black_queen.png'),
        "black_king_img": pygame.image.load(r'assets/black_king.png')
    }
    #loading the icons for the buttons#
    quit_icon = pygame.image.load(r'assets/quit.png')
    takeback_icon = pygame.image.load(r'assets/takeback.png')
    resign_icon = pygame.image.load(r'assets/resign_flag.png')
    test_icon = pygame.image.load(r'assets/lightbulb.png')

    #creating the board
    build_board(mode, s, images)

    #creating the chessbot based on .json parameters
    bot = Stockfish(b'components\stockfish_20011801_x64.exe')
    bot.set_skill_level(bot_difficulty)

    quit_button = Button(x=8.5 * tile_size,
                         y=0.4 * tile_size,
                         w=int(0.6 * tile_size),
                         h=int(0.6 * tile_size),
                         color_b=BLACK,
                         color_in=GREY,
                         color_t=WHITE,
                         command=quit,
                         icon=quit_icon,
                         imaginary_x=anchor_point_hud[0],
                         imaginary_y=anchor_point_hud[1])

    resign_button = Button(x=9.2 * tile_size,
                           y=0.4 * tile_size,
                           w=int(0.6 * tile_size),
                           h=int(0.6 * tile_size),
                           color_b=BLACK,
                           color_in=GREY,
                           color_t=WHITE,
                           command=lambda: [decideWhoLost(round_int)],
                           icon=resign_icon,
                           imaginary_x=anchor_point_hud[0],
                           imaginary_y=anchor_point_hud[1])

    test_zone_button = Testmode_Button(
        x=9.2 * tile_size,
        y=0.4 * tile_size + 0.74 * tile_size,
        w=int(0.6 * tile_size),
        h=int(0.6 * tile_size),
        color_b=BLACK,
        color_in=GREY,
        color_t=WHITE,
        command1=lambda: [
            Board.change_testmode(),
            #Pieces.change_ignore_me_standard(),
            Pieces.crop_move_done(),
            Pieces.kill_board(),
            build_board(mode, s, images),
            Pieces.build_from_list(screen=s),
            Pieces.set_round(Pieces.round_safe)
        ],
        command2=lambda: [
            Board.change_testmode(),
            #Pieces.change_ignore_me_standard(),
            Pieces.safe_round()
        ],
        icon=test_icon,
        imaginary_x=anchor_point_hud[0],
        imaginary_y=anchor_point_hud[1],
        deaf=False)

    if bot_bool:
        command = lambda: [
            takeback(board, s, takeback_button),
            takeback(board, s, takeback_button)
        ]
    else:
        command = lambda: [takeback(board, s, takeback_button)]

    takeback_button = Button(x=8.5 * tile_size,
                             y=0.4 * tile_size + 0.74 * tile_size,
                             w=int(0.6 * tile_size),
                             h=int(0.6 * tile_size),
                             color_b=BLACK,
                             color_in=GREY,
                             color_t=WHITE,
                             command=command,
                             icon=takeback_icon,
                             imaginary_x=anchor_point_hud[0],
                             imaginary_y=anchor_point_hud[1])

    start_sound = mixer.Sound("assets/sounds/board-start.mp3")
    start_sound.play()

    #the mainloop#
    while go:
        #setting the framerate#
        clock.tick(60)

        #refreshing the round counter#
        json_file = open(os.getcwd() + r"\components\constants.json", "r")
        json_content = json.load(json_file)
        round_int = json_content["round_int"]
        json_file.close()

        #drawing the board#
        # if not Board.game_over:
        board.draw_board()

        #updating the bot with the new game state#
        bot.set_fen_position(Pieces.give_FEN())

        #detecting, if the game is over, or not
        if not Board.game_over:
            Pieces.detectingCheck()
            Board.game_over = Pieces.detectGameOver(round_int=round_int)

        #end the game if the game is over#
        if Board.game_over or Board.resign_w or Board.resign_b:
            if Pieces.white_is_checked or Board.resign_w:
                board.end_screen('BLACK', s)
            elif Pieces.black_is_checked or Board.resign_b:
                board.end_screen('WHITE', s)
            else:
                board.end_screen('STALEMATE', s)
            takeback_button.active = False
            resign_button.active = False
            test_zone_button.active = False

        #checking if a pawn is promotable#
        for pawn in Pieces.all_pieces_list:
            if 'Pawn-B' in pawn.name and pawn.y == 7 * tile_size or 'Pawn-W' in pawn.name and pawn.y == 0 * tile_size:
                pawn.promotion()

        Pieces.detectingCheck()
        #highlighting the checked king#
        if Pieces.white_is_checked:
            for king in Pieces.all_pieces_list:
                if isinstance(king, Kings) and king.farbe == WHITE:
                    board.check(king_pos=(king.x, king.y))

        #highlighting the checked king#
        elif Pieces.black_is_checked:
            for king in Pieces.all_pieces_list:
                if isinstance(king, Kings) and king.farbe == BLACK:
                    board.check(king_pos=(king.x, king.y))

        #drawing all the pieces#
        # if not Board.game_over:
        for pieces in Pieces.all_pieces_list:
            pieces.draw(screen)

        #updating the mainsurface#
        pygame.display.update()

        #clearing the Subsurfaces#
        p1.fill(BG_COLOR_1)
        p2.fill(BG_COLOR_1)
        hud.fill(BG_COLOR_2)

        #refresh the time of the timers#
        timer.refreshTime()

        #creating the labels to be printed on the subsurfaces#
        Player_1_label = font_titles.render(player1, 1, BLACK)
        Player_2_label = font_titles.render(player2, 1, BLACK)
        timer_label = font_titles.render(timer.getTime(), 1, BLACK)

        #printing the labes on the subsurfaces#
        p1.blit(Player_1_label,
                (p1.get_width() / 2 - Player_1_label.get_width() / 2, 0))
        p2.blit(Player_2_label,
                (p2.get_width() / 2 - Player_2_label.get_width() / 2, 0))

        #creating the history
        h.fill(BG_COLOR_2)
        h.print((0.31 * tile_size, 20), 'Spielhistorie', font)
        for i in range(len(Pieces.moves_done)):
            fac_50 = 5 / 7 * tile_size
            fac_20 = 2 / 7 * tile_size
            h.print(pos=((i % 2) * fac_50 + fac_20,
                         (i // 2) * fac_20 + 2 * fac_20),
                    label=Pieces.moves_done[i],
                    font=font)

        #showing the taken pieces#
        Pieces.taken_pieces.sort(key=lambda x: x.value, reverse=False)
        white_loss = [[], []]
        black_loss = [[], []]
        for piece in Pieces.taken_pieces:
            if piece.farbe == (0, 0, 0):
                if len(black_loss[0]) < 8:
                    black_loss[0].append(piece)
                else:
                    black_loss[1].append(piece)
            elif piece.farbe == WHITE:
                if len(white_loss[0]) < 8:
                    white_loss[0].append(piece)
                else:
                    white_loss[1].append(piece)

        for line in black_loss:
            for piece in line:
                p1.blit(
                    pygame.transform.scale(piece.image,
                                           (tile_size // 3, tile_size // 3)),
                    ((line.index(piece) * 11 / 32 + 6 / 40) * tile_size,
                     (black_loss.index(line) + 1) * 0.5 * tile_size))
        for line in white_loss:
            for piece in line:
                p2.blit(
                    pygame.transform.scale(piece.image,
                                           (tile_size // 3, tile_size // 3)),
                    ((line.index(piece) * 11 / 32 + 6 / 40) * tile_size,
                     (white_loss.index(line) + 1) * 0.5 * tile_size))

        value_white = 0
        value_black = 0

        for piece in Pieces.taken_pieces:
            if piece.farbe == (0, 0, 0):
                value_black += piece.value
            elif piece.farbe == WHITE:
                value_white += piece.value

        label = font.render('+' + str(abs(int(value_white - value_black))),
                            True, BLACK)
        if int(value_white - value_black) > 0:
            if len(white_loss[0]) < 8:
                p2.blit(label,
                        ((len(white_loss[0]) * 11 / 32 + 6 / 40) * tile_size,
                         0.55 * tile_size))
            else:
                p2.blit(label,
                        ((len(white_loss[1]) * 11 / 32 + 6 / 40) * tile_size,
                         1.05 * tile_size))
        elif int(value_white - value_black) < 0:
            if len(black_loss[0]) < 8:
                p1.blit(label,
                        ((len(black_loss[0]) * 11 / 32 + 6 / 40) * tile_size,
                         0.55 * tile_size))
            else:
                p1.blit(label,
                        ((len(black_loss[1]) * 11 / 32 + 6 / 40) * tile_size,
                         1.05 * tile_size))

        #updating the hud#
        if round_int % 2 == 0:
            pygame.draw.rect(hud, BLACK, [
                0.45 * tile_size, 0.2 * tile_size, 3.1 * tile_size,
                1.6 * tile_size
            ])
        elif round_int % 2 == 1:
            pygame.draw.rect(hud, BLACK, [
                4.45 * tile_size, 0.2 * tile_size, 3.1 * tile_size,
                1.6 * tile_size
            ])
        hud.blit(p1, (0.5 * tile_size, 0.25 * tile_size))
        hud.blit(p2, (4.5 * tile_size, 0.25 * tile_size))
        hud.blit(timer_label, (3.65 * tile_size, 0.75 * tile_size))

        #creating the buttons on the hud
        resign_button.draw(screen=hud)
        quit_button.draw(screen=hud)
        takeback_button.draw(screen=hud)
        test_zone_button.draw(screen=hud)

        items = [quit_button, resign_button, takeback_button, test_zone_button]

        #bliting the subsurfaces on the mainsurface
        screen.blit(s, anchor_point_s)
        screen.blit(h, anchor_point_h)
        screen.blit(hud, anchor_point_hud)

        #bot moves#
        if round_int % 2 == 1 and bot_bool and not Board.game_over and not Board.test_mode:
            opt_move = bot.get_best_move_time(random.randint(400, 1200))
            for piece in Pieces.all_pieces_list:
                if piece.farbe == BLACK:
                    move = piece.move_from_pos(
                        move=opt_move,
                        board=board,
                        screen=screen,
                        takeback_button=takeback_button,
                        ignore_me=Pieces.ignore_me_standard)
                    if move != None:
                        break

        #checking for events#
        else:
            for event in pygame.event.get():

                for item in items:
                    item.processEvent(event)

                #closing the screen by clicking the X#
                if event.type == pygame.QUIT:
                    go = False

                #Keyboard-Inputs#
                if event.type == pygame.KEYDOWN:

                    #kill window if ESC is pressed#
                    if event.key == pygame.K_ESCAPE:
                        Pieces.white_is_checked = False
                        Pieces.black_is_checked = False
                        Pieces.checking_piece = None

                        json_file = open(r'components\constants.json', 'r')
                        json_content = json.load(json_file)
                        json_content["round_int"] = 0
                        json_file.close()
                        json_file = open(r'components\constants.json', 'w')
                        json_file.writelines(json.dumps(json_content))
                        json_file.close()

                        quit()

                    #(TEMP) my information key (arrow down) to get certain information#
                    if event.key == pygame.K_DOWN:
                        print(Pieces.give_FEN())
                        #print([x.name for x in Pieces.all_pieces_list])
                        # for king in Pieces.all_pieces_list:
                        #     if "King-W" in king.name:
                        #         print(list(king.is_castle_legal()))

                #left mouse click#
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:

                    #getting the mouseposition and than correcting it by the relative position of the subsurface#
                    mouse_pos = pygame.mouse.get_pos()
                    mouse_pos = (mouse_pos[0] - anchor_point_s[0],
                                 mouse_pos[1] - anchor_point_s[1])

                    #checking if a Piece stands on the clicked tile#
                    if not Board.game_over:
                        for piece in Pieces.all_pieces_list:
                            if mouse_pos[0] >= piece.x and mouse_pos[
                                    1] >= piece.y:
                                if mouse_pos[
                                        0] < piece.x + tile_size and mouse_pos[
                                            1] < piece.y + tile_size:

                                    #if the clicked piece is one of the team that currently is to move...#

                                    with_bool = round_int % 2 == 0 and piece.farbe == (
                                        255, 255, 255)
                                    without_bool = round_int % 2 == 1 and piece.farbe == (
                                        0, 0, 0)

                                    if with_bool or without_bool:

                                        #...wait for the second mouse input#
                                        move_ = piece.move(
                                            board=board,
                                            screen=screen,
                                            takeback_button=takeback_button,
                                            ignore_me=Pieces.ignore_me_standard
                                        )

                                        move_ = move_[1][2:3] + move_[2] + str(
                                            move_[0][2:])

                                        #check if the white kiung is checked#
                                        Pieces.detectingCheck()

    #resetting class variables#
    Pieces.white_is_checked = False
    Pieces.black_is_checked = False
    Pieces.checking_piece = None

    #resetting the variables in the .json file#
    json_file = open(r'components\constants.json', 'r')
    json_content = json.load(json_file)
    json_content["round_int"] = 0
    json_file.close()
    json_file = open(r'components\constants.json', 'w')
    json_file.writelines(json.dumps(json_content))
    json_file.close()
示例#21
0
def results():

    stockfish = Stockfish(
        '/Users/faizaanmadhani/Desktop/PCHACKS/chessapp/stockfish-10-mac/Mac/stockfish-10-64'
    )

    board = chess.Board()
    legalMove = board.legal_moves

    # build a request object
    req = request.get_json(force=True)

    oldPosition = req.get('queryResult').get('parameters').get('oldPosition')
    newPosition = req.get('queryResult').get('parameters').get('newPosition')
    checkmate = req.get('queryResult').get('queryText')
    piece = req.get('queryResult').get('parameters').get('piece')

    pieceStr = str(piece)
    newPositionStr = str(newPosition)

    if (pieceStr == 'knight' or 'night'):
        pieceStr = 'N' + newPositionStr
    elif (pieceStr == 'pawn' or 'Pawn'):
        pieceStr = newPositionStr
    else:
        pieceStr = pieceStr.charAt(0).upper() + newPositionStr

    # fetch action from json
    action = req.get('queryResult').get('action')

    if (os.stat("fenState.txt").st_size == 0):
        #If file fenState is empty, Write initial state of board to fenState
        writeFile = open("fenState.txt", "w")
        strBoardFen = board.fen()
        writeFile.write(str(strBoardFen))
        writeFile.close()

        #Then, read the state of the file
        readFile = open("fenState.txt", "r")
        boardState = readFile.read()
        board = chess.Board(boardState)

    else:
        #Otherwise, Read initial state of board
        readFile = open("fenState.txt", "r")
        boardState = readFile.read()
        board = chess.Board(boardState)

    if (chess.Move.from_uci(str(oldPosition) + str(newPosition))
            in board.legal_moves):
        board.push_san(pieceStr)

        #Get Fen position
        fenPosition = board.fen()

        #Engine makes their move
        stockfish.set_fen_position(fenPosition)
        bestmove = stockfish.get_best_move()
        board.push_san(bestmove)
        finalReturn = "I have moved " + bestmove

        #Write State to file (Debugging)
        writeFile = open("state.txt", "w")
        strBoard = str(board)
        writeFile.write(strBoard)
        writeFile.close()

        #Write FenState to file (State saving between moves)
        writeFile = open("fenState.txt", "w")
        boardFen = board.fen()
        strBoardFen = boardFen
        writeFile.write(strBoardFen)
        writeFile.close()

        if (str(checkmate) == 'checkmate' and board.is_checkmate() == True):
            finalReturn = "Checkmate!, and game over"
        elif (board.is_checkmate() == False and str(checkmate) == 'checkmate'):
            finalReturn = "You Can't Checkmate bro"

    else:
        finalReturn = "This move is wrong"

        writeFile = open("move.txt", "w+")
        Position = str(oldPosition + newPosition)
        writeFile.write(Position)
        writeFile.close()

    # return a fulfillment response
    return {'fulfillmentText': finalReturn}
示例#22
0
# else:
#     chester.move_square(move)
if (player == "w"):
    input("Make your first move, then press Enter")
# else:
#     print("I'm making my first move")
#     time.sleep(10)
#     chester.move_piece("d2d4")
#     input("Make your move, then press Enter")

winner = False  #Need to check if there's a winner after each move and if so: break the loop
while (not winner):
    fen, pieces = chester.calculate_fen_position(
    )  #This takes a picture and analyzes it, then generates the fen position of the board and returns it as a string
    print(fen)
    stockfish.set_fen_position(fen)
    print(stockfish.get_board_visual())
    time.sleep(1)
    move = str(stockfish.get_best_move())
    if (move == "None"):
        print("No possible move or something")
        exit()
    for p in pieces:
        if (move[2:4] == p["square"]):
            chester.move_piece(move[2:4] + 't0')
    print("Moving " + move)
    chester.move_piece(move)
    input("Make your move, then press Enter")

# pictures = [cv.imread("Q1.jpg"), cv.imread("Q2.jpg"), cv.imread("Q3.jpg") ,cv.imread("Q4.jpg")]
# print(chester.get_img_pieces(pictures))
示例#23
0
文件: test.py 项目: voicut31/vt-chess
from stockfish import Stockfish

stockfish = Stockfish('../stockfish-10/Mac/stockfish-10-64')

stockfish.set_position(['e2e4', 'e7e6'])

# set position by FEN:
stockfish.set_fen_position(
    "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")

print(stockfish.get_best_move())
print(stockfish.is_move_correct('a2a3'))

#print(stockfish.info)
示例#24
0
class SampleStockfish:
    """
    Stockfish player class.
    """
    def __init__(self, side, board, max_time_per_move, time_control):
        """
        Initialize player class to implement Stockfish.

        side: str
          Either 'white' or 'black' for the side that the player is expected to play

        board: Board (default: chess.Board())
          Initial board configuration (the default is just the normal board).

        max_time_per_move: float (default: None)
          Max. thinking time (in sec) to be passed to the players.
        
        time_control: 2-tuple of floats (default: None)
          The time control, formatted as (x, y) where the time control is x minutes
          with a y second increment. This argument is distinct from max_time_per_move.
        """
        self.name = 'Stockfish'
        
        self.side = side
        self.board = board
        self.max_time_per_move = max_time_per_move
        self.time_control = time_control
        
        # Manage time control
        if self.time_control is not None and self.max_time_per_move is not None:
            self.time_left = np.min([60 * self.time_control[0], self.max_time_per_move])
        elif self.time_control is not None:
            self.time_left = 60 * self.time_control[0]
        elif self.max_time_per_move is not None:
            self.time_left = self.max_time_per_move
        else:
            self.time_left = None
        
        # Start Stockfish
        from stockfish import Stockfish
        self.stockfish = Stockfish('./stockfish-11-win/Windows/stockfish_20011801_x64_modern.exe')
    
    def make_move(self):
        """
        Method to make a move. Returns the move in UCI.
        """
        self.stockfish.set_fen_position(self.board.fen())
        if self.time_left is not None:
            move = self.stockfish.get_best_move_time(0.8 * self.time_left * 1000)
        else:
            # If no time controls, make this 30 s
            move = self.stockfish.get_best_move_time(30 * 1000)
        
        self.board.push(chess.Move.from_uci(move))
        
        return move
    
    def receive_move(self, move, time_left=None):
        """
        Method to update board with move from the other side.
        
        move: str
          Move that opponent made
        
        time_left: float (default: None)
          Time remaining, if None, there is no global time control
        """
        self.board.push(chess.Move.from_uci(move))
        self.time_left = time_left
        
        return
    
    def request_draw(self):
        """
        Method to request a draw. Return True if want to request a draw, False if not.
        """
        return False
    
    def respond_draw(self):
        """
        Method to respond to a draw request. Return True if accept draw, False if not.
        """
        return False
    
    def receive_trash_talk(self, trash_talk):
        """
        Method to receive trash talk.
        """
        return
    
    def solicit_trash_talk(self):
        """
        Method to solicit trash talk. Return a string to solicit trash talk. If no trash
        talk, return none.
        """
        return None
示例#25
0
for game in data["finished_games"]:
    if len(game["moves"]) < 10:
        continue

    matches = {"W": 0, "B": 0}
    count = {"W": 0, "B": 0}
    winner = game["winner"]

    if winner == "TIE":
        continue

    for i in range(len(game["moves"])):
        move = game["moves"][i]
        turn = "W" if i % 2 == 0 else "B"
        count[turn] += 1
        stockfish.set_fen_position(move["fen"])
        if i > 0 and "uci" in move:
            if move["uci"] == best_move:
                matches[turn] += 1
        best_move = stockfish.get_best_move()

    # Threshold for analysis
    if count["W"] > 8:
        match_percentage = {
            "W": matches["W"] / count["W"] * 100,
            "B": matches["B"] / count["B"] * 100
        }
        for side in ["W", "B"]:
            match_percentage[turn] = round(match_percentage[turn], 1)

        if match_percentage[winner] > 45:
示例#26
0
def evaluate_position_sf(fen_board, threads=2, depth=2):
    """Evaluate a position using stockfish, position must be in Forsyth–Edwards Notation.
    TODO - Pass arbitrary params, the default depth seems OOL with evaluate_position()"""
    stockfish_engine = Stockfish(parameters={"Threads": threads})
    stockfish_engine.set_fen_position(fen_board)
    return stockfish_engine.get_evaluation()
示例#27
0
from bs4 import BeautifulSoup
from types import SimpleNamespace
import requests, json
from stockfish import Stockfish
#Ejemplo de lo que pueden hacer los tramposos XD
stockfish = Stockfish('stockfish',
                      parameters={
                          "Threads": 4,
                          "Minimum Thinking Time": 30
                      })
stockfish.set_depth(15)

while True:
    r = requests.get("https://lichess.org/KuXPWqE0bK55")
    soup = BeautifulSoup(r.content, 'html.parser')
    scripts = soup.select('script')
    game = scripts[-1]
    game = game.contents[0][41:-3]
    x = json.loads(game, object_hook=lambda d: SimpleNamespace(**d))
    stockfish.set_fen_position(x.data.game.fen)
    print("Best move: " + stockfish.get_best_move(), end='')
    next_move = input()
示例#28
0
from stockfish import Stockfish


def debug(msg):
    print(msg, file=sys.stderr)


def parser_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l',
                        '--level',
                        help='Show board',
                        type=int,
                        action='store',
                        default=1)
    args = parser.parse_args()
    return args


debug("Stockfish bot starting!\n")

args = parser_args()
s = Stockfish('./bin/stockfish')
s.set_skill_level(args.level)

while True:
    fen = input()
    debug(fen)
    s.set_fen_position(fen)
    print(s.get_best_move())
示例#29
0
def play_back(fen):
    sf = Stockfish()
    sf.set_fen_position(fen)
    next_move = sf.get_best_move()
    del sf
    return next_move
示例#30
0
    x = np.where(np.array(color) != np.array(color2))

    print(np.array(color))
    print(x)

    if color2.iloc[x[0][0], x[1][0]] != 'e':
        x = np.array([[x[0][1], x[0][0]], [x[1][1], x[1][0]]])

    position, color = update1(position, color, x)

    print(board)
    print(color)
    print(position)

    move1 = chess.Move.from_uci(pos(x, index, columns))
    board.push(move1)

    sf.set_fen_position(board.fen())
    zz = sf.get_best_move()
    move2 = chess.Move.from_uci(zz)
    board.push(move2)

    initial = list(zz[1::-1])
    final = list(zz[3::-1])
    position, color = update2(position, color, initial, final)

    print(board)
    print(color)
    print(position)