示例#1
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())
示例#2
0
class Computer:
    def __init__(self, skill_level):
        self.engine = Stockfish("./stockfish12/bin/stockfish")
        self.engine.set_skill_level(skill_level)
        self.move_history = []

    def get_move(self, player_move):
        self.move_history.append(player_move)
        self.engine.set_position(self.move_history)
        auto_move = self.engine.get_best_move()
        self.move_history.append(auto_move)

        return auto_move

    def get_suggestion(self):
        self.engine.set_position(self.move_history)
        auto_move = self.engine.get_best_move()

        return auto_move

    def print_board(self):
        self.engine.set_position(self.move_history)
        print(self.engine.get_board_visual())


# input -- board state (changes based on the user's move)

# output -- stockfish move
示例#3
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()
示例#4
0
class LiChessBot():
    def __init__(self):
        self.driver = webdriver.Firefox()
        self.engine = Stockfish()
        self.engine.set_skill_level(20)
        self.last_output = None
        self.logged_in = False

    def enter_match(self, time_format):
        """Starts a game with the given time format."""
        self.driver.get('https://lichess.org')
        sleep(SLEEP_TIME_MATCHING)
        self.driver.find_element_by_xpath(
            f'//*[@data-id="{TIME_FORMAT}"]/div').click()
        sleep(SLEEP_TIME_MATCHING)

        # finding the color
        page = self.request_script()
        sleep(1)
        for i in range(len(page) - len((key := "\"player\":{\""))):
示例#5
0
class Engine(object):
    
    def __init__(self):
        super().__init__()
        self.engine = None
        self.max_time = 1000  # Milliseconds

        self.list_moves = []
    
    def set_engine(self, engine_name="stockfish", skill_level=10):
        if engine_name == "stockfish":
            # stockfish_dir = os.path.join(Resource.get_engine_dir(), "stockfish_20090216_x64.exe")
            stockfish_dir = os.path.join("E:\\Jeee\\Documents\\Projects\\Python\\Chess\\engines", "stockfish_20090216_x64.exe")
            self.engine = Stockfish(stockfish_dir)
            self.set_engine_skill_level(skill_level)
            

    def set_engine_skill_level(self, level):
        self.engine.set_skill_level(level)


    
    def get_best_move(self):
        move = self.engine.get_best_move()
        return move

    def move(self, move):
        self.list_moves.append(move)
        self.engine.set_position(self.list_moves)
        # self.print_board_visual()
        Logger.record_move(move)

    def print_board_visual(self):
        print(self.engine.get_board_visual())

    def close_engine(self):
        self.engine.__del__
示例#6
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())
示例#7
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()
示例#8
0
from stockfish import Stockfish
import config
import chess
import copy

board = chess.Board()

#Windows
# stockfish = Stockfish('stockfish/stockfish_13_win_x64_bmi2.exe')
#Linux
stockfish = Stockfish('/home/pi/Downloads/Stockfish-sf_13/src/stockfish')

stockfish.set_skill_level(25)
# stockfish.set_position(["e2e4", "e7e6"])
# print(stockfish.get_board_visual())
# print(stockfish.is_move_correct('a2a5'))
# print(stockfish.get_best_move_time(250))
# stockfish.set_position(["b2b3"])
# print(stockfish.get_board_visual())
# print(stockfish.get_fen_position())


def make_move(move):
    print('the move {} is a move'.format(move))
    if stockfish.is_move_correct(move):
        config.moves.append(move)
        stockfish.set_position(config.moves)
        board = chess.Board(stockfish.get_fen_position())
        config.confirm_move = copy.deepcopy(config.current_board)
        return 1
    config.current_board = copy.deepcopy(config.confirm_move)
示例#9
0

def main():
    if tabuleiro.current_player == tabuleiro.bot_color:
        moviment = stockfish.get_best_move()
        captured_piece = tabuleiro.perform_chess_move(
            ChessPosition(moviment[0], int(moviment[1])),
            ChessPosition(moviment[2], int(moviment[3])))
        stockfish.set_fen_position(tabuleiro.get_fen_notation())

    gui.cpu_suggestions = Suggestion(tabuleiro)
    gui.thread = threading.Thread(
        target=gui.cpu_suggestions.calculate_suggestions, args=(gui, ))
    gui.thread.start()
    gui.draw_board()
    gui.draw_pieces()
    gui.parent.mainloop()
    UI.print_match(tabuleiro, stockfish)


if __name__ == "__main__":
    print('Escolha a Cor:')
    print('[1] BRANCAS')
    print('[2] NEGRAS')
    player_color = int(input())
    tabuleiro = ChessMatch.ChessMatch('BLACK' if player_color ==
                                      1 else 'WHITE')
    stockfish = Stockfish("./src/cpu/stockfish_20090216_x64")
    stockfish.set_skill_level(0)
    gui = GUI(tabuleiro, stockfish)
    main()
示例#10
0
class Player(abc.ABC):
    """
    An abstract class for player.
    """
    QUIT_MOVE = 'a1a1'

    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)

    def get_turns(self) -> List[str]:
        """
        Get previous turns to the game from the other player, gets the board to the desired initial state.

        Returns:
            The pre turns set by the other player.
        """
        moves_num = struct.unpack('H', self.socket.recv(2))[0]
        moves = []
        for _ in range(moves_num):
            moves.append(self.socket.recv(5).decode('utf-8').rstrip('\0'))
        return moves

    def forward_turns(self, moves: Optional[List[str]] = None):
        """
        Send previous turns to the game to the other player.

        Args:
            moves: The pre turns set by this player.
        """
        if moves is None:
            moves = []

        self.socket.send(struct.pack('H', len(moves)))
        for move in moves:
            self.socket.send(move.ljust(5, '\0').encode('utf-8'))

    def set_turns(self, moves: List[str]):
        """
        Set the pre turns of the game.

        Args:
            moves: The pre turns of the game.
        """
        self.moves = moves
        self.player_turn ^= len(moves) % 2

    def choose_move(self):
        """
        Choose a move to perform.
        Chooses the move using stockfish and sends it to the other player.
        """
        self.stockfish.set_position(self.moves)
        move = self.stockfish.get_best_move()
        if not move:
            raise RuntimeError('game over')
        print('Move chosen:', move)
        self.socket.send(move.ljust(5, '\0').encode('utf-8'))
        self.moves.append(move)

    def get_move(self):
        """
        Get the move done by the other player.
        """
        move = self.socket.recv(5).decode('utf-8').rstrip('\0')
        if move == self.QUIT_MOVE:
            raise RuntimeError('game over')
        self.moves.append(move)
        print('Move got:', move)

    def turn(self):
        """
        Perform a single turn, either get the move done by the other player, or do a move.
        """
        if self.player_turn:
            self.choose_move()
        else:
            self.get_move()

        self.player_turn = not self.player_turn

    def print_board(self):
        """
        Print the current board's state.
        """
        self.stockfish.set_position(self.moves)
        print(self.stockfish.get_board_visual())

    def __del__(self):
        """
        Destruct a player.
        Disconnects the socket.
        """
        self.socket and self.socket.close()
示例#11
0
class Game:  # handles game logic + interacts with stockfish
    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)

    def set_skill_level(self, d_level):  # function to set a skill level
        self.sf.set_skill_level(d_level)
        self.m_skill_level = d_level

    def choose_side(self, d_side):  # function to set a starting side
        self.m_cur_turn = d_side
        self.m_starting_side = d_side

    def check_for_mate(
        self, val
    ):  # function periodically checks if there is a checkmate and ends game if true
        # we can check for checkmate by looking at what stockfish thinks is the best move
        # if stockfish says only 1 move is the best move, we're in check
        # if no move is the best move, we're in checkmate.
        moves = self.sf.get_best_move()
        mate = 0
        print(moves)
        if moves == None:
            mate = 1
        return mate

    def check_for_castle(self, start, end):
        r_a = 0
        r_b = 0
        if start == 60:  # black side
            print('black king \n')
            if (start - end) == -2:  # castled 'h' rook
                r_a = 63
                r_b = 61
            else:  # castled 'a' rook
                r_a = 56
                r_b = 59
        elif start == 4:  # white side
            if (start - end) == -2:  # h rook
                r_a = 7
                r_b = 5
            else:
                r_a = 0
                r_b = 3
        self.m_board.change_pos(r_a, r_b)
        return 1

    def updateBoard(self, move):
        # first two characters of move are start, last two are end
        start_pos = move[:2]
        ind_pos_s = (ord(start_pos[0]) - 97) + ((int(start_pos[1]) - 1) * 8)
        end_pos = move[2:4]
        ind_pos_e = (ord(end_pos[0]) - 97) + ((int(end_pos[1]) - 1) * 8)

        # check for special moves occuring
        # check if a king in its original position has moved.
        print('Index: ' + str(ind_pos_s) + '\n' + 'Type: ' +
              str(self.m_board.get_piece_at(ind_pos_s)) + '\n\n\n\n')
        if (self.m_board.get_piece_at(ind_pos_s) == 1):
            print('castling!')
            self.check_for_castle(ind_pos_s, ind_pos_e)
        self.m_board.change_pos(ind_pos_s, ind_pos_e)
        return 1

    def endGame(self, ):
        # if mate is triggered, loser will be whoever's current turn it is
        win = 0
        w_side = 0
        if self.m_cur_turn == 0:  # white lost
            w_side = 1
            if self.m_cur_turn != self.m_starting_side:
                win = 1
        else:  # black lost
            if self.m_cur_turn != self.m_starting_side:
                win = 1
        if win:
            print('you won!')
        else:
            print('you lost!')
        return 1

    def request_side(self, ):  # prompts user for choosing a starting side
        side_set = False
        side = "white"
        count = 0
        c_side = 0
        while not side_set and count < 5:
            count = count + 1
            side = input('Which side? (type in white, black or random): ')
            if side == 'white' or side == 'black' or side == 'random':
                if side == 'black':
                    # if black, computer goes first
                    c_side = 1
                elif side == 'white':
                    # if white, player goes first
                    c_side = 0
                else:
                    if (random.randint(0, 999) / 100) > 5:
                        c_side = 1
                    else:
                        c_side = 0
                side_set = True
            elif count == 5:
                print("Setting to default side of white.")
                c_side = 0
                side_set = True
            else:
                print("Invalid input" + "\n")
        return c_side

    def request_skill_level(
        self, ):  # prompts user for inputting a skill level for engine
        level_set = False
        count = 0
        while not level_set and count < 5:
            count = count + 1
            skill = input(
                'What skill level? (integers between 1 and 21 inclusive): ')
            if skill.isdigit() and int(skill) > 0 and int(skill) < 22:
                level_set = True
            elif count == 5:
                print("Setting to default of skill level 5.")
                skill = 5
            else:
                print("Invalid input" + "\n")
        return skill

    def run(self, ):
        print('Game is now starting.')
        in_game = True
        # start game
        self.m_board.print_board_state()
        while in_game:
            # check if currently in checkmate (to end game)
            mate = self.check_for_mate()
            if mate:  # game is now over
                break
            turn = "your" if self.m_cur_turn == 0 else "the computer's"
            print("It is now " + turn + " turn." + "\n")
            if self.m_cur_turn == 0:
                move_done = 0
                while not move_done:
                    move = input('Enter your move: ' + '\n').strip()
                    # first check if valid move format (letter + number + letter + number)
                    valid = re.search(rule, move)
                    if valid and self.sf.is_move_correct(move):
                        # valid move syntax and able to be made
                        self.m_move_his.append(move)
                        self.sf.set_position(self.m_move_his)
                        print("You entered the move: " + move + '\n')
                        move_done = 1
                    else:
                        print("Invalid move, please enter a different move." +
                              '\n')
                self.m_cur_turn = 1
            else:  # computer's turn
                move = self.sf.get_best_move()
                print("The computer moves: " + move + '\n')
                self.m_move_his.append(move)
                self.sf.set_position(self.m_move_his)
                self.m_cur_turn = 0
            self.num_moves = self.num_moves + 1
            self.updateBoard(move)
            self.m_board.print_board_state()
        self.endGame()
示例#12
0
class Menu:
    bot_color = None

    def __init__(self):
        self.parent = tk.Tk()
        self.parent.title("Tutor Chess")
        self.parent.iconphoto(
            False, tk.PhotoImage(file='src/application/images/icon.png'))
        self.tabuleiro = None
        self.stockfish = None
        self.game_gui = None

        # Imagem de fundo
        width_size = 8 * 64
        height_size = 8 * 64
        self.principal = tk.Canvas(self.parent,
                                   width=width_size,
                                   height=height_size)
        background_image = ImageTk.PhotoImage(
            Image.open("src/application/images/background_image.jpg").resize(
                (725, 515)))
        label = tk.Label(self.parent, image=background_image)
        label.image = background_image
        label.place(x=0, y=0, relwidth=1, relheight=1)
        self.principal.pack()

        # Imagem da logo
        img = Image.open("src/application/images/logoProjeto.png").resize(
            (400, 100)).convert("RGBA")
        logo_image = ImageTk.PhotoImage(img)
        label_logo = tk.Label(self.parent, image=logo_image)
        label_logo.image = logo_image
        label_logo.place(relx=0.5, rely=0.25, anchor=tk.CENTER)

        # Botões
        # PLayer vs Player
        self.novo_jogo_player = tk.Button(self.parent,
                                          text="Player vs Player",
                                          height=2,
                                          width=50,
                                          command=self.new_game)
        self.novo_jogo_player.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

        # PLayer vs Bot
        self.novo_jogo_bot = tk.Button(self.parent,
                                       text="Player vs Bot",
                                       height=2,
                                       width=50,
                                       command=self.set_color)
        self.novo_jogo_bot.place(relx=0.5, rely=0.6, anchor=tk.CENTER)

        # Tutorial
        self.tutorial = tk.Button(self.parent,
                                  text="Tutorial",
                                  height=2,
                                  width=50,
                                  command=self.tutorial_text)
        self.tutorial.place(relx=0.5, rely=0.7, anchor=tk.CENTER)

        # Sair
        self.finalizar = tk.Button(self.parent,
                                   text="Finalizar",
                                   height=2,
                                   width=50,
                                   command=exit)
        self.finalizar.place(relx=0.5, rely=0.8, anchor=tk.CENTER)

        # Posicionamento da Tela Principal
        self.parent.update_idletasks()
        positionRight = int(
            (self.parent.winfo_screenwidth() - self.parent.winfo_reqwidth()) /
            2)
        positionDown = int(
            (self.parent.winfo_screenheight() - self.parent.winfo_reqheight())
            / 2)
        self.parent.geometry("+{}+{}".format(positionRight, positionDown))
        self.parent.resizable(0, 0)

    # Descrever um tutorial sobre a aplicação
    def tutorial_text(self):
        tk.messagebox.showinfo("Tutorial", "Tutorial sobre o Jogo")

    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)

    def new_game(self):
        self.__initial_game()
        if self.tabuleiro.current_player == self.bot_color:
            moviment = self.stockfish.get_best_move()
            self.tabuleiro.perform_chess_move(
                ChessPosition(moviment[0], int(moviment[1])),
                ChessPosition(moviment[2], int(moviment[3])))

        self.stockfish.set_fen_position(self.tabuleiro.get_fen_notation())
        self.game_gui.cpu_suggestions = Suggestion(self.tabuleiro)
        self.game_gui.thread = threading.Thread(
            target=self.game_gui.cpu_suggestions.calculate_suggestions,
            args=(self.game_gui, ))
        self.game_gui.thread.start()
        self.game_gui.lateral_suggestions.insert(1, "Calculando Sugestões...")

        self.game_gui.draw_board()
        self.game_gui.draw_pieces()
        self.game_gui.parent.mainloop()
        # self.parent.deiconify()

    def set_color(self):
        self.win = tk.Toplevel(bg="#FFFFFF")
        self.win.wm_title("Escolha a Cor")
        positionRight = int(self.win.winfo_screenwidth() / 2 - 266 / 2)
        positionDown = int(self.win.winfo_screenheight() / 2 - 100 / 2)
        self.win.geometry("+{}+{}".format(positionRight, positionDown))
        self.win.grab_set()
        text = tk.Text(self.win, width=30, height=1, relief=tk.FLAT)
        text.insert(tk.INSERT, "Escolha a cor do seu jogador.")
        text.configure(state=tk.DISABLED)
        text.pack(padx=8, pady=8, side=tk.TOP)

        # Cor Branca
        white_color = tk.Button(self.win,
                                text="Brancas",
                                height=2,
                                width=15,
                                command=self.__set_bot_black)
        white_color.pack(padx=8, pady=8, side=tk.LEFT)

        # Cor Negra
        black_color = tk.Button(self.win,
                                text="Negras",
                                height=2,
                                width=15,
                                command=self.__set_bot_white)
        black_color.pack(padx=8, pady=8, side=tk.RIGHT)

    def __set_bot_black(self):
        self.bot_color = 'BLACK'
        self.win.destroy()
        self.new_game()

    def __set_bot_white(self):
        self.bot_color = 'WHITE'
        self.win.destroy()
        self.new_game()