PyGame,等待计算机决定它的移动

PyGame, waiting for computer to decide its move

好的

所以我正在 pygame 上构建一个井字游戏,玩家可以在其中对战玩家、计算机对玩家或计算机对计算机。

我已经开发了 MiniMaxAgent() 的代码,它将其输入作为二维矩阵,return 是 (row, col) 的输入。问题是这段代码可能需要几秒钟才能在 nxn 板上执行。因此 pyGame 代码挂起。

示例事件循环:

while running:
    mouseClicked = False
    DISPLAYSURF.fill(BGCOLOR)
    renderBoard()
    #event handlers
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == MOUSEMOTION:
                mouseX, mouseY = event.pos
        elif event.type == MOUSEBUTTONUP:
            mouseX, mouseY = event.pos
            mouseClicked = True

    row, col = players[currentPlayer].turn(currentPlayer*board.state)
    board.state[row][col] = currentPlayer
    currentPlayer = currentPlayer * -1
    pygame.display.update()

如您所见,当我调用函数 players[currentPlayer].turn() 时,它应该 return 我在几秒钟内找到最佳着法。但是 PyGame 冻结了。

我应该如何实施?

一个简单的解决方案是运行 Thread 中有问题的阻塞函数。这将使您的游戏循环保持 运行ning。

这是一个简单的例子。注意循环如何保持 运行ning 而 turn 函数浪费了一些时间。

import pygame
import pygame.freetype
import random
import time
import threading
pygame.init()
screen = pygame.display.set_mode((800, 300))

PLAYER_TURN, AI_TURN = 0, 1
font = pygame.freetype.Font(None, 30)
state = PLAYER_TURN
running = True
result = None

def turn(boardstate):
    print('thinking about ' + boardstate + '....')
    time.sleep(1)
    print('thinking very hard....')
    time.sleep(1)
    global result
    global state
    result = random.randint(10, 100)
    state = PLAYER_TURN

r = pygame.rect.Rect((0, 250, 100, 50))

while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        elif e.type == pygame.MOUSEBUTTONUP:
            if state == PLAYER_TURN:
                state = AI_TURN
                threading.Thread(target=turn, args=['an argument']).start()

    screen.fill(pygame.color.Color('grey'))
    if state == PLAYER_TURN:
        font.render_to(screen, (50, 50), 'It is your turn. Click anything')
        if result:
            font.render_to(screen, (50, 180), 'AI said: ' + str(result))
    elif state == AI_TURN:
        font.render_to(screen, (50, 50), 'Waiting for AI')
        pygame.draw.rect(screen, pygame.color.Color('red'), r)
        r.move_ip(1, 0)
        if not screen.get_rect().contains(r):
            r.x = 0

    pygame.display.update()