Skip to main content
 首页 » 编程设计

python之在 Python 中使用时间模块时如何同时运行两个 while 循环

2025年05月04日1498°冷暖

基本上我使用的是pygame。我的 gameloop 有很多事件处理和控制 Sprite 的位置等。

每隔 1 秒雪球 Sprite 就会从屏幕左侧进来,但是当在游戏函数中输入这个 while 循环时,只会运行 while 循环,并且游戏只是卡住,因为它只等待 1 秒并更新 Sprite ,不关注事件处理或任何事情。

即使使用两个不同的函数,在运行滚雪球函数时,程序也无法专注于这两个函数,并且仍然停留在滚雪球函数上。

我不想使用任何复杂的东西,只是一个简单优雅的解决方案。我看过线程,但它看起来太复杂了,而且我是 Python 的新手。

请您参考如下方法:

不要使用 time 模块。

只需创建一个事件,并告诉 pygame 每秒将该事件放入事件队列(使用 pygame.time.set_timer 函数)。然后您可以像处理其他事件一样在主循环中处理它。

这是一个简单的例子。它使用带有 pygame.time.set_timer 的自定义事件和一个主循环,不需要 time 模块:

import pygame 
import random 
pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
player, dir, size = pygame.Rect(100,100,20,20), (0, 0), 20 
MOVEEVENT, APPLEEVENT, trail = pygame.USEREVENT+1, pygame.USEREVENT+2, [] 
pygame.time.set_timer(MOVEEVENT, 250) 
pygame.time.set_timer(APPLEEVENT, 1000) 
apples=[] 
while True: 
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_w]: dir = 0, -1 
    if keys[pygame.K_a]: dir = -1, 0 
    if keys[pygame.K_s]: dir = 0, 1 
    if keys[pygame.K_d]: dir = 1, 0 
 
    if pygame.event.get(pygame.QUIT): break 
    for e in pygame.event.get(): 
        if e.type == MOVEEVENT: # this event happens every 250 ms 
            trail.append(player.inflate((-10, -10))) 
            trail = trail[-5:] 
            player.move_ip(*[v*size for v in dir]) 
        if e.type == APPLEEVENT: # this event happens every 1000 ms 
            apples.append(pygame.rect.Rect(random.randint(0, 30) * 10, random.randint(0, 30) * 10, 10, 10)) 
 
    screen.fill((0,120,0)) 
    for t in trail: 
        pygame.draw.rect(screen, (255,0,0), t) 
    for a in apples: 
        pygame.draw.rect(screen, (0,255,100), a) 
 
    pygame.draw.rect(screen, (255,0,0), player) 
    pygame.display.flip() 

这应该会让您了解如何解决您的问题。不要使用 time.sleep,它只会阻塞你的循环。