コード例 #1
0
    def __init__(self, caption):
        pygame.init()
        self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.buttons = []
        #self.buttons.append(StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))
        self.buttons.append(
            GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 275))
        #
        self.buttons.append(
            EasyButton(self.screen, 'Easy', MAP_WIDTH + 30,
                       BUTTON_HEIGHT + 45))
        self.buttons.append(
            MediumButton(self.screen, 'Normal', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 110))
        self.buttons.append(
            DifficultyButton(self.screen, 'Hard', MAP_WIDTH + 30,
                             BUTTON_HEIGHT + 175))
        #
        self.is_play = False

        self.map = Map(CHESS_LEN, CHESS_LEN)
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
        self.action = None
        self.AI = ChessAI(CHESS_LEN)
        self.useAI = False
        self.winner = None
        self.level = None
コード例 #2
0
ファイル: Game.py プロジェクト: Koyamin/Game
    def __init__(self, caption):
        self.__screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(caption)
        self.__clock = pygame.time.Clock()

        self.__start_map = StartMap(self.__screen, CHESS_LEN, CHESS_LEN)
        self.__chess_map = ChessMap(self.__screen, CHESS_LEN, CHESS_LEN)
        self.__is_in_start_map = True

        self.__action = None
        self.__is_play = False
        self.__player = None
        self.__winner = None

        self.__AI = ChessAI(CHESS_LEN)
        self.__isAI = False
        self.__useAI = True
コード例 #3
0
 def __init__(self, caption):
     pygame.init()
     self.screen = pygame.display.set_mode([SCREEN_WIDTH,
                                            SCREEN_HEIGHT])  #初始化窗口或屏幕进行显示
     pygame.display.set_caption(caption)  #设置窗口标题
     self.clock = pygame.time.Clock()  #创建一个时钟(用来帮助跟踪时间)
     self.buttons = []  #按钮list
     self.buttons.append(
         StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))  #添加开始按钮
     self.buttons.append(
         GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30,
                      BUTTON_HEIGHT + 45))  #添加结束按钮
     self.is_play = False
     self.map = Map(CHESS_LEN, CHESS_LEN)  #实例化一个棋盘,参数是线条数而非实际大小
     self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE  #定义玩家?????????
     self.action = None
     self.winner = None
     self.AI = ChessAI(CHESS_LEN)
     self.useAI = False
コード例 #4
0
ファイル: ChessGamePlay.py プロジェクト: k9on/DeepPurple
    def __init__(self):
        self.gameNum = 0
        self.ai = AI.ChessAI()
        self.player1 = None
        self.menuNum = 0
        self.autoSave = False # AIvsAI 모드 일때 기보 자동저장
        self.gameCount = 0 # AIvsAI 모드 일때 몇 게임을 진행하였는지 보여주기 위한 변수

        ########### 게임 결과정보 변수 ##############
        self.winner = None
        self.countNode = 0 # 게임이 몇개의 기보만에 끝이 났는지
コード例 #5
0
ファイル: main.py プロジェクト: tianxiancode/PythonGobang
    def __init__(self, caption, play_mode, AI_first):
        pygame.init()
        self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.mode = play_mode
        self.buttons = []
        self.buttons.append(
            StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))
        self.buttons.append(
            GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 45))
        self.is_play = False

        self.map = Map(CHESS_LEN, CHESS_LEN)
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
        self.action = None
        self.AI = ChessAI(CHESS_LEN)
        self.AI_first = AI_first
        self.winner = None
コード例 #6
0
 def __init__(self):
     self.client = socket(AF_INET, SOCK_STREAM)
     self.th = threading.Thread(target=self.recv, args=())
     self.client.connect(("127.0.0.1", 30005))
     self.board = chess.Board()
     self.ai = AI.ChessAI()
     self.player_turn = White_turn
     self.mode = single_mode
     self.mlm = MLM.MovesMaker()
     self.stockAI = Engine(depth=20)     #stockfish 객체생성
     self.list = []
     self.ai_turn = False
コード例 #7
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False
    animate = False
    gameOver = False
    load_images()
    sqSelected = ()  # last click of the user
    playerClicks = []  # keeps track of player clicks  - two tuples
    running = True
    playerOne = True  # if a human is white this is True
    playerTwo = True  # if a human is black  this is True
    while running:
        humanTurn = (gs.whiteToMove and playerOne) or (not gs.whiteToMove
                                                       and playerTwo)
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
                # mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    location = p.mouse.get_pos()
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if sqSelected == (
                            row, col
                    ):  # clicking twice the same sq deselects everything
                        sqSelected = ()
                        playerClicks = []
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(sqSelected)
                    if len(playerClicks) == 2:  # after 2nd click
                        move = ChessEngine.Move(playerClicks[0],
                                                playerClicks[1], gs.board)
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                moveMade = True
                                animate = True
                                gameOver = False
                                sqSelected = ()
                                playerClicks = []
                        if not moveMade:
                            playerClicks = [sqSelected]

            # key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # undo a move when z is pressed
                    gs.undoMove()
                    moveMade = True
                    animate = False  # don't animate after a undo
                    gameOver = False
                if e.key == p.K_r:
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    gameOver = False
                    animate = False
                    moveMade = False
        # AI move finder
        if not gameOver and not humanTurn:
            AIMove = ChessAI.findBestMoveMinMax(gs, validMoves)
            if AIMove is None:
                ChessAI.findRandomMove(validMoves)
            # AIMove = ChessAI.findRandomMove(validMoves)
            gs.makeMove(AIMove)
            moveMade = True
            animate = True

        if moveMade:
            if animate:
                animateMove(gs.moveLog[-1], screen, gs.board, clock)
            validMoves = gs.getValidMoves()
            moveMade = False
            animate = False

        drawGameState(screen, gs, validMoves, sqSelected)

        if gs.checkmate:
            gameOver = True
            if gs.whiteToMove:
                drawText(screen, 'Black won by checkmate')
            else:
                drawText(screen, 'White won by checkmate')
        elif gs.stalemate:
            gameOver = True
            drawText(screen, 'Draw by stalemate')

        clock.tick(MAX_FPS)
        p.display.flip()
コード例 #8
0
class Game():
    def __init__(self, caption):
        pygame.init()
        self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.buttons = []
        #self.buttons.append(StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))
        self.buttons.append(
            GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 275))
        #
        self.buttons.append(
            EasyButton(self.screen, 'Easy', MAP_WIDTH + 30,
                       BUTTON_HEIGHT + 45))
        self.buttons.append(
            MediumButton(self.screen, 'Normal', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 110))
        self.buttons.append(
            DifficultyButton(self.screen, 'Hard', MAP_WIDTH + 30,
                             BUTTON_HEIGHT + 175))
        #
        self.is_play = False

        self.map = Map(CHESS_LEN, CHESS_LEN)
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
        self.action = None
        self.AI = ChessAI(CHESS_LEN)
        self.useAI = False
        self.winner = None
        self.level = None

    def start(self, level):
        self.level = level
        self.is_play = True
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
        self.map.reset()

    def play(self):
        self.clock.tick(60)

        light_yellow = (247, 238, 214)
        pygame.draw.rect(self.screen, light_yellow,
                         pygame.Rect(0, 0, MAP_WIDTH, SCREEN_HEIGHT))
        pygame.draw.rect(self.screen, (255, 255, 255),
                         pygame.Rect(MAP_WIDTH, 0, INFO_WIDTH, SCREEN_HEIGHT))

        for button in self.buttons:
            button.draw()

        if self.is_play and not self.isOver():
            if self.useAI:
                x, y = self.AI.findBestChess(self.map.map, self.player,
                                             self.level)
                self.checkClick(x, y, True)
                self.useAI = False

            if self.action is not None:
                self.checkClick(self.action[0], self.action[1])
                self.action = None

            if not self.isOver():
                self.changeMouseShow()

        if self.isOver():
            self.showWinner()

        self.map.drawBackground(self.screen)
        self.map.drawChess(self.screen)
        self.map.drawSelection(self.screen)

    def changeMouseShow(self):
        map_x, map_y = pygame.mouse.get_pos()
        x, y = self.map.MapPosToIndex(map_x, map_y)
        if self.map.isInMap(map_x, map_y) and self.map.isEmpty(x, y):
            pygame.mouse.set_visible(False)
            light_red = (213, 90, 107)
            pos, radius = (map_x, map_y), CHESS_RADIUS
            pygame.draw.circle(self.screen, light_red, pos, radius)
        else:
            pygame.mouse.set_visible(True)

    def checkClick(self, x, y, isAI=False):
        self.map.click(x, y, self.player)
        if self.AI.isWin(self.map.map, self.player):
            self.winner = self.player
            self.click_button(self.buttons[0])
        else:
            self.player = self.map.reverseTurn(self.player)
            if not isAI:
                self.useAI = True

    def mouseClick(self, map_x, map_y):
        if self.is_play and self.map.isInMap(map_x,
                                             map_y) and not self.isOver():
            x, y = self.map.MapPosToIndex(map_x, map_y)
            if self.map.isEmpty(x, y):
                self.action = (x, y)

    def isOver(self):
        return self.winner is not None

    def showWinner(self):
        def showFont(screen, text, location_x, locaiton_y, height):
            font = pygame.font.SysFont(None, height)
            font_image = font.render(text, True, (205, 85, 85),
                                     (255, 255, 255))
            font_image_rect = font_image.get_rect()
            font_image_rect.x = location_x
            font_image_rect.y = locaiton_y
            screen.blit(font_image, font_image_rect)

        if self.winner == MAP_ENTRY_TYPE.MAP_PLAYER_ONE:
            str = 'Winner is White'
        else:
            str = 'Winner is Black'
        showFont(self.screen, str, MAP_WIDTH + 25, SCREEN_HEIGHT - 80, 30)
        pygame.mouse.set_visible(True)

    def click_button(self, button):
        if button.click(self):
            for tmp in self.buttons:
                if tmp != button:
                    tmp.unclick()

    def check_buttons(self, mouse_x, mouse_y):
        for button in self.buttons:
            if button.rect.collidepoint(mouse_x, mouse_y):
                self.click_button(button)
                break
コード例 #9
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    board = chess.Board()

    ai = ChessAI.ChessAI(board)

    drag = False

    loadImages()
    running = True

    mouse_pos = ()

    sqSelected = ()
    playerClicks = []

    while running:
        if (board.is_checkmate() == True):
            print("CHECKMATE")
            exit()
        if (board.is_stalemate() == True):
            print("STALEMATE")
            exit()

        if (board.turn == chess.BLACK):
            board.push(ai.getBestMove())

        for ev in pygame.event.get():
            if (ev.type == pygame.QUIT):
                running = False
            elif (ev.type == pygame.MOUSEBUTTONDOWN):
                drag = True
                loc = pygame.mouse.get_pos()
                col = loc[0] // SQ_SIZE
                row = loc[1] // SQ_SIZE

                sqSelected = chess.square(col, 7 - row)

            elif (ev.type == pygame.MOUSEMOTION):
                if (drag == True):
                    mouse_pos = pygame.mouse.get_pos()

            elif (ev.type == pygame.MOUSEBUTTONUP):
                drag = False
                mouse_pos = pygame.mouse.get_pos()

                col = mouse_pos[0] // SQ_SIZE
                row = mouse_pos[1] // SQ_SIZE

                move = chess.Move(
                    chess.square(file_index=chess.square_file(sqSelected),
                                 rank_index=chess.square_rank(sqSelected)),
                    chess.square(file_index=col, rank_index=7 - row))

                if (move in board.legal_moves):
                    board.push(move)

                sqSelected = ()

            elif (ev.type == pygame.KEYDOWN):
                if (ev.key == pygame.K_z):
                    gs.undoMove()

        clock.tick(MAX_FPS)

        drawGameState(screen, board)
        if (drag == True):
            drawDrag(screen, board, sqSelected)

        pygame.display.flip()
コード例 #10
0
class Game():
    def __init__(self, caption):
        pygame.init()
        self.screen = pygame.display.set_mode([SCREEN_WIDTH,
                                               SCREEN_HEIGHT])  #初始化窗口或屏幕进行显示
        pygame.display.set_caption(caption)  #设置窗口标题
        self.clock = pygame.time.Clock()  #创建一个时钟(用来帮助跟踪时间)
        self.buttons = []  #按钮list
        self.buttons.append(
            StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))  #添加开始按钮
        self.buttons.append(
            GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30,
                         BUTTON_HEIGHT + 45))  #添加结束按钮
        self.is_play = False
        self.map = Map(CHESS_LEN, CHESS_LEN)  #实例化一个棋盘,参数是线条数而非实际大小
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE  #定义玩家?????????
        self.action = None
        self.winner = None
        self.AI = ChessAI(CHESS_LEN)
        self.useAI = False

    def start(self):
        self.is_play = True  #更改游戏状态
        self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE  #定义玩家?????????
        self.map.reset()  #调用map类的函数清空棋盘

    def play(self):
        self.clock.tick(60)  #每秒循环60次
        light_yellow = (247, 238, 214)  #定义一种颜色
        pygame.draw.rect(self.screen, light_yellow,
                         pygame.Rect(0, 0, MAP_WIDTH,
                                     SCREEN_HEIGHT))  #绘制棋盘的底色矩形
        pygame.draw.rect(self.screen, (255, 255, 255),
                         pygame.Rect(MAP_WIDTH, 0, INFO_WIDTH,
                                     SCREEN_HEIGHT))  #绘制棋盘右侧的底色矩形

        for button in self.buttons:  #画出按钮
            button.draw()

        if self.is_play and not self.isOver():
            if self.useAI:
                x, y = self.AI.findBestChess(self.map.map, self.player)
                self.checkClick(x, y, True)
                self.useAI = False

            if self.action is not None:
                self.checkClick(self.action[0], self.action[1])  #下棋并轮到对方下
                self.action = None

            if not self.isOver():
                self.changeMouseShow()

        if self.isOver():
            self.showWinner()

        self.map.drawBackground(self.screen)  #画棋盘的线
        self.map.drawChess(self.screen)  #画棋子

    def changeMouseShow(self):
        map_x, map_y = pygame.mouse.get_pos()  #获取鼠标的坐标
        x, y = self.map.MapPosToIndex(map_x, map_y)  #鼠标坐标变为行列序号
        if self.map.isInMap(map_x, map_y) and self.map.isEmpty(x, y):
            pygame.mouse.set_visible(False)
            light_red = (213, 90, 107)
            pos, radius = (map_x, map_y), CHESS_RADIUS
            pygame.draw.circle(self.screen, light_red, pos, radius)
        else:
            pygame.mouse.set_visible(True)

    def checkClick(self, x, y, isAI=False):
        self.map.click(x, y, self.player)  #落子
        if self.AI.isWin(self.map.map, self.player):
            self.winner = self.player
            self.click_button(self.buttons[1])
        else:
            self.player = self.map.reverseTurn(self.player)
            if not isAI:
                self.useAI = True

    def mouseClick(self, map_x, map_y):  #当鼠标在棋盘上点击时读取出行列序号
        if self.is_play and self.map.isInMap(map_x,
                                             map_y) and not self.isOver():
            x, y = self.map.MapPosToIndex(map_x, map_y)
            if self.map.isEmpty(x, y):
                self.action = (x, y)

    def isOver(self):
        return self.winner is not None

    def showWinner(self):
        def showFont(screen, text, location_x, locaiton_y, height):
            font = pygame.font.SysFont(None, height)
            font_image = font.render(text, True, (0, 0, 255), (255, 255, 255))
            font_image_rect = font_image.get_rect()
            font_image_rect.x = location_x
            font_image_rect.y = locaiton_y
            #font_image_rect.topleft = (location_x, locaiton_y)等价于上面两句
            screen.blit(font_image, font_image_rect)  #写出Winner

        if self.winner == MAP_ENTRY_TYPE.MAP_PLAYER_ONE:
            str = 'Winner is White'
        else:
            str = 'Winner is Black'
        showFont(self.screen, str, MAP_WIDTH + 25, SCREEN_HEIGHT - 60, 30)
        pygame.mouse.set_visible(True)  #返回鼠标的前一个可见状态

    def click_button(self, button):  #点击Start或Give up按钮后,重新绘制按钮,换掉底色
        if button.click(self):
            for tmp in self.buttons:
                if tmp != button:
                    tmp.unclick()

    def check_buttons(self, mouse_x,
                      mouse_y):  #检测鼠标是否在刚才下的棋子所在矩形内,为已经点击了的按钮更换底色
        for button in self.buttons:
            if button.rect.collidepoint(mouse_x, mouse_y):
                self.click_button(button)
                break
コード例 #11
0
ファイル: ChessMain.py プロジェクト: crypticsy/Playground
def main():
    """ Main function that handles user input and graphics """

    # PyGame initialization
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_icon(IMAGES['logo'])  # add icon to the pg window
    screen = pg.display.set_caption(' Chess')  # add title to the pg window
    screen = pg.display.set_mode((BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH,
                                  BOARD_HEIGHT))  # set size of the pg window
    screen.fill(pg.Color("black"))  # add background color to the pg window

    move_log_font = pg.font.SysFont("Arial", 13, True, False)

    # GameEngine initialization
    game_state = ChessEngine.GameState()
    running = True
    sq_selected = ()  # store last click of the user
    player_click = []  # store clicks up to two clicks
    move_finder_process = None  # allow multi processing

    valid_moves = game_state.get_all_valid_moves()
    move_made = False  # flag variable for when a move is made
    animate = False  # flag variable for when a move needs to be animated
    game_over = False  # flag variable for when game is over
    ai_thinking = False  # flag variable for when the AI is finding best move
    move_undone = False  # flag variable for when the move is undone

    # if a human is playing white, then this will be True, else False
    player_one = False

    # if a human is playing black, then this will be True, else False
    player_two = False

    # infinite loop
    while running:

        human_turn = (game_state.white_to_move and player_one) or (
            not game_state.white_to_move and player_two
        )  # check if the human is controlling the turn

        for e in pg.event.get():  # for each event in event queue

            if e.type == pg.QUIT:  # trigger for ending infinite loop
                pg.quit()
                sys.exit()

            elif not game_over and e.type == pg.MOUSEBUTTONDOWN:
                if not game_over and human_turn:
                    location = pg.mouse.get_pos(
                    )  # (x, y) location fot the mouse
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE

                    # storing player clicks
                    if sq_selected == (
                            row, col
                    ) or col >= 8:  # in case the click is same as previous click, reset player clicks
                        sq_selected = ()
                        player_click.clear()

                    else:  # else update the new click position
                        sq_selected = (row, col)
                        player_click.append(sq_selected)

                    if len(player_click
                           ) == 2:  # when 2 unique clicks have been identified
                        move = ChessEngine.Move(player_click[0],
                                                player_click[1],
                                                game_state.board)

                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                game_state.make_move(valid_moves[i])

                                move_made = True
                                animate = True

                                # reset input
                                sq_selected = ()
                                player_click.clear()
                                break

                        else:
                            player_click = [sq_selected]

            elif e.type == pg.KEYDOWN and e.key == pg.K_z:  # trigger for undoing a move
                game_state.undo_move()
                move_made = True
                animate = False
                game_over = False

                if ai_thinking:
                    move_finder_process.terminate()
                    ai_thinking = False

                move_undone = True

            elif e.type == pg.KEYDOWN and e.key == pg.K_r:  # trigger for resetting the board
                game_state = ChessEngine.GameState()
                valid_moves = game_state.get_all_valid_moves()
                sq_selected = ()
                player_click.clear()
                move_made = False
                animate = False
                game_over = False

                if ai_thinking:
                    move_finder_process.terminate()
                    ai_thinking = False

                move_undone = True

        # AI move finder
        if not game_over and not human_turn and not move_undone:

            if not ai_thinking:
                ai_thinking = True
                return_queue = Queue()  # store and pass data between threads
                move_finder_process = Process(target=ChessAI.find_best_move,
                                              args=(game_state, valid_moves,
                                                    return_queue))
                move_finder_process.start()

            if not move_finder_process.is_alive():
                ai_move = return_queue.get()

                if ai_move is None:
                    ai_move = ChessAI.findRandomMove(valid_moves)

                game_state.make_move(ai_move)
                move_made = True
                animate = True
                ai_thinking = False

        if move_made:
            if animate:
                animate_move(game_state.move_log[-1], screen, game_state.board,
                             clock)  # animate the move made by the user
            valid_moves = game_state.get_all_valid_moves()
            move_made = False
            animate = False
            move_undone = False

        if not game_over:
            draw_GameState(screen, game_state, valid_moves, sq_selected,
                           move_log_font)

        if game_state.check_mate or game_state.stale_mate:
            game_over = True
            win_txt = 'Stalemate' if game_state.stale_mate else 'Black wins by checkmate.' if game_state.white_to_move else 'White  wins by checkmate.'
            draw_end_game_text(screen, win_txt)

        clock.tick(MAX_FPS)
        pg.display.flip()
コード例 #12
0
ファイル: Game.py プロジェクト: Koyamin/Game
class Game(object):
    def __init__(self, caption):
        self.__screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(caption)
        self.__clock = pygame.time.Clock()

        self.__start_map = StartMap(self.__screen, CHESS_LEN, CHESS_LEN)
        self.__chess_map = ChessMap(self.__screen, CHESS_LEN, CHESS_LEN)
        self.__is_in_start_map = True

        self.__action = None
        self.__is_play = False
        self.__player = None
        self.__winner = None

        self.__AI = ChessAI(CHESS_LEN)
        self.__isAI = False
        self.__useAI = True

    def start(self):
        self.__is_play = True
        self.__player = MapEntryType.MAP_PLAYER_ONE
        self.__chess_map.reset()

    def play(self):
        if self.__is_in_start_map:
            self.__start_map.draw_background()
        else:
            self.__clock.tick(60)

            pygame.draw.rect(self.__screen, LIGHT_YELLOW,
                             pygame.Rect(0, 0, MAP_WIDTH, MAP_HEIGHT))
            pygame.draw.rect(
                self.__screen, WHITE_COLOR,
                pygame.Rect(MAP_WIDTH, 0, INFO_WIDTH, SCREEN_HEIGHT))
            self.__chess_map.draw_button()

            if self.__is_play and not self.is_over():
                if self.__useAI:
                    self.__chess_map.draw_yagoo()
                if self.__useAI and self.__isAI:
                    x, y = self.__AI.find_best_chess(
                        self.__chess_map.get_map(), self.__player)
                    self.chess_map_check_click(x, y)
                    self.__isAI = False

                if self.__action is not None:
                    self.chess_map_check_click(self.__action[0],
                                               self.__action[1])
                    self.__action = None

                if not self.is_over():
                    self.__chess_map.change_mouse_show()

            if self.is_over():
                self.__chess_map.show_winner(self.__winner)

            self.__chess_map.draw_background()
            self.__chess_map.draw_chess(self.__screen)

    def chess_map_check_click(self, x, y):
        self.__chess_map.click(x, y, self.__player)
        if self.__AI.is_win(self.__chess_map.get_map(), self.__player):
            self.__winner = self.__player
            self.__chess_map.click_giveup_button(self)
        else:
            self.__player = self.__chess_map.reverse_turn(self.__player)
            if self.__useAI and not self.__isAI:
                self.__isAI = True

    def mouse_click(self, mouse_x, mouse_y):
        if self.__is_in_start_map:
            if self.__start_map.check_buttons(self, mouse_x, mouse_y):
                self.__is_in_start_map = False
                self.play()
        else:
            if self.__is_play and not self.is_over(
            ) and self.__chess_map.is_in_map(mouse_x, mouse_y):
                x, y = self.__chess_map.map_pos_to_index(mouse_x, mouse_y)
                if self.__chess_map.is_empty(x, y):
                    self.__action = (x, y)
            if self.__chess_map.check_buttons(self, mouse_x, mouse_y):
                self.start()

    def is_over(self):
        return self.__winner is not None

    def back_to_start(self):
        self.__start_map.reset()
        self.__is_in_start_map = True
        self.__useAI = True
        self.__isAI = False
        self.__chess_map.click_restart_button(self)

    def get_is_play(self):
        return self.__is_play

    def set_is_play(self, is_play):
        self.__is_play = is_play

    def get_map(self):
        return self.__chess_map

    def get_player(self):
        return self.__player

    def get_winner(self):
        return self.__winner

    def set_winner(self, winner):
        self.__winner = winner

    def get_useAI(self):
        return self.__useAI

    def set_useAI(self, useAI):
        self.__useAI = useAI
コード例 #13
0
	def __init__(self, *args, **kwargs):
		self.checkmate = False
		self.command = ''
		self.current_player = 0
		self.figures = {'wP':chr(14), 'wR':chr(15), 'wT':chr(16), 'wB':chr(17), 'wQ':chr(18), 'wK':chr(19), 'bP':chr(20), 'bR':chr(21), 'bT':chr(22), 'bB':chr(23), 'bQ':chr(24), 'bK':chr(25)}
		self.board = None
		self.rules = None
		self.players = [0,0]
		self.AIvsAI = False
		self.AIpause = False
		self.AIpauseSeconds = 1
		if has_chess_modules:
			self.rules = ChessRules()
			self.board = ChessBoard(0)
			player1Name = 'Kasparov'
			player1Type = 'human'
			player1Color = 'white'
			player2Name = 'Light Blue'
			player2Type = 'randomAI'
			player2Color = 'black'		
			if player1Type == 'human':
				self.players[0] = ChessPlayer(player1Name,player1Color)
			elif player1Type == 'randomAI':
				self.players[0] = ChessAI.ChessAI_random(player1Name,player1Color)
			elif player1Type == 'defenseAI':
				self.players[0] = ChessAI.ChessAI_defense(player1Name,player1Color)
			elif player1Type == 'offenseAI':
				self.players[0] = ChessAI.ChessAI_offense(player1Name,player1Color)
			if player2Type == 'human':
				self.players[1] = ChessPlayer(player2Name,player2Color)
			elif player2Type == 'randomAI':
				self.players[1] = ChessAI.ChessAI_random(player2Name,player2Color)
			elif player2Type == 'defenseAI':
				self.players[1] = ChessAI.ChessAI_defense(player2Name,player2Color)
			elif player2Type == 'offenseAI':
				self.players[1] = ChessAI.ChessAI_offense(player2Name,player2Color)
			if 'AI' in self.players[0].GetType() and 'AI' in self.players[1].GetType():
				self.AIvsAI = True
		self.font_size_text = 20
		self.font_file_text = os.environ['SYSTEMROOT']+'/Fonts/arial.ttf'
		self.font_size_chess = 40
		self.font_file_chess = 'chess.ttf'
		#~ self.font_file_chess = 'cheq_tt.ttf'
		self.black = SColor(255, 0, 0, 0)
		self.white = SColor(255, 255, 255, 255)
		self.back_color = SColor(255,150,150,150)
		self.board_color = SColor(255, 255, 255, 0)
		self.help_dialog = None
		self.video_driver = None
		self.scene_manager = None
		self.gui_environment = None
		self.font_text = None
		self.font_chess = None
		self.skin = None
		p = SIrrlichtCreationParameters()
		p.DriverType = driverType
		p.WindowSize = dimension2du(640, 480)
		p.AntiAlias = True
		p.WithAlphaChannel = True
		self.device = createDeviceEx(p)
		if self.device:
			self.device.setWindowCaption('Python Chess written by Steve Osborne, Irrlicht GUI by Maxim Kolosov')
			self.device.setResizable(True)
			self.video_driver = self.device.getVideoDriver()
			self.scene_manager = self.device.getSceneManager()
			self.gui_environment = self.device.getGUIEnvironment()
			# icon
			if is_frozen():
				self.video_driver.SetIcon(101)
			else:
				self.video_driver.SetIcon()
			# skin
			self.skin = self.gui_environment.getSkin()
			self.skin.setColor(EGDC_HIGH_LIGHT_TEXT, SColor(255, 0, 0, 0))
			self.skin.setColor(EGDC_GRAY_TEXT, SColor(255, 0, 255, 0))
			# chess font
			self.font_chess = CGUITTFont(self.gui_environment, self.font_file_chess, self.font_size_chess)
			if self.font_chess:
				self.skin.setFont(self.font_chess)
			else:
				self.font_chess = self.gui_environment.getBuiltInFont()
				print('++++ ERROR chess font not created !!!')
			# text font
			self.font_text = CGUITTFont(self.gui_environment, self.font_file_text, self.font_size_text)
			if self.font_text:
				self.skin.setFont(self.font_text, EGDF_BUTTON)
				self.skin.setFont(self.font_text, EGDF_WINDOW)
				self.skin.setFont(self.font_text, EGDF_MENU)
				self.skin.setFont(self.font_text, EGDF_TOOLTIP)
			# create board
			#~ self.dlg_tbl = self.gui_environment.addWindow(recti(0,0,800,600), True, _('board'))
			self.back_table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl, drawBackground = True)
			#~ self.back_table.setDrawFlags(EGTDF_ROWS | EGTDF_COLUMNS)
			self.table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl)
			self.table.setResizableColumns(False)
			self.table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			#~ self.black_table = self.gui_environment.addTable(recti(0,0,800,600), self.dlg_tbl)
			#~ self.black_table.setResizableColumns(False)
			#~ self.black_table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			self.fill_table()
			# create dialog list commands
			self.dlg_cmd = self.gui_environment.addWindow(recti(0,0,150,400))#, True, _('Steps history'))
			self.commands = self.gui_environment.addListBox(recti(0,20,150,300), self.dlg_cmd)
			self.commands.setAutoScrollEnabled(True)
			self.dlg_cmd.setRelativePosition(position2di(500,0))
		else:
			print('ERROR createDevice')
コード例 #14
0
def main():
    p.init()
    screen = p.display.set_mode((BOARD_WIDTH+MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    currState = ChessEngine.GameState()
    validMoves = currState.get_all_valid_moves()
    moveLogFont = p.font.SysFont("Times New Roman", 15, False, False)
    moveMade = False
    animate = False
    gameOver = False
    load_images()
    running = True
    squareSelected = ()
    playerClicks = []
    humanIsWhite = True  # If a human is playing white, this flag will be true, else False
    humanIsBlack = True  # If a human is playing black, this flag will be true, else False
    while running:
        humanTurn = (currState.whiteToMove and humanIsWhite) or (not currState.whiteToMove and humanIsBlack)
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            # handle mouse clicks
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    location = p.mouse.get_pos()
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if squareSelected == (row, col) or col >= 8:  # user clicked the same square or user clicked side panel => UNDO
                        squareSelected = ()
                        playerClicks = []
                    else:
                        squareSelected = (row, col)
                        playerClicks.append(squareSelected)
                        if len(playerClicks) == 2:
                            move = ChessEngine.Move(playerClicks[0], playerClicks[1], currState.board)
                            for i in range(len(validMoves)):
                                if move == validMoves[i]:
                                    moveMade = True
                                    animate = True
                                    currState.make_move(validMoves[i])
                                    # reset
                                    squareSelected = ()
                                    playerClicks = []
                            if not moveMade:
                                # set the first square as the last selected square
                                playerClicks = [squareSelected]
            # handle key presses
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # if 'z' is pressed, undo move
                    currState.undo_move()
                    moveMade = True
                    animate = False
                    gameOver = False
                if e.key == p.K_r:  # if 'r' is pressed, reset board
                    currState = ChessEngine.GameState()
                    validMoves = currState.get_all_valid_moves()
                    squareSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False
                    gameOver = False

        if not gameOver and not humanTurn:
            AIMove = ChessAI.find_best_move_nega_max_alpha_beta(currState, validMoves)
            if AIMove is None:
                AIMove = ChessAI.find_random_move(validMoves)
            currState.make_move(AIMove)
            moveMade = True
            animate = True

        if moveMade:
            if animate:
                animate_move(currState.moveLog[-1], screen, currState.board, clock)
            validMoves = currState.get_all_valid_moves()
            moveMade = False

        draw_game_state(screen, currState, validMoves, squareSelected, moveLogFont)
        if currState.checkmate or currState.stalemate or currState.repetition or currState.fiftyMovesDone:
            gameOver = True
            text = "Draw by stalemate!" if currState.stalemate else "Draw by repetition!" if currState.repetition else "Draw by 50-move rule!" if currState.fiftyMovesDone\
                else "0-1 : Black wins by checkmate!" if currState.whiteToMove else "1-0 : White wins by checkmate!"
            draw_game_end_text(screen, text)
        p.display.flip()
        clock.tick(MAX_FPS)
コード例 #15
0
    def mainLooptemp(self):     
        chess = ChessBoard()
        clock = pygame.time.Clock()
        screen = pygame.display.set_mode((480, 480),1)
        pygame.display.set_caption('ChessBoard Client')
        view = PyGameWindowView(chess,screen)
        controller = Controller(chess)        
        running = True
              
#        paired_piece_weights_1 = run_genetic_algorithms.build_random_pair_piece_dict()    
#        paired_piece_weights_2 = run_genetic_algorithms.build_random_pair_piece_dict()    
        
        player_1 = Human(ChessBoard.WHITE)
#        player_2 = Human(ChessBoard.BLACK)
#        AI1ply = 2
#        player_1 = ChessAI(ChessBoard.WHITE,chess,evaluation_functions.terminal_eval_simple,
#                           prune_functions.never_prune,QFunctions.simple_end_game,paired_piece_weights_1,AI1ply)
        AI2ply = 2
        player_2 = ChessAI(ChessBoard.BLACK,chess,evaluation_functions.terminal_eval,
                           prune_functions.never_prune,QFunctions.no_extension,None,AI2ply)
##        AI_color = ChessBoard.BLACK
#        player_color = ChessBoard.WHITE
#        human_player = Player(player_color)
##        AI = (AI_color)    
#        player_2_color = ChessBoard.BLACK
#        human_player_2 = Player(player_2_color)
        
        while running:
            clock.tick(30)        
            if chess.getTurn() == player_1.color and not chess.isGameOver():
                if type(player_1) == Human:
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            running = False
                            pygame.quit()
                            return
                        else:
                            controller.handle_event(event)   
                else:
                    print "AI 1 (WHITE) making turn"
                    player_1.make_next_move()
                    chess.moveNumber += 1
            elif chess.getTurn() == player_2.color and not chess.isGameOver():
                if type(player_2) == Human:
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            running = False
                            pygame.quit()
                            return
                        else:
                            controller.handle_event(event)   
                else:
                    print "AI 2 (BLACK) making turn"
                    player_2.make_next_move()
                    chess.moveNumber += 1
                    
            #multithread in python to be able to make calculations and quit during player's turn
            
#            if chess.getTurn() == AI.color:
#                    turn = machine.get_turn()
#                    board.updatewithMachine'sturn
                    
            if chess.isGameOver():
                view.title_game_display(chess)
                chess.validMoves = []
                chess.markPos[0] = -1
                chess.markPos[1] = -1
                for event in pygame.event.get():
                    if event.type == QUIT:
                        running = False
                        pygame.quit()
                        return
            else:
                pygame.display.set_caption('ChessBoard Client') 
                                            
            view.draw(chess)
            pygame.display.flip()  
            
        pygame.quit()
コード例 #16
0
ファイル: ChessMain.py プロジェクト: nadavleh/Chess_AI
def main():
    p.init()  # try init above if poblems arrise due to dependencies
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color(
        "white"))  # make the game window white initially (not neccessary)
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False  # this is a flag variable for when a move is made
    moveCount = 0

    loadImages(
    )  # only do this once before the while loop, load the pieces images
    running = True
    sqSelected = (
    )  # no square is selected, keep track of the last click of the user ( a tuple in the form (row, col))
    playerClicks = [
    ]  # keep track of player clicks (in the form of two tuples [(6,4), (4,4) ]
    #  where the first tuple is the click where we chose a piece and the second
    # tuple is its designated aquare we chose)

    gameOver = False
    ai = ChessAI.ChessAI()

    while running:
        # the method pygame.event records events from the opperating system,
        # which are related to the game window. events are essentialy muse clicks
        # or keyboard clicks. for example if the event type is "QUIT" it means
        # the user pressed the red x exit button. we essentialy pop the last event
        # recorded, query its type and act accordingly
        for e in p.event.get():
            # user pressed exit
            if e.type == p.QUIT:
                running = False
                p.quit()

            # mouse press handlers
            elif e.type == p.MOUSEBUTTONDOWN and gs.WhiteToMove:  #########ADDED here: and gs.WhiteToMove:
                location = p.mouse.get_pos(
                )  # pixel (x,y) location of the mouse

                col = location[
                    0] // SQ_SIZE  # convert pixel coordinates to square coordinates
                row = location[
                    1] // SQ_SIZE  # using "floor devision" opperator '//' see www.w3schools.com/python/python_operators.asp

                if sqSelected == (
                        row,
                        col):  # the user already clicked this square in the
                    # last loop run, i.e. the user selected the same square twice
                    # which we want to make a "undo select"
                    sqSelected = ()
                    playerClicks = []
                else:
                    sqSelected = (row, col)
                    playerClicks.append(
                        sqSelected
                    )  # so if the square selected is different from the last square selected,
                    # we append it to the list. now we need to make sure the list have just two moves
                    # and stop there.
                    if len(playerClicks) == 2:
                        # we can move the pices now, but to do that it would be a good practice
                        # to implement the movements via a designated class, which we add in the ChessEngine.py file.
                        move = ChessEngine.Move(
                            playerClicks[0], playerClicks[1],
                            gs.board)  # create a "Move" object
                        # print(move.getChessNotation()) # print the move to the screen for debugging purpossess

                        # now, once the player have chosen a piece and a destination square we want to check if its a valid move
                        # inorder to do so we check if the move made by the plaer is in the validMoves array of "Move" objects.
                        # this python property is very nice and saves us lines of code by typing the "in" command, however python implements it
                        # by regular loops and compare each var in the "move" object to each of validMoves objects. we can speed this
                        # up by modifying the "==" opperator of the "Move" Class in such a way so that cheking if two "Move" objects are the same
                        # only by comparing an ID which is distinct for each move

                        for i in range(len(validMoves)):
                            # =============================================================================
                            # we do it like this and not the shorter "if move in validMoves:"
                            # because that way we can make the move validMoves[i] which may
                            # have more information that the players move which has only initial
                            # square and end square, where the interlal move for instance may
                            # have information regarding en-passant or castling for example,
                            # which the player move doesnt have. However each move has its own ID number
                            # based on the iniial and end squares, so if the player has entered a move with the same
                            # ID as a special move (e.g. a castling move), the move that will be made is the one
                            # in the validMoves list (which has all the internal info needed), and not the players move.
                            # inorder to check if two move objects are equal, we have changed the "==" opperator
                            # of the Move class, so that two objects are equal iff two of them have the same ID
                            # =============================================================================
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                moveMade = True  # indicate that a move was made so we can update the valid moves
                                moveCount += 1

                                str = " white to move" if gs.WhiteToMove else " black to move"
                                print("moves made: ", moveCount, str)

                                sqSelected = (
                                )  # reset user clicks. doesnt matter if a move was made or not
                                playerClicks = []
                            if not moveMade:  # if the user chooses a pawn by mistake and wants o choose another pawn, the computer would
                                # think the player wanted to move one pawn over the other which is not a valid move, and thus will reset
                                # the playerClicks list. so this "else" statement allows the player to choose the other pawn withot all the fuss as before
                                playerClicks = [sqSelected]

            elif not gameOver and not gs.WhiteToMove:  #########ADDED here: all of the elif
                score, move = ai.alphaBeta(gs, depth=4)
                gs.makeMove(move)
                moveMade = True
                moveCount += 1

            # keyboard press handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  #undo move by pressing 'z'
                    gs.undoMove()
                    # once the "to be deleted" move was made, the validMoves array
                    # was updated according to the new board position which we want to undo.
                    # Hence, we need to once more update the validMoves array according to te last position
                    moveMade = True
                elif e.key == p.K_i:  #information
                    print("The valid moves are: ")
                    for move in validMoves:
                        print(move.pieceMoved[1], "to r =", move.endRow,
                              " c =", move.endCol)

        # we only want to search for valid moves if a move was made, otherwise each
        # while loop itteration we will update the validMoves array, which is a
        # costly opperation, and will generate the same valid moves if a move
        # wasnt made.
        if moveMade:
            # print(gs.board)
            validMoves = gs.getValidMoves()
            # print("number of valid moves: ", len(validMoves) )
            moveMade = False

        ############### now if the game ended draw the result on the screen ############
        if gs.checkmate:
            # print("kaki kaki kaki")
            # gameOver = True
            if gs.WhiteToMove:
                # drawText(screen, 'Black Wins by Checkmate') # drawText() isnt working a the moment
                pass
            else:
                # drawText(screen, 'White Wins by Checkmate')  # drawText() isnt working a the moment
                pass
        elif gs.stalemate:
            # gameOver = True
            # drawText(screen, 'Stalemate')  # drawText() isnt working a the moment
            pass

        # now generate the chess board gaphics
        drawGameState(screen, gs, validMoves, sqSelected)
        clock.tick(MAX_FPS)
        p.display.flip(
        )  # redraws the displayed frame, according to the MAX_FPS rate
コード例 #17
0
        if count >= 5:
            return 1  # 被判断方胜利
        else:
            return 0  # 未分出胜负

        self.TURN = -self.TURN  # 轮换


if __name__ == "__main__":

    AI = None
    choice = None  # 选择圈的id

    # AI
    AI1 = MovebyPos()
    AI2 = ChessAI(1, 2)

    def set_AI():
        global AI, choice
        ai = var.get()
        if ai == 1:
            AI = AI1
            if choice != None:
                cv.delete(choice)
            choice = cv.create_oval(50,
                                    0,
                                    250,
                                    200,
                                    fill=None,
                                    outline='yellow')
        else:
コード例 #18
0
def main():
    """
    The main driver for our code.
    This will handle user input and updating the graphics.
    """
    p.init()
    screen = p.display.set_mode(
        (BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    game_state = ChessEngine.GameState()
    valid_moves = game_state.getValidMoves()
    move_made = False  # flag variable for when a move is made
    animate = False  # flag variable for when we should animate a move
    loadImages()  # do this only once before while loop
    running = True
    square_selected = (
    )  # no square is selected initially, this will keep track of the last click of the user (tuple(row,col))
    player_clicks = []  # this will keep track of player clicks (two tuples)
    game_over = False
    ai_thinking = False
    move_undone = False
    move_finder_process = None
    move_log_font = p.font.SysFont("Arial", 14, False, False)
    player_one = True  # if a human is playing white, then this will be True, else False
    player_two = False  # if a hyman is playing white, then this will be True, else False

    while running:
        human_turn = (game_state.white_to_move
                      and player_one) or (not game_state.white_to_move
                                          and player_two)
        for e in p.event.get():
            if e.type == p.QUIT:
                p.quit()
                sys.exit()
            # mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                if not game_over:
                    location = p.mouse.get_pos(
                    )  # (x, y) location of the mouse
                    col = location[0] // SQUARE_SIZE
                    row = location[1] // SQUARE_SIZE
                    if square_selected == (
                            row, col
                    ) or col >= 8:  # user clicked the same square twice
                        square_selected = ()  # deselect
                        player_clicks = []  # clear clicks
                    else:
                        square_selected = (row, col)
                        player_clicks.append(
                            square_selected
                        )  # append for both 1st and 2nd click
                    if len(player_clicks
                           ) == 2 and human_turn:  # after 2nd click
                        move = ChessEngine.Move(player_clicks[0],
                                                player_clicks[1],
                                                game_state.board)
                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                game_state.makeMove(valid_moves[i])
                                move_made = True
                                animate = True
                                square_selected = ()  # reset user clicks
                                player_clicks = []
                        if not move_made:
                            player_clicks = [square_selected]

            # key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # undo when 'z' is pressed
                    game_state.undoMove()
                    move_made = True
                    animate = False
                    game_over = False
                    if ai_thinking:
                        move_finder_process.terminate()
                        ai_thinking = False
                    move_undone = True
                if e.key == p.K_r:  # reset the game when 'r' is pressed
                    game_state = ChessEngine.GameState()
                    valid_moves = game_state.getValidMoves()
                    square_selected = ()
                    player_clicks = []
                    move_made = False
                    animate = False
                    game_over = False
                    if ai_thinking:
                        move_finder_process.terminate()
                        ai_thinking = False
                    move_undone = True

        # AI move finder
        if not game_over and not human_turn and not move_undone:
            if not ai_thinking:
                ai_thinking = True
                return_queue = Queue()  # used to pass data between threads
                move_finder_process = Process(target=ChessAI.findBestMove,
                                              args=(game_state, valid_moves,
                                                    return_queue))
                move_finder_process.start()

            if not move_finder_process.is_alive():
                ai_move = return_queue.get()
                if ai_move is None:
                    ai_move = ChessAI.findRandomMove(valid_moves)
                game_state.makeMove(ai_move)
                move_made = True
                animate = True
                ai_thinking = False

        if move_made:
            if animate:
                animateMove(game_state.move_log[-1], screen, game_state.board,
                            clock)
            valid_moves = game_state.getValidMoves()
            move_made = False
            animate = False
            move_undone = False

        drawGameState(screen, game_state, valid_moves, square_selected)

        if not game_over:
            drawMoveLog(screen, game_state, move_log_font)

        if game_state.checkmate:
            game_over = True
            if game_state.white_to_move:
                drawEndGameText(screen, "Black wins by checkmate")
            else:
                drawEndGameText(screen, "White wins by checkmate")

        elif game_state.stalemate:
            game_over = True
            drawEndGameText(screen, "Stalemate")

        clock.tick(MAX_FPS)
        p.display.flip()
コード例 #19
0
def main():
    '''
    The main driver for our code.
    This will handle user input and updating the graphics.
    '''
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    game_state = ChessEngine.GameState()
    valid_moves = game_state.getValidMoves()
    move_made = False #flag variable for when a move is made
    animate = False #flag variable for when we should animate a move
    loadImages() #do this only once before while loop
    
    running = True
    square_selected = () #no square is selected initially, this will keep track of the last click of the user (tuple(row,col))
    player_clicks = [] #this will keep track of player clicks (two tuples)
    game_over = False
    
    white_did_check = ""
    black_did_check = ""
    last_move_printed = False
    moves_list = []
    
    turn = 1
    
    player_one = True #if a human is playing white, then this will be True, else False
    player_two = False #if a human is playing white, then thiss will be True, else False

    while running:
        human_turn = (game_state.white_to_move and player_one) or (not game_state.white_to_move and player_two)
        for e in p.event.get():  
            if e.type == p.QUIT:
                running = False
                p.quit()
                sys.exit()
            #mouse handler            
            elif e.type == p.MOUSEBUTTONDOWN:
                if not game_over and human_turn:
                    location = p.mouse.get_pos() #(x, y) location of the mouse
                    col = location[0] // SQUARE_SIZE
                    row = location[1] // SQUARE_SIZE
                    if square_selected == (row, col): #user clicked the same square twice
                        square_selected = () #deselect
                        player_clicks = [] #clear clicks
                    else:
                        square_selected = (row, col)
                        player_clicks.append(square_selected) #append for both 1st and 2nd click
                    if len(player_clicks) == 2: #after 2nd click                                                                    
                        move = ChessEngine.Move(player_clicks[0], player_clicks[1], game_state.board)  
                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                game_state.makeMove(valid_moves[i])
                                move_made = True
                                animate = True
                                square_selected = () #reset user clicks
                                player_clicks = []   
                        if not move_made:
                            player_clicks = [square_selected]

            #key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z: #undo when 'z' is pressed
                    if game_state.white_to_move:
                        if turn > 1:
                            turn -= 1
                    game_state.undoMove()
                    move_made = True
                    animate = False
                    game_over = False
                    last_move_printed = False

                if e.key == p.K_r: #reset the game when 'r' is pressed
                    game_state = ChessEngine.GameState()
                    valid_moves = game_state.getValidMoves()
                    square_selected = ()
                    player_clicks = []
                    move_made = False
                    animate = False
                    game_over = False
                    turn = 1    
                    last_move_printed = False
                    moves_list = []
                    
        #AI move finder
        if not game_over and not human_turn:
            AI_move = ChessAI.findBestMoveNegaMaxAlphaBeta(game_state, valid_moves)
            if AI_move is None:
                AI_move = ChessAI.findRandomMove(valid_moves)
            game_state.makeMove(AI_move)
            move_made = True
            animate = True
        
        if move_made:
            if game_state.checkForPinsAndChecks()[0]:
                if not game_state.white_to_move:
                    white_did_check = "+"
                else:
                    black_did_check = "+"
            if game_state.white_to_move:
                moves_list.append(f"\n{turn}. {game_state.move_log[-2].getChessNotation()}{white_did_check} {game_state.move_log[-1].getChessNotation()}{black_did_check}")
                print(f"\n{turn}. {game_state.move_log[-2].getChessNotation()}{white_did_check} {game_state.move_log[-1].getChessNotation()}{black_did_check}", end= "")
                turn+=1
                white_did_check = ""
                black_did_check = ""
            
            
            
            if animate:
                animateMove(game_state.move_log[-1], screen, game_state.board, clock)
            valid_moves = game_state.getValidMoves()
            move_made = False
            animate = False
                    
                            
        drawGameState(screen, game_state, valid_moves, square_selected) 
        
        if game_state.checkmate:
            game_over = True
            if game_state.white_to_move:
                drawText(screen, "Black wins by checkmate")
                if not last_move_printed:
                    moves_list[-1] += "+"
                    moves_list.append("result: 0-1")
                    print("+")
                    print("result: 0-1")
                    last_move_printed = True
                    saveGame(moves_list)
                    
            else:
                drawText(screen, "White wins by checkmate")
                if not last_move_printed:
                    moves_list.append(f"\n{turn}. {game_state.move_log[-1].getChessNotation()}++")
                    moves_list.append("result: 1-0")
                    print(f"\n{turn}. {game_state.move_log[-1].getChessNotation()}++")
                    print("result: 1-0")
                    last_move_printed = True
                    saveGame(moves_list)

        elif game_state.stalemate:
            game_over = True
            drawText(screen, "Stalemate")
            if not last_move_printed:
                if not game_state.white_to_move:
                    moves_list.append(f"\n{turn}. {game_state.move_log[-1].getChessNotation()}")
                    moves_list.append("result: 1/2-1/2")
                    print(f"\n{turn}. {game_state.move_log[-1].getChessNotation()}")
                    print("result: 1/2-1/2")
                    last_move_printed = True      
                    saveGame(moves_list)
        
        clock.tick(MAX_FPS)
        p.display.flip()