【问题标题】:How to increase a integer every second [closed]如何每秒增加一个整数[关闭]
【发布时间】:2022-02-09 14:14:45
【问题描述】:

我正在用 Python 制作一个躲避游戏,我希望分数每秒增加 1,但问题是我不知道怎么做。如果能找到一个我不必更改太多代码的解决方案,那就太好了。

有人可以帮忙吗?

【问题讨论】:

    标签: python time


    【解决方案1】:

    当您遍历游戏循环时,您可以使用时间库检查当前时间。然后,您可以检查自上次获得积分以来是否已经过了一秒。 它可能看起来像这样:

    import time
    points = 0
    currentTime = time.time()
    previousPointAwardedTime = currentTime
    
    while gameRunning == True:
        ...
        currentTime = time.time()
        if (currentTime - previousPointAwardedTime) >= 1:
            points += 1
            previousPointAwardedTime = currentTime
    

    【讨论】:

    • 谢谢解决,但我也想问一个问题,为什么一定要在if语句中使用?
    • 这个 if 语句将确定是否已经过了一整秒。如果您的游戏在 0.001 秒内循环,则 if 语句将阻止添加一个点,直到发生 1000 次 while 循环迭代。
    • 哦,谢谢!!!
    【解决方案2】:

    你可以试试asyncio

    import asyncio
    
    score = 0  # starting game with a score of zero
    
    
    async def s():
        global score
        score += 1 #increasing score by 1
        await asyncio.sleep(1)  #waiting for 1 second
    
    while True:  #while game is running
        asyncio.run(s()) #calling function
        print(score)  #printing score
    

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2023-04-09
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多