randint上的Python计时器

时间:2015-03-26 16:52:48

标签: python-2.7 pygame

如果我有这段代码:

r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
screen.fill((r, g, b))

如何设置它以便每隔10秒钟选择一个随机数?

1 个答案:

答案 0 :(得分:2)

该问题有许多不同的方法。 :)

一种非常简单,快速和肮脏的方法是在主游戏循环中暂停游戏(即设置延迟)一段时间。你可以使用PyGames pygame.time.delay()函数:

#import pygame and randint function from random module
import pygame
from random import randint

pygame.init()

screen = pygame.display.set_mode((800,800)) #create screen

while True:
    #get events from the event queue
    for ev in pygame.event.get():
        if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                pygame.quit()
                exit()

    #create random variables r, g and b
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)

    #fill screen
    screen.fill((r, g, b))

    #update whole screen
    pygame.display.flip()

    #set timout for 500ms (i.e. pause game for 500ms)
    pygame.time.delay(500)

这种方法存在的问题是,你无法获得任何事件,并且在游戏暂停的时间内(例如500ms)做一些的事情。< / p>

要避免此问题,您可以创建您的自己的事件,该事件在每个给定的毫秒数的事件队列中出现。您可以使用pygame.time.set_timer()创建活动:

import pygame
from random import randint

pygame.init()

#create a new event id called event_500ms
event_500ms = pygame.USEREVENT + 1

#set timer event to appear on the event queue every 500 number of milliseconds
pygame.time.set_timer(event_500ms, 500)

screen = pygame.display.set_mode((800,800))

while True:
    #get events from the event queue
    for ev in pygame.event.get():
        if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                pygame.quit()
                exit()

        #check for event_500ms event
        if ev.type == event_500ms:

            r = randint(0, 255)
            g = randint(0, 255)
            b = randint(0, 255)

            screen.fill((r, g, b))

            pygame.display.flip()

我希望这会有所帮助:)