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

Python格斗游戏中执行计算时playerHealth为何变为NoneType?

问题分析与解决

核心错误原因

报错的直接原因是Enemy.opponentMoves()方法在敌人选择Block动作时,没有返回任何值(Python中无return语句的函数默认返回None)。而在main()函数中,你将该方法的返回值直接赋值给了playerHealth:

playerHealth = run.opponentMoves(playerHealth)

当敌人第一次选择Block后,playerHealth被赋值为None,下次敌人选择Attack时,执行playerHealth -= self.attack就会触发NoneType与int的运算错误。

修复方案

修改Enemy.opponentMoves()方法,确保无论敌人选择哪种动作,都返回更新后的playerHealth(Block动作不需要修改生命值,直接返回原数值即可):

def opponentMoves(self,playerHealth):
    import random as rd
    oppMoves = ["Attack","Block"]
    oppMove = oppMoves[rd.randint(0,1)]
    if oppMove == "Attack":
        print("The enemy attacks you.")
        playerHealth -= self.attack
        print("\nDamage Received: " + str(self.attack) + "\nHealth remaining: " + str(playerHealth))
        return playerHealth
    else:
        print("The enemy blocks your attack.")
        return playerHealth  # 关键:返回原生命值,避免返回None

额外逻辑问题修复

除核心错误外,代码还有两处明显逻辑漏洞:

  • 闪避功能完全失效:在Player.moveExecution()的闪避分支中,你定义chance = [1,2]后随机取元素,结果chance只能是1或2,永远不会等于0,导致成功闪避的逻辑永远不会触发。修改为:
elif move == 3:
    print("You try to dodge out the way of the enemy.")
    chance = rd.randint(0,1)  # 直接生成0(成功)或1(失败)的随机数
    if chance == 0:
        print("You have successfully dodged out the way of the enemy.\nDamage taken: 0\nHealth remaining: " + str(self.health))
        return chance, flee, health
    else:
        print("Dodge unsuccessful.")
        return chance, flee, health
  • 重复创建Enemy对象:在Player.moveExecution()里每次都会新建Enemy(health),这会导致敌人属性被重置,应该直接使用main()中已创建的run对象。修改方式为:
# 修改Player.moveExecution的定义,增加enemy参数
def moveExecution(self,move,oppNum,health, enemy):
    import random as rd
    flee = 0
    chance = 1
    if move == 1:
        print(r"You attempt to block the attack and take 50% less damage.")
        self.health -= enemy.attack/2
        print("\nDamage taken: " + str(enemy.attack/2) + "\nHealth remaining: " + str(self.health))
        return chance, flee, health
    # 其他分支保持不变...

# 在main()中调用时传入已有的run对象
chance, flee, health = running.moveExecution(move,oppNum,health, run)

经过上述修改,程序的核心错误和逻辑漏洞即可修复,生命值不会再变为NoneType,闪避功能也能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:34:59