在下面的代码中,我在Pygame中得到了一个带有按钮的屏幕。现在,我想单击按钮,然后启动random()
函数,并在5秒钟后从按钮开始从屏幕返回到屏幕,让我选择再次单击并再次调用随机函数。
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position.
if button.collidepoint(event.pos):
# Incremt the number.
number += 1
random()
loop()
pygame.quit()
答案 0 :(得分:1)
添加一个状态变量(runRandom
),该变量指示是否必须运行函数random
:
runRandom = False
while not done:
# [...]
if runRandom:
random()
添加用户定义的pygame.event
,可将其用作计时器:
runRandomEvent = pygame.USEREVENT + 1
for event in pygame.event.get():
# [...]
elif event.type == runRandomEvent:
# [...]
如果random
未运行 ,则允许按下按钮。如果按下按钮,则进入状态runRandom
,并在确定的时间段内(例如5000毫秒= 5秒)启动计时器(pygame.time.set_timer()
):
# [...]
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if button.collidepoint(event.pos) and not runRandom:
# [...]
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000)
时间过去后,请random
停止运行runRandom = False
并停止计时器:
# [...]
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
以某种方式将建议应用于您的代码:
# define user event for the timer
runRandomEvent = pygame.USEREVENT + 1
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
runRandom = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position and "random" is not running
if button.collidepoint(event.pos) and not runRandom:
# Incremt the number.
number += 1
# Start timer and enable running "random"
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000) # 5000 milliseconds
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
# [...]
# run "random"
if runRandom:
random()
# [...]