Python角色扮演混乱

2024-04-26 23:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有一个问题,当调用它时,它似乎使战斗持续的时间比它应该的要长

我认为问题出在if语句上,所以我一直在玩弄它们,但我似乎没有把它弄对

class Enemy:
    def __init__(self, Name, HP, ATK, DEF, Damage):
        self.Name = Name
        self.HP = HP
        self.ATK = ATK
        self.DEF = DEF
        self.Damage = Damage

def attack(attacker, attackee):  # The attack function
    hit = random.randint(min_roll, max_roll) + attacker.ATK

    if (hit > attackee.DEF):
        print(attacker.Name, "inflicts", attacker.Damage)

        attackee.HP = attackee.HP - attacker.Damage

        if attackee.HP <= 0:  # if the attackee's health drops below zero
            print("With a forceful attack,", attackee.Name, "dies.")
        else:
            print(attackee.Name, "has", attackee.HP, "HP remaining.")
    else:
        print("You missed. Better defend!")


def fight(attacker, enemy):  # The attack loop takes in two enemy objects
    while(attacker.HP >= 0 and enemy.HP >=0):
        if attacker.HP >= 0 and enemy.HP >= 0:
            attack(attacker, enemy)
        else:
            print("You're dead")

        if enemy.HP >= 0 and attacker.HP >= 0:
            attack(enemy, attacker)
        else:
            print("The enemy is dead")

theClass= Enemy("warrior", 10, 4, 5, 5)
skeleton1 = Enemy("The Skeleton", 10, 4, 5, 5)  # This creates a new Skeleton enemy. The order is the Name, HP, ATK, DEF, and Damage.

fight(theClass, skeleton1)

当其中一个角色死亡时,输出应该完全停止,并且每个角色每卷只能攻击一次。由于某种原因,当我这次运行代码时,最后一次攻击让战士在骷髅死亡之前运行了三次

我也看到有时它也很好用。不一致的结果是不好的。谢谢你


Tags: andthenameselfifdefelsehp
2条回答

你想让他们在0血量时继续攻击吗?当您将检查更改为if enemy.HP > 0 and attacker.HP > 0时,输出是什么

此外,在子句中放入return语句可能会有帮助,因为您发现其中一个已经死了;这样,你就可以确定一旦他们中的一个死了,战斗就结束了

attack函数中,您可以说:

if attackee.HP <= 0: # if the attackee's health drops below zero

从注释和fight中的if语句来看,似乎当生命值正好为0时,你并不认为它们已经死亡,它们仍然可以战斗。
但是if语句也将在health等于0时打印死亡消息。只需编辑它以保持一致:

if attackee.HP < 0:

它会起作用的

相反,如果希望它们在运行状况正好为0时死亡,请在attack函数中保持相等,但将其从fight函数中的所有if语句中删除

相关问题 更多 >