Простое решение состоит в том, чтобы запустить соответствующую функцию блокировки в 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](https://i.stack.imgur.com/vQmRe.gif)