|
发表于 2023-9-17 19:31:49
|
显示全部楼层
本楼为最佳答案
 下面是一个示例代码,展示了如何利用构造器、多态、继承和封装来创建一个角色游戏:
- import random
- class Character:
- def __init__(self, name, hp=50):
- self.name = name
- self.hp = hp
- def attack(self, target):
- raise NotImplementedError("Subclass must implement attack method")
- def is_alive(self):
- return self.hp > 0
- def __str__(self):
- return self.name
- class Human(Character):
- def __init__(self):
- super().__init__("Human", hp=50)
- def attack(self, target):
- if isinstance(target, Ghost):
- target.hp -= 10
- elif isinstance(target, Monster):
- target.hp -= 5
- class Monster(Character):
- def __init__(self):
- super().__init__("Monster", hp=100)
- def attack(self, target):
- if isinstance(target, Human):
- target.hp -= 10
- elif isinstance(target, Ghost):
- target.hp -= 5
- class Ghost(Character):
- def __init__(self):
- super().__init__("Ghost", hp=40)
- def attack(self, target):
- if isinstance(target, Human):
- target.hp -= 5
- elif isinstance(target, Monster):
- target.hp -= 10
- def main():
- characters = [Human(), Monster(), Ghost()]
- while len(characters) > 1:
- attacker = random.choice(characters)
- target = random.choice(characters)
-
- if attacker != target and attacker.is_alive() and target.is_alive():
- print(f"{attacker} attacks {target}!")
- attacker.attack(target)
-
- if not target.is_alive():
- characters.remove(target)
- print(f"{target} is dead.")
-
- print("Current status:")
- for character in characters:
- print(f"{character}: {character.hp} HP")
- print()
- if characters:
- print(f"{characters[0]} survives.")
- else:
- print("No one survives.")
- if __name__ == "__main__":
- main()
复制代码
这个示例代码定义了三个角色类:Human、Monster和Ghost,它们都继承自Character基类。每个角色类都实现了attack方法来执行相应的攻击行为。在主函数中,创建了三个角色对象,并通过随机选择攻击对象来模拟随机自动攻击的游戏场景。当一个角色的HP降至0以下时,会被从角色列表中移除,直到只剩下一个角色或者没有角色存活时游戏结束。
希望这个示例能对您有所帮助!
如果问题已经解决,请设置最佳答案 |
|