如何创建允许其他代码作为

2024-05-17 16:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个业余程序员。我正在为一个生物学项目做一个小游戏,但是我在代码中遇到了一个问题。我有一个循环,每两秒钟给可变的阳光加上+1。但是,既然我已经创建了循环,那么循环下面的所有代码都是不起作用的。我猜是因为它在等待循环结束。有没有办法让循环始终运行,但允许代码同时在其序列中运行?你知道吗

print("Game started!")
sunlight = 0
while True:
  time.sleep(2)
  sunlight += 1
  commands = input("Type stats to see which molecules you have, type carbon to get carbon\ndioxide, and type water to get water: ")
  if commands == ("stats"):
    print("Sunlight: ",sunlight,"")

Tags: to项目代码getstatstypecommands程序员
2条回答

作为初学者,我不建议您使用multithreadingasyncio。相反,只要开始时间,当用户输入“stats”时,elapsed time//2将等于sunlight。你知道吗

import time
start_time = time.time()
while True:
    commands = input("Type stats to see which molecules you have, type carbon to get carbon\ndioxide, and type water to get water: ")
    if commands == ("stats"):
        sunlight = (time.time()-start_time)//2   # elapsed time // 2
        print("Sunlight: ", sunlight, "")

您的sunlight变量基本上起着时钟的作用;它计算程序开始后的秒数的一半。与其使用time.sleep()实现自己的时钟,不如只使用time库中的现有时钟。你知道吗

函数time.monotonic返回秒数,因此您可以使用它通过保存开始时间来获取当前阳光,然后每次您想知道sunlight的值时,将当前时间和开始时间之差除以2。你知道吗

start_time = time.monotonic()

def get_sunlight():
    current_time = time.monotonic()
    return int(current_time - start_time) // 2

为此,最好使用monotonic()函数而不是clock()函数,因为clock()函数is deprecated as of Python 3.3

The time.clock() function is deprecated because it is not portable: it behaves differently depending on the operating system.

出于这个目的,它也比time()函数好,因为time()will affect the result对系统时钟的更改(例如由于夏时制而向前或向后):

While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

相关问题 更多 >