需求:狙擊手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)))