Skip to main content
 首页 » 编程设计

python之定时 Action之随机

2025年05月04日32qlqwjy

我试图在一个简单的游戏中每 0.5 - 2 秒随机创建一个障碍。我已经有了创建障碍的功能,但我无法为实例化计时。我试过研究这个,但我还没有想出任何相关的东西。你们能帮帮我吗?

请您参考如下方法:

您可以使用 pygame.time.set_timer 安排您自己的事件

这是一个每 0.5-2 秒更改一次背景颜色的最小示例:

import pygame, random 
 
pygame.init() 
screen, bg = pygame.display.set_mode((200, 200)), pygame.color.Color('Grey') 
pygame.time.set_timer(pygame.USEREVENT, random.randint(500, 2001)) 
 
while True: 
    for e in pygame.event.get(): 
        if e.type == pygame.QUIT: break 
        if e.type == pygame.USEREVENT: 
            bg = random.choice(pygame.color.THECOLORS.values()) 
            pygame.time.set_timer(pygame.USEREVENT, random.randint(500, 2001)) 
    else: 
        screen.fill(bg) 
        pygame.display.flip() 
        continue 
    break