我想制作一个程序,让你在游戏中失去“能量”
当你按下回车键时,我就这样做了,你会获得“能量”:
if question == '':
print("press enter to gain energy")
while True:
energyup = input()
if energyup == "":
energy += energygain
print(energy)
我还想让你每0.5秒失去一次能量。我不知道怎么做
我试着加上:
while True:
energy -= energyloss
print(energy)
time.sleep(1)
到程序的底部,但这会使你的能量损失太快,我不知道是否有办法让一行代码休眠,而其他一切都在继续(我使用的time.sleep
会影响整个程序),最重要的是,它会使能量获取系统无法工作
对不起,如果这是一个愚蠢的问题,我刚刚开始学习编程,这是我在这个网站上的第一个问题
与
time.sleep
不同的是,只需检查上次能量损失时间是否超过0.5秒:这使得游戏循环代码的其余部分可以并发运行
我认为线程的解决方案可能会有所帮助,但从您的问题陈述来看,我相信您只需要有一个函数来提供累积的总能量和随时间损失的能量之差
为此,您可以在开始时启动计时器,并创建一个函数,该函数将使用当前时间减去执行时间来计算每次的能量损失
以下内容可能足以满足您的情况:
将调试日志添加到打印其行为方式的方法中:
输出:
你需要使用线程。线程A负责消耗,线程B监听输入
使用螺纹。锁紧以确保螺纹安全
增加能量时还需要调用
with lock
相关问题 更多 >
编程相关推荐