我正在尝试制作一个让你失去“能量”的程序(Python 3)

2024-09-30 14:36:29 发布

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

我想制作一个程序,让你在游戏中失去“能量”

当你按下回车键时,我就这样做了,你会获得“能量”:

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会影响整个程序),最重要的是,它会使能量获取系统无法工作

对不起,如果这是一个愚蠢的问题,我刚刚开始学习编程,这是我在这个网站上的第一个问题


Tags: 程序true游戏iftimesleepenergy能量
3条回答

time.sleep不同的是,只需检查上次能量损失时间是否超过0.5秒:

prev_time = time.time()
while True:
    # rest of the game loop
    curr_time = time.time()
    if curr_time - prev_time > 0.5:
        energy -= energyloss
        prev_time = curr_time

这使得游戏循环代码的其余部分可以并发运行

我认为线程的解决方案可能会有所帮助,但从您的问题陈述来看,我相信您只需要有一个函数来提供累积的总能量和随时间损失的能量之差

为此,您可以在开始时启动计时器,并创建一个函数,该函数将使用当前时间减去执行时间来计算每次的能量损失

以下内容可能足以满足您的情况:

import time

energy_gain_constant = 5
energy_loss_constant = -2
total_energy_gain = 0
start_time = time.time()

def print_total_energy():
    print(total_energy_gain + int((time.time() - start_time) / 0.5) * energy_loss_constant)


print("press enter to gain energy")
while True:
    energyup = input()
    if energyup == "":
        total_energy_gain += energy_gain_constant

    print_total_energy()

将调试日志添加到打印其行为方式的方法中:

def print_total_energy():
    total_energy_lost = int((time.time() - start_time) / 0.5) * energy_loss_constant
    print(f'Total execution time: {time.time() - start_time}')
    print(f'Total energy lost: {total_energy_lost}')
    print(f'Total energy gained: {total_energy_gain}')
    print(f'Total Energy: {total_energy_gain + total_energy_lost}')

输出:

Total execution time: 12.982820272445679
Total energy lost: -50
Total energy gained: 65
Total Energy: 15

你需要使用线程。线程A负责消耗,线程B监听输入


energy = 0
energyloss = 1
energygain = 1
lock = threading.Lock()


def consumption():
    global energy
    while 1:
        with lock:
            energy -= energyloss
            time.sleep(0.5)
            print(energy)


threading.Thread(target=consumption).start()

使用螺纹。锁紧以确保螺纹安全

增加能量时还需要调用with lock

相关问题 更多 >