You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在if和elif语句执行后添加可正常运行的while语句?

回合制PVP游戏代码问题:敌人HP归0后未触发胜利逻辑

我正在制作一款回合制PVP游戏,目前处于入门教程阶段。已编写if和elif语句,设置groof的hp为10,用户输入"attack"时敌人会损失HP,这部分功能正常。但添加while groofhp == 0:语句后,当groof的HP降至0时,代码直接终止,未执行while内逻辑。

问题代码:

print("A wild groof has spawned. Pick a card to attack. Element and ATTACK.")
groofpvpturn1 = input("What card shall you pick to start the fight?")

if groofpvpturn1 in ("ATTACK", "Attack", "attack"):
    print( + charactername + "has hit the groof! The groof lost 5hp!")
    time.sleep(2)
    print("Pick another card.")
    if groofpvpturn1 in ("ATTACK", "Attack", "attack"):
       groof1hp - 5
    elif groofpvpturn1 in ("ELEMENT", "element", "Element"):
        groofhp - 5
    
elif groofpvpturn1 in ("Element", "element", "ELEMENT"):
      print(""+ charactername + " has used ELEMENT on the groof! The groof lost 10 hp!")
      groof1hp - 10
      while groof1hp == 0:
            print("You have defeated the groof. GG!")

问题根源及修正步骤

  1. 变量名混乱:代码里混用groof1hp和groofhp,必须统一为同一个变量(比如groof_hp)。
  2. HP修改未生效:groof1hp - 5只是做减法运算,没有把结果存回变量,要改成groof_hp -= 5才能真正减少敌人HP。
  3. while循环用法错误:while groof_hp == 0会在HP为0时无限循环打印,且仅在element分支里触发,逻辑位置完全不对。应该用if判断HP是否归0,或者用while循环控制整个战斗回合流程。
  4. 嵌套逻辑冗余:第一个if分支里的嵌套if完全多余,已经判断过输入是attack,没必要重复判断。
  5. 语法错误:print( + charactername + "...")开头多了加号,要去掉;同时缺少groof_hp和charactername的初始化代码。

修正后的完整代码

import time

# 初始化必要变量
charactername = "Player"  # 可替换成自定义角色名
groof_hp = 10

print("A wild groof has spawned. Pick a card to attack. Element and ATTACK.")

# 用while循环控制战斗回合,直到敌人HP<=0
while groof_hp > 0:
    action = input("What card shall you pick to start the fight? ").strip().lower()
    
    if action == "attack":
        groof_hp -= 5
        print(f"{charactername} has hit the groof! The groof lost 5hp!")
        print(f"Groof's remaining HP: {groof_hp}")
    elif action == "element":
        groof_hp -= 10
        print(f"{charactername} has used ELEMENT on the groof! The groof lost 10 hp!")
        print(f"Groof's remaining HP: {groof_hp}")
    else:
        print("Invalid action! Please enter 'attack' or 'element'.")
        continue  # 无效输入跳过本次回合
    
    time.sleep(2)
    if groof_hp <= 0:
        print("You have defeated the groof. GG!")
        break
    print("Pick another card.")

关键改进说明

  • 用while groof_hp > 0循环整个战斗流程,直到敌人被击败
  • 将输入转为小写,不用判断多种大小写形式,简化代码
  • 用f-string格式化输出,更简洁易读
  • 增加无效输入处理,避免程序逻辑混乱
  • 每次攻击后显示剩余HP,让玩家清晰掌握战斗状态

内容的提问来源于stack exchange,提问作者Skesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:32:45