You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python文本游戏玩家生命值跟踪功能故障排查与实现

解决Python游戏中玩家生命值跟踪与战斗循环的问题

我来帮你搞定这个生命值跟踪的问题!你的代码里有几个关键逻辑错误,导致要么直接判定胜利要么循环出问题,咱们一个个来修正:

主要问题分析

  1. reduce_health函数逻辑错误
    • 你试图把字符串"enemy_damage"转成整数,这完全是无效操作,而且函数没有接收实际的敌人伤害值作为参数,根本无法正确扣减生命值。
  2. combat函数胜负判断逻辑错误
    • 原来的player_win = player_damage >= enemy["health"]是判断单次攻击是否直接秒杀敌人,这不符合正常战斗逻辑,应该是每次攻击后扣除敌人生命值,再判断敌人是否死亡。同理,敌人胜利的判断也没有扣减玩家生命值,直接用单次伤害和玩家总血量比较,逻辑错误。
  3. describe_combat函数执行顺序错误
    • 你在打印完伤害后就直接return reduce_health,导致后面的胜负判断代码完全不会执行,而且没有实际调用reduce_health函数来更新玩家生命值。
  4. 战斗循环逻辑错误
    • 循环中没有更新fight_result变量,而且if True的分支会无条件执行,导致直接打印胜利,完全忽略实际战斗结果。

修复后的完整代码

import random
import time

# Tracking weapon and player health
player = {"weapon": None, "health": None}

# Function for questions to avoid repeat
def ask(question):
    answer = input(question + " [y/n]")
    return answer in ["y", "Y", "Yes", "YES", "yes"]

def game_over():
    print("You Lose")
    exit()  # 退出游戏,避免继续执行

# Initial question to start
print("The adventures Of Magical Nadia")

# Question to start game or end game
if ask("Do you wish to embark on this great adventure?"):
    print("You have accepted the adventure. God Speed my young rass!")
    player["health"] = 100
    # 给玩家初始武器,避免None的伤害范围,也可以让玩家选择,这里先默认给Spear
    player["weapon"] = "Spear"
else:
    print("You are a coward and shall not embark on a great adventure!")
    exit()

# Dict of all the weapons in the game
WEAPONS = {
    "Spear": (3, 10),
    None: (1, 3),
    "knife": (4, 16),
    "Gun": (16, 25),
    "Glass Bottle": (4, 16)
}

# Enemies type
Gaint_spider = {"name": "Spider", "health": 10, "attack": (7, 10)}
Dogs = {"name": "Dogs", "health": 50, "attack": (4, 15)}
Dragon = {"name": "Dragon", "health": 150, "attack": (35, 45)}

def reduce_health(enemy_damage):
    """扣减玩家生命值,并检查是否死亡"""
    player["health"] -= enemy_damage
    print(f"Player health {player['health']}")
    if player["health"] <= 0:
        game_over()

# Function each fight gives random dmg, update health, check winner
def combat(player, enemy):
    player_damage = random.randint(*WEAPONS[player["weapon"]])
    enemy_damage = random.randint(*enemy["attack"])
    
    # 更新敌人生命值
    enemy["health"] -= player_damage
    
    player_win = enemy["health"] <= 0
    enemy_win = player["health"] - enemy_damage <= 0  # 先预判是否会死亡,再实际扣减
    
    return player_damage, player_win, enemy_damage, enemy_win

# Structure of a fight
Sample_FIGHT = {
    "player_damage": "You desperately try to stop the %s for %i damage",
    "enemy_damage": "%s gores you for %i damage",
    "player_win": "The %s collapses with a thunderous boom",
    "enemy_win": "You are squished"
}

# Describe the fight in a function
def describe_combat(player, enemy, fight_description):
    player_damage, player_win, enemy_damage, enemy_win = combat(player, enemy)
    
    print(fight_description["player_damage"] % (enemy["name"], player_damage))
    time.sleep(1.0)
    print(fight_description["enemy_damage"] % (enemy["name"], enemy_damage))
    
    # 扣减玩家生命值并检查
    reduce_health(enemy_damage)
    
    if player_win:
        print(fight_description["player_win"] % enemy["name"])
        return True
    if enemy_win:
        print(fight_description["enemy_win"])
        return False
    # 双方都没死,返回None继续战斗
    return None

# Start the fight
# 注意:要复制敌人字典,避免修改原有的敌人数据(下次战斗可以重新使用)
current_enemy = Gaint_spider.copy()
fight_result = describe_combat(player, current_enemy, Sample_FIGHT)

while fight_result is None:
    fight_result = describe_combat(player, current_enemy, Sample_FIGHT)

# 循环结束后判断最终结果
if fight_result:
    print("You have won the fight")
else:
    print("You lost")

关键修改说明

  1. reduce_health函数
    • 新增enemy_damage参数,接收实际的敌人伤害值,直接扣减玩家生命值并打印当前生命值,死亡时调用game_over并退出游戏。
  2. combat函数
    • 每次攻击后更新敌人的生命值,修改胜负判断逻辑为:敌人生命值<=0则玩家胜利,玩家扣除伤害后生命值<=0则敌人胜利。
  3. describe_combat函数
    • 移除了无效的return reduce_health,改为实际调用reduce_health(enemy_damage)来更新玩家生命值;修正了敌人胜利时的打印文本(原来错误用了player_win的描述);正确返回战斗结果。
  4. 战斗循环
    • 复制了敌人字典(current_enemy = Gaint_spider.copy()),避免修改原有的敌人数据;循环中更新fight_result,循环结束后根据结果打印最终胜负。
  5. 新增初始武器
    • 给玩家默认设置了初始武器Spear,避免使用None武器的低伤害,你也可以改成让玩家选择武器的逻辑。

运行效果示例

The adventures Of Magical Nadia
Do you wish to embark on this great adventure? [y/n] Y
You have accepted the adventure. God Speed my young rass!
You desperately try to stop the Spider for 5 damage
Spider gores you for 8 damage
Player health 92
You desperately try to stop the Spider for 7 damage
Spider gores you for 9 damage
Player health 83
The Spider collapses with a thunderous boom
You have won the fight

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

火山引擎 最新活动