100.自定义枪类 自定义枪类
枪类
- 使用
Gun
类可以创建 枪对象 - 枪有三个属性:
- 型号 model:字符串
- 杀伤力 damage:整数
- 子弹数量 bullet_count:整数,枪初始没有子弹
- 调用
add_bullets
方法可以增加 子弹数量 - 调用
shoot
方法可以给参数 敌人对象 造成伤害- 如果 没有子弹,则 提示玩家 并且返回
- 如果 有子弹,则:
- 子弹数量 减少
- 调用 匪徒对象 的
hurt
方法,给匪徒造成伤害
注意:
在调用 shoot
方法时:
- 如果传入的
bad_man
是由Player
创建的对象,就让bad_man
调用hurt
方法,处理bad_man
的受伤细节
# 自定义枪类 class Gun(object): def __init__(self, model, damage): # 添加属性并赋值 # 型号 self.model = model # 杀伤力 self.damage = damage # 子弹数量 self.bullet_count = 0 # 追踪属性变化 def __str__(self): return "型号:%s, 杀伤力:%d, 子弹数:%d" % (self.model, self.damage, self.bullet_count) # 添加子弹 def add_bullets(self, count): self.bullet_count += count # 枪打坏人 def shoot(self, bad_man): # 判断枪是否有子弹 if self.bullet_count <= 0: print("请添加子弹...") return # 发射一颗子弹 self.bullet_count -= 1 # 判断子弹是否击中坏人 # 如果击中 if bad_man: # 叫坏人受伤 bad_man.hurt(self) print("%s发射了一颗子弹, 剩余子弹数量:%d" % (self.model, self.bullet_count)) if __name__ == '__main__': # 创建一把ak47 ak47 = Gun("AK47", 50) print(ak47) # ak47.add_bullets(10) # print(ak47) # 发射一颗子弹未击中敌人 ak47.shoot(None)
例子:
# 自定义枪类 class Gun(object): def __init__(self, model, damage): # 型号 self.model = model # 杀伤力 self.damage = damage # 子弹数量 self.bullet_count = 0 # 追踪属性值变化 def __str__(self): return "型号:%s, 杀伤力:%d, 子弹数量:%d" % (self.model, self.damage, self.bullet_count) # 填装子弹 def add_bullet(self, count): # 修改bullet_count属性值 self.bullet_count += count # 枪打敌人 def shoot(self, bad_man): # 判断是否有子弹 if self.bullet_count <= 0: print("请先填装子弹,再射击...") return # 如果有子弹 # 消耗一颗子弹 self.bullet_count -= 1 # 判断是否击中敌人 # 击中 if bad_man: # 让匪徒受伤 pass print("%s发射了一颗子弹,子弹剩余%d颗" % (self.model, self.bullet_count)) # 创建ak47 ak47 = Gun("AK47", 50) print(ak47) ak47.shoot(None) ak47.add_bullet(10) print(ak47) ak47.shoot(None)