人狗大战python代码

2023-02-14 00:00:00 python 代码 大战

下面是一份 Python 代码,可以模拟人狗大战的游戏:

import random

class Person:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def attack(self, opponent):
        damage = random.randint(10, 20)
        opponent.health -= damage
        print(f"{self.name} attacked {opponent.name} and dealt {damage} damage.")

class Dog:
    def __init__(self, name):
        self.name = name
        self.health = 80

    def attack(self, opponent):
        damage = random.randint(5, 15)
        opponent.health -= damage
        print(f"{self.name} attacked {opponent.name} and dealt {damage} damage.")

person = Person("John")
dog = Dog("Rufus")

while person.health > 0 and dog.health > 0:
    attacker = random.choice([person, dog])
    defender = person if attacker == dog else dog
    attacker.attack(defender)
    print(f"{person.name}'s health: {person.health}")
    print(f"{dog.name}'s health: {dog.health}")
    print()

if person.health > 0:
    print(f"{person.name} won the battle!")
else:
    print(f"{dog.name} won the battle!")

游戏通过创建一个 Person 和一个 Dog 的实例,然后不断地随机选择一个攻击者,攻击另一个对象,直到其中一方的血量降为零为止。输出最后胜利者的名称。

相关文章