大模型学习-python基础-面向对象项目:愤怒的小鸟
·
一.类的设计思路
1.Birds基类
2.具体小鸟类
3.Obstacle类
代表游戏中的障碍物,比如木头堡垒等,负责处理障碍物被小鸟攻击的逻辑。
属性设计:
name:障碍物名字,方便区分不同类型的障碍物
strength:障碍物强度,即能够承受的伤害值。强度为0时,障碍物被摧毁
方法设计:
be_attacked(bird):模拟障碍物被小鸟攻击的过程。根据小鸟的类型计算伤害,并且更新障碍物强度,同时输出攻击和受损信息。
二.代码实现
1.定义鸟的基类
#定义鸟的基类
class Birds:
def __init__(self,name,color,skill_description):
self.name = name
self.color = color
self.skill_description = skill_description
def fly(self):
print(f"{self.name} is flying...")
def call(self):
print(f"{self.name} is calling...")
def use_skill(self):
print(f"{self.skill_description} is using skill...")
2.定义鸟的子类
class RedBirds(Birds):
def __init__(self):
super().__init__("red fire","red","damage obstacles")
def fly(self):
print("red fire is flying steadily")
def call(self):
print("wowowo")
class YellowBirds(Birds):
def __init__(self):
super().__init__("Yellow fire","Yellow","damage obstacles in a high speed")
def fly(self):
print("Yellow fire is flying steadily")
def call(self):
print("wwwww")
3.定义障碍物类
class Obstacle:
def __init__(self,name,strength)
self.name = name
self.strength = strength
def be_attacked(self,bird): #这里的bird体现的就是多态
printf(f"{bird.name} rush to {self.name}")
bird.use_skill()
if isinstance(bird,RedBirds)
damage = 80
else
damage = 60
self.strength -= damage
if self.strength <= 0
printf(f"{self.name} has destroied")
else
printf(f"{self.name} still alive")
isinstance 函数的基本用法
isinstance() 是 Python 内置函数,用于检查对象是否属于指定类型或类型元组中的某一类型。其语法如下
isinstance(object, classinfo)
object:待检查的对象。classinfo:类型(如int、str)或类型元组(如(int, float))。
返回值为 True 或 False
4.模拟过程:
#创建一个障碍物对象
o1 = Obstacle("stone house",strengh = 100)
#创建鸟对象
r1 = RedBirds()
o1.be_attacked(r1)
y1 = YellowBirds()
01.be_attacked(y1)
更多推荐

所有评论(0)