PyGame,等待计算机决定其移动

时间:2018-09-24 11:36:19

标签: python-3.x pygame minimax

好吧

因此,我正在pygame上制作一个井字游戏,其中玩家可以与玩家,计算机与玩家或计算机与计算机对抗。

我已经开发了MiniMaxAgent()的代码,该代码将其输入作为2D矩阵并返回(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()时,它应该在几秒钟内为我返回最佳移动。但是PyGame死机了。

我应该如何实现呢?

1 个答案:

答案 0 :(得分:2)

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

这是一个简单的例子。请注意,在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()

enter image description here