简体   繁体   English

类和对象:如何从方法中设置 boolean 以创建具有毒状态的“机会”,或稍后用于闪避和其他可重复使用

[英]Classes and Objects: How do I set a boolean from a method to create "chance" with a poison status, or use later for dodge and other reusables

How do I set a boolean from a method to create "chance" with a poison status, or use later for dodge and other reusable.如何通过一种方法设置 boolean 以创建具有毒状态的“机会”,或稍后用于闪避和其他可重复使用。

Just now learning Simple Inheritance with Super() and not yet gotten to Complex Inheritance. Not sure if that would make a difference in how I could of coded this but using what I know, here is what I have.刚刚使用 Super() 学习简单的 Inheritance,还没有学习复杂的 Inheritance。不确定这是否会对我的编码方式产生影响,但使用我所知道的,这就是我所拥有的。

What I am trying to do is create a method inside the Hero Class, and make the hero only be poisoned if a condition is met or a boolean is passed.我想做的是在英雄 Class 中创建一个方法,让英雄只有在满足条件或通过 boolean 时才会中毒。 I keep getting an issue with the logic.我一直对逻辑有疑问。 Still new to programming.还是编程新手。

I've re-written the code multiple times using Idle for speed and it just keeps giving me problems, even when i place the for-loop inside the hero.PoisionedCheck(True) I only get the displayed text and not the forloop activated.我已经使用 Idle 多次重写代码以提高速度,但它一直给我带来问题,即使我将 for 循环放在 hero.PoisionedCheck(True) 中,我也只得到显示的文本,而没有激活 forloop。 Then I will get an error that "amount" parameter is not defined or called before assignment, then when I fix that I will get that scorpion.health and scorpion.energy is not defined.然后我会得到一个错误,“amount”参数在赋值之前没有定义或调用,然后当我修复它时,我会得到 scorpion.health 和 scorpion.energy 没有定义。 I'm running in circles.我在原地转圈。

Thank you for reading.感谢您阅读。

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()

To be honest, I am not really sure what you are trying to achieve, hopefully this answers your question or gets you going.老实说,我不太确定您要实现什么目标,希望这能回答您的问题或帮助您前进。

Firstly I would suggest adding a target parameter to Scorpion's attack behaviour and modifying it's behaviour.首先,我建议为 Scorpion 的攻击行为添加一个目标参数并修改它的行为。 That way you can define multiple heroes and have them combat the scorpion, for example:这样你就可以定义多个英雄并让他们与蝎子作战,例如:

scorpion = Scorpion(health = 200, energy = 150)
hero_one = Hero(health=100, energy=100)
hero_two = Hero(health=200, energy=100)

scorpion.attack(hero_one)
scorpion.attack(hero_two)

Secondly, Scorpion doesn't seem to lose energy after attacking and doesn't deal initial damage.其次,蝎子攻击后似乎不会失去能量,也不会造成初始伤害。 You could fix that by changing Scorpion attack behaviour to first call parent attack function:您可以通过将 Scorpion 攻击行为更改为先调用父攻击 function 来解决此问题:

class Scorpion(Monster):
...
    def attack(self, amount, target):
        super().attack(amount, target)
        print('Poison has take effect!')
        ...

But Monster attack behaviour doesn't accept second argument, so my suggestion is to modify Monster's attack function with second parameter to also deal initial damage to target (and correctly subtract target's health with damage amount):但是怪物的攻击行为不接受第二个参数,所以我的建议是用第二个参数修改怪物的攻击 function 也对目标造成初始伤害(并正确地减去目标的生命值和伤害量):

class Monster:
...
    def attack(self, amount, target):
        print(f'{self.name} has attacked')
        print(f'{amount} damage was delt!')
        target.health -= amount
        self.energy -= 20

To track poisoned status, easiest you can do is to introduce state in Monster class constructor called poisoned and set it to False (initial state is that monster and every child object is not poisoned).要跟踪中毒状态,最简单的方法是在名为poisoned的 Monster class 构造函数中引入 state 并将其设置为False (初始 state 是怪物和每个子 object 未中毒)。

Then you can change target's poisoned state in Scorpion's attack method, like so:然后你可以在Scorpion的攻击方法中改变目标中毒的state,像这样:

class Scorpion(Monster):
...
    def attack(self, amount, target):
        ...
        target.poisoned = True
        ...

This way you can see if one of Heroes is poisoned, like so:通过这种方式,您可以查看其中一位英雄是否中毒,如下所示:

  print(hero_one.poisoned) --> False or True (if attacked by scorpion)

To calculate a chance (lets say 50%) if Scorpion's attack will poison the target or not, extract poison application behaviour into separate private function and modify it like this:要计算 Scorpion 的攻击是否会使目标中毒的机会(比如说 50%),将毒应用行为提取到单独的私有 function 中并像这样修改它:

class Scorpion(Monster):
...
def attack(self, amount, target):
    super().attack(amount, target)
    self.__poison_target(amount, target)


def __poison_target(self, amount, target):
    # A coin toss to decide if target will be poisoned or not.
    should_apply_poison = random.randint(0, 1) == 1
    if should_apply_poison:
        print('Poison has take effect!')
        target.poisoned = True
        # 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 {target.name}')
        target.health -= amount
 ...

Or you can delegate damage dealing behaviour from Scorpion to Hero by creating abstract class Poisonable which you can use to check if the target is Poisonable (in your case - Hero inherits from Poisonable ).或者您可以通过创建抽象 class Poisonable将伤害处理行为从 Scorpion 委托给 Hero,您可以使用它来检查目标是否有毒(在您的情况下 - Hero 继承自Poisonable )。 This way Scorpion class doesn't care if target is successfuly poisoned or not.这样 Scorpion class 不关心目标是否成功中毒。

Poisonable class is contract which all classes that inherit from it must abide by (eg implement their own version of resistance, damage taking from poison). Poisonable class 是所有从它继承的类都必须遵守的契约(例如,实现他们自己的抵抗版本,从毒药中获得伤害)。 This way every poisoned creature can react differently.这样每个中毒的生物都会有不同的反应。

class Poison:
    def __init__(self):
        self.damage_per_tick = 5
        self.ticks = 3

class Scorpion(Monster):
    name = 'Scorpion'

    def __init__(self, health, energy):
        super().__init__(health, energy)
        self.poison = Poison()

    def attack(self, amount, target):
        super().attack(amount, target)
        self.__poison_target(target)


    def __poison_target(self, target):
        if isinstance(target, Poisonable):
            target.suffer_poison_damage(self.poison)


class Poisonable(ABC):
    @abc.abstractmethod
    def resist_poison(self) -> bool:
        pass

    @abc.abstractmethod
    def suffer_poison_damage(self, poison: Poison) -> None:
        pass

class Hero(Monster, Poisonable, ABC):
    name = 'Rockwood'

    def __init__(self, health, energy) -> None:
        super().__init__(health, energy)

    def resist_poison(self) -> bool:
        # resist poison chance
        return random.randint(0, 1) == 1

    def suffer_poison_damage(self, poison: Poison) -> None:
        if self.resist_poison():
            pass
        else:
            print('Poison has take effect!')
            # Loops Poison display repeated with time delay.
            # for repeater amount of times.
            total_amount = 0
            for poison_tick in range(poison.ticks):
                total_amount += poison.damage_per_tick
                print(f'Poisoned: {poison.damage_per_tick} damage')
                time.sleep(0.5)

            print(f'Poison did a total damage of {total_amount} to {self.name}')
            self.health -= total_amount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个继承其他两个类的方法的类,并将其自己和方法共享给它们 - How do I create a class that inherits methods from two other classes and shares own and their methods back to them 如何从列表创建对象? - How do I create objects from lists? 如何在以后的编程中创建可用于访问类实例的内容? - How do I create something that I can use to access class instances later in my programming? 如何存储/缓存类中的方法的值以供以后在同一类的其他方法中使用? - How can I store / cache values from methods in a class for later use in other methods of the same class? 如何使用While / For循环创建类? (Python / PyQt) - How do i use a While/For loop to create classes?? (Python/PyQt) Python 3 - 如何使用循环一次创建多个类? - Python 3 - How do I use a loop to create multiple classes at once? 当我稍后设置变量值时,如何避免来自 Pylint 的“不可下标”类型检查? - how do I avoid "not subscriptable" type checks from Pylint when I later set a variable value? 如何从 django bulk_create 获取创建的对象作为查询集? - How do I get created objects as a query set from django bulk_create? 如何使用 get_or_create 方法创建的对象? - How to use the created objects from get_or_create method? 如何在Pygame中设置两个对象以使用碰撞检测? - How do i set two objects to use collision detection in Pygame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM