Python案例练习——老王开枪

import time


class Person(object):
    """人的类"""
    def __init__(self, name):
        super(Person, self).__init__()
        self.name = name  # 记录人的名字
        self.gun = None  # 默认人是没有枪的
        self.hp = 100  # 默认人的血量100

    def anzhuang_zidan(self, dan_jia_temp, zi_dan_temp):
        """把子弹安装到弹夹内"""
        dan_jia_temp.baocun_zidan(zi_dan_temp)

    def anzhuang_danjia(self, ak47, dan_jia):
        """把弹夹安装到枪内"""
        ak47.baocun_danjia(dan_jia)

    def na_qiang(self, gun_temp):
        """拿起一把枪"""
        self.gun = gun_temp

    def __str__(self):
        if self.gun:
            return "%s的血量:%d,%s, 他开枪了,嘣!" %(self.name, self.hp, self.gun)
        else:
            if self.hp == 100:
                return "%s的血量,%d, 他没有枪" % (self.name, self.hp)
            elif self.hp > 0:
                return "%s的血量,%d,他没有枪,他正在受到炮火的袭击,小心!他中了一枪..." % (self.name, self.hp)
            else:
                return "%s已经死亡..." % self.name

    def kai_qiang(self, diren, zi_dan_temp, dan_jia_temp):
        """打敌人"""
        diren.hp -= zi_dan_temp.sha_shang_li  # 减血
        dan_jia_temp.zidan_list.pop()  # 减子弹

class Gun(object):
    """枪类"""
    def __init__(self, name):
        super(Gun, self).__init__()
        self.name = name  # 记录枪的类型
        self.danjia = None  # 默认枪中是没有弹夹的

    def baocun_danjia(self, dan_jia_temp):
        """枪保存弹夹"""
        self.danjia = dan_jia_temp

    def __str__(self):
        if self.danjia:
            return "枪的信息:%s, %s" % (self.name, self.danjia)
        else:
            return "枪的信息:%s,这把枪没有弹夹" % self.name

class DanJia(object):
    """弹夹类"""
    def __init__(self, max_num):
        super(DanJia, self).__init__()
        self.max_num =max_num  # 弹夹的最大容量
        self.zidan_list = []  # 用列表保存子弹的数量

    def baocun_zidan(self, zi_dan_temp):
        """弹夹保存子弹"""
        self.zidan_list.append(zi_dan_temp)

    def __str__(self):
        return "弹夹的信息:%d/%d" % (len(self.zidan_list), self.max_num)

class ZiDan(object):
    """子弹类"""
    def __init__(self, sha_shang_li):
        super(ZiDan, self).__init__()
        self.sha_shang_li = sha_shang_li  # 子弹的杀伤力

def main():
    """用来控制整个程序的流程"""
    # 创建老王
    lao_wang = Person('老王')

    # 创建枪
    ak47 = Gun("AK47")

    # 创建弹夹
    dan_jia = DanJia(30)

    # 创建子弹
    zi_dan = ZiDan(10)

    for i in range(25):
        # 老王把子弹安装到弹夹内
        lao_wang.anzhuang_zidan(dan_jia, zi_dan)

    # 老王把弹夹安装到枪中
    lao_wang.anzhuang_danjia(ak47, dan_jia)

    # 测试弹夹的信息
    # print(dan_jia)

    # 测试枪的信息
    # print(ak47)

    # 老王拿枪
    lao_wang.na_qiang(ak47)

    # 测试老王对象
    # print(lao_wang)

    # 创建一个敌人
    gebi_laowang = Person("隔壁老王")

    for i in range(10):
    # 老王拿枪打隔壁老宋
        lao_wang.kai_qiang(gebi_laowang, zi_dan, dan_jia)
        print(lao_wang)
        print(gebi_laowang)
        time.sleep(2)
        print("")

if __name__ == '__main__':
    main()
posted @ 2020-04-10 12:04  秋弦  阅读(129)  评论(0编辑  收藏  举报