gpt4 book ai didi

python-3.x - PyGame,等待计算机决定它的 Action

转载 作者:行者123 更新时间:2023-12-05 05:14:26 26 4
gpt4 key购买 nike

好的

所以我在 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 卡住了。

我应该如何实现?

最佳答案

一个简单的解决方案是在 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

关于python-3.x - PyGame,等待计算机决定它的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com