使用 Python 2.7.11,time.time()
函数会导致 pygame 出现问题。我有检查pygame事件并响应它们的函数。
def check_keydowns(event):
global points
""" Checks the key that has been pressed """
global running
if event.key == pygame.K_SPACE:
print "Hi"
elif event.key == pygame.K_q:
running = False
elif event.key == pygame.K_RIGHT:
points += 1
def check_keyups(event):
global points
""" Checks the key that has been released """
if event.key == pygame.K_SPACE:
print "Bye"
elif event.key == pygame.K_RIGHT:
points += 1
def check_events():
""" Check the type of event from the user """
global running
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
check_keydowns(event)
elif event.type == pygame.KEYUP:
check_keyups(event)
我的主要问题是time.time()
似乎对time.time() - t0 == 1
没有反应。
t0 = time.time()
# The main loop for the game
while running:
update(GRAY, x, y, points) # Updates the text and redraws the screen
check_events() # Checks key presses
if time.time() - t0 == 1:
points += 1
t0 = time.time()
我希望屏幕上的文本每秒增加 1 个。但问题是变量points
保持为零(这就是变量的初始化方式 - 任何其他数字points
都不会改变。此外,points
变量是一个int
。我也尝试打印 points
的值,但同样,0 是输出。
我不太了解python,所以请尝试尽可能简化答案(解释会很好(。
谢谢
你的问题是你正在使用非常详细的浮点数,减去它们并期望它等于一个整数。
这几乎是不可能的。
而是使用简单的不等式来检查是否已经过去了 1 秒。
t0 = time.time()
# The main loop for the game
while running:
update(GRAY, x, y, points) # Updates the text and redraws the screen
check_events() # Checks key presses
if time.time() - t0 > 1:
points += 1
t0 = time.time()
而不是检查两个浮点数在减去时是否正好等于 1。只需检查差值是否大于 1。
我希望这个答案对您有所帮助,如果您有任何其他问题,请随时在下面发表评论。