需求:狙击手xxx使用xx枪,射击敌人xxx,敌人生命值归0,应声倒下
分析设计类:
- 封装狙击手类 属性: 名字 行为:捡枪 装弹 射击
- 封装枪类 属性: 型号 行为:射击
- 封装弹夹类 属性:弹夹容量 存储子弹的列表
- 封装子弹类 属性:伤害值 移动速度 行为:移动
- 封装敌人类 属性:名称 生命值
#狙击手类 class Sniper:def __init__(self,name):self.name = name# self.gun = None#捡枪def pickupGun(self):gun = Gun('AWM')#给对象添加一个gun的属性self.gun = gun#装弹def loading(self):#创建一个弹容量为10的弹夹clip = Clip(10)for i in range(clip.capacity):bullet = Bullet()#循环装子弹clip.bullet_list.append(bullet)#给你拥有的枪添加一个属性self.gun.clip = clip#射击敌人def shoot(self,enemy):print('{}瞄准{}进行射击'.format(self.name,enemy.name))self.gun.shoot(enemy) #枪类 class Gun:def __init__(self,type):self.type = type#枪的射击功能def shoot(self,enemy):while enemy.hp > 0:# 将子弹从弹夹中移除bullet = self.clip.bullet_list.pop()enemy.hp -= bullet.damageif enemy.hp <= 0:bullet.move()print('敌人{}应声倒下'.format(enemy.name)) #弹夹类 class Clip:def __init__(self,capacity):#弹夹容量self.capacity = capacity#用来存储子弹的列表self.bullet_list = [] #子弹类 class Bullet:def __init__(self):self.damage = 100self.speed = 1000def move(self):print('子弹以{}m/s向敌人'.format(self.speed)) #敌人类 class Enemy:def __init__(self,name,hp):self.name = nameself.hp = hp#创建狙击手对象 sniper = Sniper('海豹突击1号') #狙击手捡枪 sniper.pickupGun() # print(dir(sniper)) # print(dir(sniper.gun)) #装弹 sniper.loading() # print(dir(sniper.gun)) # #打印狙击手的枪的弹夹的子弹列表中的子弹 # print(sniper.gun.clip.bullet_list) # #创建敌人对象 enemy = Enemy('小日本1',100) #射击 sniper.shoot(enemy) print('枪中剩余子弹{}发'.format(len(sniper.gun.clip.bullet_list)))