生活随笔
收集整理的這篇文章主要介紹了
面向对象思想封装狙击手狙击敌人
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:狙擊手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)))
轉載于:https://www.cnblogs.com/ilovepython/p/11068889.html
總結
以上是生活随笔為你收集整理的面向对象思想封装狙击手狙击敌人的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。