简体   繁体   English

如何使计时器变慢? (蟒蛇)

[英]How to make a slower timer? (Python)

I'm fairly new to using Python, and I'm trying to get a hit timer so that in my game when my player is hit, it needs to wait a couple seconds before he can be hit again. 我对使用Python相当陌生,我想尝试一个命中计时器,以便在我的游戏中,当我的玩家被击中时,它需要等待几秒钟才能再次被击中。

I thought I could just do something like: 我以为我可以做这样的事情:

while hitTimer > 0:
    hitTimer -= 1

and being hit resets the counter to 10 , and requiring the counter to be > 0 to be able to be hit again, but it goes way to fast. 并被击中会将计数器重置为10 ,并要求计数器> 0才能再次被击中,但是它很快就消失了。

I tried using very small numbers like -= .00005 but that just makes my program lag bad. 我尝试使用-= .00005这样的很小的数字,但这只会使程序滞后。

How can I make it so it takes away 1 per second or something like that? 我如何才能使它每秒减少1个?

Thanks for any help. 谢谢你的帮助。

In order to check for exactly 10 seconds, do this: 为了准确地检查10秒,请执行以下操作:

import time
# record when person was first hit.
previousHit = time.time()

if time.time() - previousHit > 10:
    # The rest of your logic for getting hit.
    previousHit = time.time() # Reset the timer to get the hit again.

Use time.clock() to check the time and time.sleep() to wait. 使用time.clock()检查时间和time.sleep()等。

Never rely on CPU speed for timing code. 切勿依赖CPU速度来获取定时代码。

You just record the time someone was hit, using time.time() : 您只需使用time.time()记录有人被击中的时间:

import time

lastHit = time.time()

And then compare the current time against lastHit : 然后将当前时间与lastHit进行比较:

if time.time() - lastHit > NUMBER_OF_SECONDS:
  # ... do seomthing about getting hit ...
  lastHit = time.time()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM