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

问题描述 投票:2回答:1

好的

所以我在pygame上构建一个tic-tac-toe,其中A玩家可以与玩家,计算机与玩家或计算机与计算机对战。

我已经开发了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冻结了。

我该如何实现呢?

python-3.x pygame minimax
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.