如何在变量大于0时同时执行两个Python函数?
问题与解决方案
问题说明
想要实现的效果:在health大于0时,一边持续扣除health值,一边提示用户发起攻击。但当前代码中kidsenemyattack()和kidfight()无法同时执行,互相覆盖。
原代码
import time health = 100 kidsHP = 10 def kidsenemyattack(): global health print('The enemy deals damage!') health -= 4 print(health) print('==========') time.sleep(3) kidsenemyattack() def kidfight(): global kidsHP ready = input('You can attack!') if ready in ['1','one','One']: kidsHP -= 1 time.sleep(2.5) while health > 0: kidsenemyattack() and kidfight() if kidsHP <= 0: print("You've defeated the evil kids")
问题根源
kidsenemyattack()用递归调用自己,一旦进入这个函数就会无限循环,永远不会执行到kidfight()。and运算符不是用来同时执行两个函数的,它只会在第一个函数返回True时才执行第二个,而这里函数没有返回值(默认返回None),所以第二个函数根本不会运行。
解决方案:使用多线程
用Python的threading模块让两个任务并行执行,一个负责敌人持续攻击,一个负责接收用户输入发起攻击,主线程监控战斗状态。
修改后的代码
import time import threading health = 100 kidsHP = 10 stop_flag = False # 全局标记控制线程停止 def kidsenemyattack(): global health, stop_flag while health > 0 and not stop_flag: print('The enemy deals damage!') health -= 4 print(f"Your current health: {health}") print('==========') time.sleep(3) if health <= 0: print("You've been defeated by the evil kids!") def kidfight(): global kidsHP, stop_flag while kidsHP > 0 and not stop_flag: try: ready = input('You can attack! Enter 1/one to attack: ') if ready.lower() in ['1', 'one']: kidsHP -= 1 print(f"Evil kid's HP: {kidsHP}") if kidsHP <= 0: print("You've defeated the evil kids!") stop_flag = True time.sleep(0.5) # 防止输入过于频繁 except KeyboardInterrupt: stop_flag = True break # 启动两个守护线程,主线程结束时自动退出 attack_thread = threading.Thread(target=kidsenemyattack, daemon=True) fight_thread = threading.Thread(target=kidfight, daemon=True) attack_thread.start() fight_thread.start() # 主线程监控战斗状态,直到结束 while not stop_flag and health > 0 and kidsHP > 0: time.sleep(1)
代码说明
- 用
stop_flag统一控制两个线程的停止逻辑,避免线程无法正常退出。 - 把递归改成
while循环,防止递归深度过大导致栈溢出。 - 守护线程(
daemon=True)确保主线程结束时子线程自动终止。
替代方案:单循环轮询(无需多线程)
如果不想用线程,可以在主循环里轮询敌人攻击时间和用户输入,通过非阻塞输入实现近似同时运行的效果:
import time import sys import select health = 100 kidsHP = 10 last_enemy_attack = time.time() while health > 0 and kidsHP > 0: # 每隔3秒触发一次敌人攻击 if time.time() - last_enemy_attack >= 3: print('The enemy deals damage!') health -= 4 print(f"Your current health: {health}") print('==========') last_enemy_attack = time.time() # 非阻塞检查用户输入 if select.select([sys.stdin], [], [], 0.1)[0]: ready = sys.stdin.readline().strip() if ready.lower() in ['1', 'one']: kidsHP -= 1 print(f"Evil kid's HP: {kidsHP}") if kidsHP <= 0: print("You've defeated the evil kids!") if health <= 0: print("You've been defeated by the evil kids!")
内容的提问来源于stack exchange,提问作者Bulrunord
相关产品推荐
相关产品推荐

