85面向对象的警察与劫匪的例子
还得多练习多敲
class Police:
""" 警察 """
def __init__(self, name, role):
self.name = name
self.role = role
if role == '队员':
self.hit_points = 200
else:
self.hit_points = 500
def show_status(self):
""" 查看警察状态 """
message = '警察{}的生命值为:{}'.format(self.name, self.hit_points)
print(message)
def bomb(self, terrorist_list):
""" 投炸弹,炸掉恐怖分子 """
for terrorist in terrorist_list:
terrorist.blood -= 200
terrorist.show_status()
class Terrorist:
""" 恐怖分子 """
def __init__(self, name, blood=300):
self.name = name
self.blood = blood
def shoot(self, police_object):
""" 开枪射击某个警察 """
police_object.hit_points -= 5
police_object.show_status()
# def strafe(self, police_object_list):
def strafe(self, *police_object_list): # 组包
""" 扫射某些警察 """
for police_object in police_object_list:
police_object.hit_points -= 8
police_object.show_status()
def show_status(self):
""" 查看恐怖分子状态 """
message = "恐怖分子{}的血量为:{}".format(self.name, self.blood)
print(message)
def run():
# 1.创建3个警察
p1 = Police("吴佩琦", '队员')
p2 = Police("元浩", "队员")
p3 = Police("于超", "队长")
# 创建2个土匪
t1 = Terrorist('alex')
t2 = Terrorist('eric')
# alex射击于超
t1.shoot(p3)
# alex扫射
# t1.strafe([p1, p2, p3])
t1.strafe(p1, p2, p3)
# eric射击元浩
t2.shoot(p2)
# 吴佩琦炸了那群王大蛋
p1.bomb([t1, t2])
# 吴佩琦又炸了alex
p1.bomb([t1])
if __name__ == '__main__':
run()
# output:
"""
警察于超的生命值为:495
警察吴佩琦的生命值为:192
警察元浩的生命值为:192
警察于超的生命值为:487
警察元浩的生命值为:187
恐怖分子alex的血量为:100
恐怖分子eric的血量为:100
恐怖分子alex的血量为:-100
"""
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/17165857.html