示例如下:
1. ⼈类
属性:
姓名
⾎量
持有的枪
⽅法:
安⼦弹
安弹夹
拿枪(持有抢)
开枪
2. ⼦弹类
属性:
杀伤⼒
方法:
伤害敌⼈(让敌⼈掉⾎)
3. 弹夹类
属性:
容量(⼦弹存储的最⼤值)
当前保存的⼦弹
⽅法:
保存⼦弹(安装⼦弹的时候)
弹出⼦弹(开枪的时候)
4. 枪类
属性:
弹夹(默认没有弹夹,需要安装)
⽅法:
连接弹夹(保存弹夹)
射⼦弹
# 人类
class Ren:
def __init__(self,name):
self.name = name # 人的名字
self.xue = 100 # 血量
self.qiang = None # 人拿的枪支名字
# 定义返回属性值函数
def __str__(self):
return self.name+"剩余血量"+str(self.xue)
# 安装子弹
def anzidan(self,danjia,zidan):
danjia.baocunzidan(zidan)
# 安弹夹
def andanjia(self, qiang, danjia):
qiang.lianjiedanjia(danjia)
# 拿枪
def naqiang(self, qiang):
self.qiang = qiang
# 开枪
def kaiqiang(self, diren):
self.qiang.she(diren)
# 掉血
def diaoxue(self, shashangli):
self.xue -= shashangli
#弹夹类
class Danjia:
def __init__(self, rongliang):
self.rongliang = rongliang
self.rongnaList = []
def __str__(self):
return "弹夹当前的⼦弹数量为:" + str(len(self.rongnaList)) + "/"
def baocunzidan(self, zidan):
if len(self.rongnaList) < self.rongliang:
self.rongnaList.append(zidan)
def chuzidan(self):
# 判断当前弹夹中是否还有⼦弹
if len(self.rongnaList) > 0:
# 获取最后压⼊到单间中的⼦弹
zidan = self.rongnaList[-1]
self.rongnaList.pop()
return zidan
else:
return None
# 子弹
class Zidan:
def __init__(self,shashangli):
self.shashangli = shashangli
def shanghai(self,diren):
diren.diaoxue(self.shashangli)
#枪类
class Qiang:
def __init__(self):
self.danjia = None
def __str__(self):
if self.danjia:
return "枪当前有弹夹"
else:
return "枪没有弹夹"
def lianjiedanjia(self,danjia):
if not self.danjia:
self.danjia = danjia
def she(self,diren):
zidan = self.danjia.chuzidan()
if zidan:
zidan.shanghai(diren)
else:
print("没有⼦弹了,放了空枪....")
#创建⼀个⼈对象
laowang = Ren("⽼王")
#创建⼀个弹夹
danjia = Danjia(20)
print(danjia)
#循环的⽅式创建⼀颗⼦弹,然后让⽼王把这颗⼦弹压⼊到弹夹中
i=0
while i<5:
zidan = Zidan(5)
laowang.anzidan(danjia,zidan)
i+=1
#测试⼀下,安装完⼦弹后,弹夹中的信息
print(danjia)
#创建⼀个枪对象
qiang = Qiang()
print(qiang)
#让⽼王,把弹夹连接到枪中
laowang.andanjia(qiang,danjia)
print(qiang)
#创建⼀个敌⼈
diren = Ren("敌⼈")
print(diren)
#让⽼王拿起枪
laowang.naqiang(qiang)
#⽼王开枪射敌⼈
laowang.kaiqiang(diren)
print(diren)
print(danjia)
laowang.kaiqiang(diren)
print(diren)
print(danjia)