[英]Running infinite loops using threads in Pygame
我遇到了一个问题。 如果你有解决方案,请告诉我你是怎么做的。
我有几个必须使用多线程的函数,每个函数内部都有一个 While 循环。 当我使用多线程时,pygame 会遇到问题。 我还准备了一个示例代码,使问题更容易理解。 请指导我理解这个问题。
为什么pygame死机,程序运行不正常?
import threading
import pygame
pygame.init()
SIZE = DW, DH = 900, 600
DS = pygame.display.set_mode(size=SIZE)
pygame.display.set_caption("Stackoverflow/Pygame/Multithreading")
FPS = 60
def main():
x = DW // 2
y = DH // 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock = pygame.time.Clock()
pygame.display.update()
DS.fill(0)
clock.tick(60)
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
y -= 5
if key[pygame.K_DOWN]:
y += 5
if key[pygame.K_RIGHT]:
x += 5
if key[pygame.K_LEFT]:
x -= 5
pygame.draw.circle(surface=DS, color=(255, 100, 100), center=(x, y), radius=15)
def one():
while True:
print("One")
def two():
while True:
print("Two")
t1 = threading.Thread(target=main)
t2 = threading.Thread(target=one)
t3 = threading.Thread(target=two)
if __name__ == '__main__':
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
我决定解决这个问题,我会为你发布解决方案。
import threading
import pygame
pygame.init()
SIZE = DW, DH = 900, 600
DS = pygame.display.set_mode(size=SIZE)
pygame.display.set_caption("Stackoverflow/Pygame/Multithreading")
def main():
x = DW // 2
y = DH // 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock = pygame.time.Clock()
pygame.display.update()
DS.fill(0)
clock.tick(60)
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
y -= 5
if key[pygame.K_DOWN]:
y += 5
if key[pygame.K_RIGHT]:
x += 5
if key[pygame.K_LEFT]:
x -= 5
pygame.draw.circle(surface=DS, color=(255, 100, 100), center=(x, y), radius=15)
def one():
while True:
if not pygame.get_init():
break
pass
def two():
while True:
if not pygame.get_init():
break
pass
t2 = threading.Thread(target=one)
t3 = threading.Thread(target=two)
t2.start()
t3.start()
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.