是否有一个形式来绘制与Pygame并发编程的背景?



我正在用pygame用python开发一个视频游戏,我想用我的函数"draw"绘制场景。并使用并发编程对其进行优化,并在整个运行过程中使用线程来管理绘图。我使用ThreadPoolExecutor可以重用线程,但绘图非常糟糕,因为有时背景在播放器(正方形)后面,有时在播放器前面。

import sys
import pygame
import threading
from concurrent.futures import ThreadPoolExecutor

pygame.init()
# ----------------------------------------
#                 Variables
# ----------------------------------------
width = 600
height = 600
square = pygame.Rect(100,100,100,100)
surface = pygame.display.set_mode( (width, height) )
executor = ThreadPoolExecutor(max_workers=1)
pygame.display.set_caption('Texto')
font = pygame.font.SysFont("arial", 24)

# ----------------------------------------
#                 Function
# ----------------------------------------

def draw():
surface.fill((20, 210, 190))

# ----------------------------------------
#                   Loop
# ----------------------------------------

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
executor.submit(draw)
pygame.draw.rect(surface,(100,100,100),square)
pygame.display.update()

我怎么做才能有播放器背后的背景,做它重用线程来优化它?

你必须在一个线程中完成所有的绘图。在不同的线程中绘制背景没有任何好处。它们不能保证不同线程之间的执行顺序。

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
surface.fill((20, 210, 190))
pygame.draw.rect(surface,(100,100,100),square)
pygame.display.update()

所有图形管道操作都在单个线程上执行是很常见的。而游戏逻辑可以在不同的线程中完成。
使用pygame,您还需要处理主线程上的事件(参见pygame.event.get()在线程内不返回任何事件)。

最新更新