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

如何在方法中设置布尔值实现中毒概率及复用至闪避等功能?

Python简单继承下的中毒状态逻辑优化问题

目前正在学习Python的简单继承(使用super()),尚未接触复杂继承。希望在Hero类中创建方法,仅当满足条件或传入布尔值时让英雄进入中毒状态,后续还想将该逻辑复用至闪避等功能。但当前代码逻辑存在问题,多次修改后仍出现循环未触发、变量未定义等错误,附上现有代码:

import time

class Monster:
    name= 'Monster'

    def __init__(self,health, energy):
        self.health = health
        self.energy = energy

    def attack(self, amount):
            print('Monster has attacked')
            print(f'{amount} damage was delt!')
            self.energy -= 20
        
    def move(self,speed):
            print(f'{self.name} has moved, at {speed} speed')

class Scorpion(Monster):
    
    name='Scorpion'
    def __init__(self,  health, energy):
        super().__init__(health, energy)
    
    def attack(self, amount):
        print('Scorpion has attacked')
        print('Poison has take effect!')
    
        # Loops Poison display repeated with time delay.
        # for repeater amount of times.
        repeater = 5
        for poison in range(repeater):
            poison = 0
            amount = poison + amount
            print(f'Poisoned: {amount} damage')
            time.sleep(0.5)
    
        poison = repeater
        amount *= poison
        print(f'Poison did a total damage of {amount} to {hero.name}')
        hero.health -= amount
        

class Hero(Monster):
    name = 'Rockwood'

    def __init__(self, health, energy) -> None:
        self.health = health
        self.energy = energy
    
    # How do I use this in a boolean to check Scorpion attack?
    # Lets say later adding *import random* later to determine chances of poison.
    # def PoisonedCheck(self, posioned):
    #     self.poisoned = posioned

    #     if posioned == True:
    #         print("Testing if become posioned- For loop goes after here to create damage.")
    #         posioned = True
    
    #     else:
    #         print('Became else.. ')
    #         posioned = False
        


monster = Monster(health=100, energy=100)
scorpion = Scorpion(health = 200, energy = 150)
hero = Hero(health=100, energy=100)

scorpion.attack(3)
print()

scorpion.move(110)
hero.move(50)
print(f"{hero.name} has {hero.health} health remaining. ")
print()

原代码核心问题

  • 硬编码全局变量:Scorpion的attack方法直接引用全局的hero变量,耦合性极强,无法攻击其他目标
  • 循环逻辑错误:中毒循环内每次将poison设为0,amount = poison + amount等于未修改数值,循环输出的伤害始终是初始值
  • 继承规范缺失:Hero类的__init__未调用父类的super().__init__,不符合继承的基本规范
  • 状态管理混乱:Hero类中注释的中毒检测方法未实际使用,且变量名存在拼写错误(posioned应为poisoned),未将中毒状态与伤害逻辑绑定

优化后的代码实现

import time
# 可后续添加import random实现概率触发

class Monster:
    name = 'Monster'

    def __init__(self, health, energy):
        self.health = health
        self.energy = energy

    def attack(self, target, base_damage):
        print(f'{self.name} has attacked')
        print(f'{base_damage} damage was dealt!')
        target.health -= base_damage
        self.energy -= 20
        
    def move(self, speed):
        print(f'{self.name} has moved, at {speed} speed')

class Scorpion(Monster):
    name = 'Scorpion'
    
    def __init__(self, health, energy):
        super().__init__(health, energy)
    
    def attack(self, target, base_damage):
        print(f'{self.name} has attacked')
        # 模拟中毒触发条件,后续可替换为random.random() < 0.5这类概率逻辑
        poison_triggered = True
        
        if poison_triggered:
            target.set_poisoned(True)
            target.take_poison_damage(base_damage, 5)
        else:
            # 未触发中毒时执行普通攻击
            super().attack(target, base_damage)
        self.energy -= 20

class Hero(Monster):
    name = 'Rockwood'

    def __init__(self, health, energy) -> None:
        super().__init__(health, energy)
        self.is_poisoned = False  # 初始化中毒状态
    
    def set_poisoned(self, is_poisoned):
        self.is_poisoned = is_poisoned
        if is_poisoned:
            print(f"{self.name} 中毒了!持续伤害即将生效...")
        else:
            print(f"{self.name} 解除了中毒状态!")
    
    def take_poison_damage(self, damage_per_tick, ticks):
        total_damage = 0
        if self.is_poisoned:
            for _ in range(ticks):
                self.health -= damage_per_tick
                total_damage += damage_per_tick
                print(f"中毒伤害:{damage_per_tick},{self.name} 剩余生命值:{self.health}")
                time.sleep(0.5)
            print(f"中毒总计造成 {total_damage} 点伤害!")
            # 中毒结束后可自动解除状态,根据需求调整
            self.set_poisoned(False)
        else:
            print(f"{self.name} 没有中毒,不会受到持续伤害!")

# 实例化与调用
monster = Monster(health=100, energy=100)
scorpion = Scorpion(health=200, energy=150)
hero = Hero(health=100, energy=100)

scorpion.attack(hero, 3)
print()

scorpion.move(110)
hero.move(50)
print(f"{hero.name} has {hero.health} health remaining. ")
print()

关键优化点说明

  1. 解耦目标对象:Scorpion的attack方法接收target参数,不再依赖全局变量,可攻击任意Monster子类对象
  2. 规范继承逻辑:Hero类的__init__调用super().__init__,统一初始化父类属性
  3. 状态与逻辑分离:Hero类中单独管理is_poisoned状态,set_poisoned负责状态切换,take_poison_damage处理中毒伤害,方便后续复用逻辑到闪避等功能
  4. 修正循环计算:中毒伤害按每tick固定值累加,逻辑清晰且符合预期
  5. 预留扩展接口:中毒触发条件预留了替换为随机概率的位置,后续只需修改poison_triggered的赋值逻辑即可实现概率触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:45:29