面向对象思想封装狙击手狙击敌人

需求:狙击手xxx使用xx枪,射击敌人xxx,敌人生命值归0,应声倒下
分析设计类:

  1. 封装狙击手类 属性: 名字 行为:捡枪   装弹   射击
  2. 封装枪类 属性: 型号 行为:射击
  3. 封装弹夹类 属性:弹夹容量   存储子弹的列表
  4. 封装子弹类 属性:伤害值    移动速度 行为:移动
  5. 封装敌人类 属性:名称    生命值
 #狙击手类
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.damage
            if 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 = 100
        self.speed = 1000
    def move(self):
        print('子弹以{}m/s向敌人'.format(self.speed))
#敌人类
class Enemy:
    def __init__(self,name,hp):
        self.name = name
        self.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)))
posted @ 2019-06-01 10:05  Python及时行乐  阅读(172)  评论(0编辑  收藏  举报