鱼C论坛

 找回密码
 立即注册
查看: 1463|回复: 3

[已解决]遇到这样一个题目 半天没有头绪 来这碰碰运气

[复制链接]
发表于 2023-9-17 19:31:49 | 显示全部楼层    本楼为最佳答案   
下面是一个示例代码,展示了如何利用构造器、多态、继承和封装来创建一个角色游戏:

  1. import random

  2. class Character:
  3.     def __init__(self, name, hp=50):
  4.         self.name = name
  5.         self.hp = hp

  6.     def attack(self, target):
  7.         raise NotImplementedError("Subclass must implement attack method")

  8.     def is_alive(self):
  9.         return self.hp > 0

  10.     def __str__(self):
  11.         return self.name


  12. class Human(Character):
  13.     def __init__(self):
  14.         super().__init__("Human", hp=50)

  15.     def attack(self, target):
  16.         if isinstance(target, Ghost):
  17.             target.hp -= 10
  18.         elif isinstance(target, Monster):
  19.             target.hp -= 5


  20. class Monster(Character):
  21.     def __init__(self):
  22.         super().__init__("Monster", hp=100)

  23.     def attack(self, target):
  24.         if isinstance(target, Human):
  25.             target.hp -= 10
  26.         elif isinstance(target, Ghost):
  27.             target.hp -= 5


  28. class Ghost(Character):
  29.     def __init__(self):
  30.         super().__init__("Ghost", hp=40)

  31.     def attack(self, target):
  32.         if isinstance(target, Human):
  33.             target.hp -= 5
  34.         elif isinstance(target, Monster):
  35.             target.hp -= 10


  36. def main():
  37.     characters = [Human(), Monster(), Ghost()]

  38.     while len(characters) > 1:
  39.         attacker = random.choice(characters)
  40.         target = random.choice(characters)
  41.         
  42.         if attacker != target and attacker.is_alive() and target.is_alive():
  43.             print(f"{attacker} attacks {target}!")
  44.             attacker.attack(target)
  45.             
  46.             if not target.is_alive():
  47.                 characters.remove(target)
  48.                 print(f"{target} is dead.")
  49.                
  50.             print("Current status:")
  51.             for character in characters:
  52.                 print(f"{character}: {character.hp} HP")
  53.             print()

  54.     if characters:
  55.         print(f"{characters[0]} survives.")
  56.     else:
  57.         print("No one survives.")

  58. if __name__ == "__main__":
  59.     main()
复制代码


这个示例代码定义了三个角色类:Human、Monster和Ghost,它们都继承自Character基类。每个角色类都实现了attack方法来执行相应的攻击行为。在主函数中,创建了三个角色对象,并通过随机选择攻击对象来模拟随机自动攻击的游戏场景。当一个角色的HP降至0以下时,会被从角色列表中移除,直到只剩下一个角色或者没有角色存活时游戏结束。

希望这个示例能对您有所帮助!
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-26 13:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表