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

Python中如何在main()循环中依据导入函数内的条件终止循环?

解决控制台RPG战斗结束后终止主循环的问题

核心问题分析

  1. 原main()中的while循环条件错误:character["Health Points"] >= 0 or enemy["Health Points"] >= 0会导致只要一方存活就一直循环,不符合战斗逻辑(应该是双方都存活时才继续战斗)。
  2. combat_system()中的temp是局部变量,修改后无法传递到main()中,无法触发循环终止。
  3. 输入选择不匹配:main()中让用户输入1/2/3,但combat_system()判断的是字符串"attack",导致攻击逻辑永远不会执行。

解决方案步骤

1. 修正combat_system()函数,返回战斗结束状态

修改combatsys.py,去掉无用的temp参数,改为返回布尔值表示战斗是否结束:

import random

def combat_system(character, choice, enemy):
    combat_ended = False

    # 处理攻击逻辑
    if choice == "attack":
        print("You chose to attack the enemy.")
    
        # 计算玩家攻击伤害,避免负数
        attack_damage = (random.randint(0, character["stats"]["Strength"])) - (random.randint(0, enemy["stats"]["Defense"] // 2))
        attack_damage = max(0, attack_damage)
        print("The damage you inflicted is: ", attack_damage )

        # 更新敌人HP
        enemy["Health Points"] -= attack_damage

        # 敌人死亡判断
        if enemy["Health Points"] <= 0:
            print("The enemy's current HP is: ", 0)
            print("You were able to kill the enemy. Good work.")
            enemy["Health Points"] = enemy["Max HP"]
            # 增加经验值
            character["experience"] += random.randint(0, character["next level"] // 2)
            print(f"Congratulations. You gained {character['experience']} experience.")
            print()
            combat_ended = True
        else:
            print("The enemy's current HP is: ", enemy["Health Points"])
        print()
        
        # 敌人反击(如果战斗还没结束)
        if not combat_ended:
            attack_damage = (random.randint(0, enemy["stats"]["Strength"])) - (random.randint(0, character["stats"]["Defense"] // 2))
            attack_damage = max(0, attack_damage)
            print("\nYou got attacked by a", enemy["name"])
            print(f"The damage inflicted by {enemy['name']} is: {attack_damage}")

            character["Health Points"] -= attack_damage

            # 玩家死亡判断
            if character["Health Points"] <= 0:
                print("Your current HP is: ", 0)
                print("You have been killed by the enemy. Game Over")
                character["Health Points"] = character["Max HP"]
                print()
                combat_ended = True
            else:    
                print("Your new HP is: ", character["Health Points"])
    
    # 防御逻辑(待实现)
    elif choice == "defend":
        print("You chose to defend.")
    # 逃跑逻辑(待实现)
    elif choice == "run":
        print("You tried to run away!")
    else:
        print("Invalid choice, please try again.")
    
    return combat_ended

2. 修正main()函数的循环条件和输入处理

修改main.py,调整循环条件,处理用户输入的数字转换为动作,并根据combat_system()的返回值终止循环:

from levelsys import level_system
from combatsys import combat_system

character = {
    "name": "",
    "level": 1,
    "experience": 0,
    "next level": 10,
    "Health Points": 10,
    "Max HP": 10,
    "Gold": 0,
    "stats": {
        "Strength": 1,
        "Defense": 1,
        "Intelligence": 1
    }
}

enemy = {
    "name": "Zombie",
    "level": 1,
    "experience": 0,
    "next level": 10,
    "Health Points": 10,
    "Max HP": 10,
    "stats": {
        "Strength": 1,
        "Defense": 1,
        "Intelligence": 1
    }
}


def main():
    print("You are being attacked by a", enemy["name"],".")
    print("How will you respond to that?")
    print("1-) Attack.")
    print("2-) Defend.")
    print("3-) Run.")
    
    # 循环条件:双方都存活时继续战斗
    while character["Health Points"] > 0 and enemy["Health Points"] > 0:
        choice_input = input("--> ").strip()
        # 将数字输入转换为对应的动作字符串
        if choice_input == "1":
            choice = "attack"
        elif choice_input == "2":
            choice = "defend"
        elif choice_input == "3":
            choice = "run"
        else:
            print("Invalid input, please enter 1, 2, or 3.")
            continue
        
        # 调用战斗系统,获取战斗是否结束的状态
        battle_over = combat_system(character, choice, enemy)
        
        # 如果战斗结束,终止循环
        if battle_over:
            break
        
        # 战斗未结束,提示下一轮选择
        print("\nWhat will you do next?")
        print("1-) Attack.")
        print("2-) Defend.")
        print("3-) Run.")

    # 战斗结束后执行等级系统
    level_system(character)

if __name__ == '__main__':
    print("#################################################")
    print("#                                               #")
    print("#                                               #")
    print("#                    MY GAME                    #")
    print("#           Journey to learning Python          #")
    print("#                                               #")
    print("#                                               #")
    print("#                               By : Godspeed   #")
    print("#                                               #")
    print("#                                               #")
    print("#            <Press ENTER to continue>          #")
    print("#                                               #")
    print("#################################################")

    input()

    print("Welcome stranger. What's your name?")
    character["name"] = input("--> ")
    
    # print("Input the experience to add  in order to test:")
    # character["experience"] = int(input("--> "))
    main()

关键修改说明

  • 战斗状态返回:combat_system()通过返回布尔值,直接告知main()战斗是否结束,无需依赖全局变量或局部变量传递,逻辑更清晰。
  • 循环条件修正:改为while character["Health Points"] > 0 and enemy["Health Points"] > 0,只有双方都存活时才继续战斗。
  • 输入匹配修复:将用户输入的1/2/3转换为对应的动作字符串,确保战斗逻辑能正确触发。
  • 伤害值优化:添加max(0, attack_damage),避免出现负数伤害(比如防御高于攻击时,不会出现加血的不合理情况)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:39:17