需求:警察用枪法中了匪徒
class Gun(object):
def __init__(self,model,damage):
self.model= model
self.damage= damage
self.bullet_count= 0
def __str__(self):
return "型号:%s,杀伤力:%d,子弹数量:%d" % (self.model,
self.damage,
self.bullet_count)
def add_bullet(self,count):
self.bullet_count+= count
def shoot(self, bad_man):
if self.bullet_count<=0:
print("请先填装子弹,在进行射击")
return
self.bullet_count-=1
if bad_man:
bad_man.hurt(self)
print("%s发射了以颗子弹,子弹剩余%d颗" % (self.model,
self.bullet_count))
class Player(object):
def __init__(self,name,hp=100):
self.name= name
self.hp= hp
self.gun= None
def __str__(self):
return "名字:%s,血量:%s,枪:%s" % (self.name,
self.hp,
self.gun)
def fire(self,bad_man):
if not self.gun:
print("请佩戴枪")
return
if self.gun.bullet_count<= 0:
self.gun.add_bullet(10)
self.gun.shoot(bad_man)
def hurt(self,police_man_gun):
self.hp-= police_man_gun.damage
if self.hp<=0:
print("%s[%d]被%s击毙了" % (self.name,
self.hp,
police_man_gun.model))
else:
print("%s[%d]被%s击中了" % (self.name,
self.hp,
police_man_gun.model))
_98k= Gun("98k",100)
police_man= Player("警察")
bad_man= Player("匪徒",70)
police_man.fire(bad_man)
police_man.gun= _98k
police_man.fire(bad_man)
结果:
请佩戴枪
匪徒[-30]被98k击毙了
98k发射了以颗子弹,子弹剩余9颗
网友评论