应用:反恐精英
1. 人类
2. 子弹类
3. 弹夹类
- 属性
- 方法
- 保存子弹(安装子弹的时候)
- 弹出子弹(开枪的时候)
4. 枪类
参考代码
class Person(object):
def __init__(self, new_name):
self.name = new_name
self.gun = None
self.ph = 100
def anzhuang_zidan(self, danjian_temp, zidan_temp):
danjian_temp.baocun(zidan_temp)
def anzhuang_danjia(self, gun_temp, danjia_temp):
gun_temp.baocun(danjia_temp)
def na_gun(self, gun_temp):
self.gun = gun_temp
def __str__(self):
if self.gun:
return "%s 的ph为:%d, 他一把%s:" % (self.name, self.ph, self.gun)
else:
return "%s 的ph为:%d, 他么有枪..." % (self.name, self.ph)
def kaiqiang(self, diren):
self.gun.fire(diren)
def diaoxue(self, shashangli):
self.ph -= shashangli
class Gun(object):
def __init__(self, new_name):
self.name = new_name
self.danjia = None
def baocun(self, danjia_temp):
self.danjia = danjia_temp
def __str__(self):
if self.danjia:
return "%s有弹夹,%s" % (self.name, self.danjia)
else:
return "%s没有弹夹"
def fire(self, diren):
zidan_temp = self.danjia.tanchu_zidan()
if zidan_temp:
zidan_temp.shanghai(diren)
else:
print("%s没子弹了" % self.name)
class Danjia(object):
def __init__(self, new_max_num):
self.max_num = new_max_num
self.zidan_list = []
def baocun(self, zidan_temp):
self.zidan_list.append(zidan_temp)
def __str__(self):
return "弹夹:%d/%d" % (len(self.zidan_list), self.max_num)
def tanchu_zidan(self):
if len(self.zidan_list) > 0:
return self.zidan_list.pop()
else:
return None
class Bullet(object):
def __init__(self, new_shashangli):
self.shashangli = new_shashangli
def shanghai(self, diren):
diren.diaoxue(self.shashangli)
lao_wang = Person("老王")
ak47 = Gun("AK47")
dan_jia = Danjia(20)
bullet = Bullet(10)
lao_wang.anzhuang_zidan(dan_jia, bullet)
print(dan_jia)
lao_wang.anzhuang_danjia(ak47, dan_jia)
print(ak47)
lao_wang.na_gun(ak47)
print(lao_wang)
gebi_laowang = Person("隔壁老王")
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
for i in range(5):
bullet = Bullet(10)
lao_wang.anzhuang_zidan(dan_jia, bullet)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)
lao_wang.kaiqiang(gebi_laowang)
print(gebi_laowang)