喂动物 老虎和羊

发布时间 2023-07-18 22:17:10作者: 胖豆芽
import random


# 动物类
class Animal:
    def __init__(self, animal_type, weight, cries, food):
        self._animal_type = animal_type
        self._weight = weight
        self._cries = cries
        self._food = food

    def getWeight(self):
        print(f"{self._animal_type}的体重是{self._weight}")
        return self._weight

    def eat(self, food):

        if self._food == food:
            self._weight += 10
        else:
            self._weight -= 10
        print(f"{self._animal_type}吃了{food}后,当前体重为{self._weight}")
        return self._weight

    def cries(self):

        self._weight -= 5
        print(f"{self._animal_type}发出了{self._cries}的叫声,当前体重为{self._weight}")
        return self._weight




# 老虎类
class Tiger(Animal):
    def __init__(self):
        super().__init__("老虎", 200, "wow", "")


# 羊类
class Sheep(Animal):
    def __init__(self):
        super().__init__("", 100, "mie", "")


# 房间类
class Room:
    # _animals = []
    def __init__(self):# 不传参数时因为 定义的动物列表是一个常量,后续不需要修改
        # 在Room类 定义的动物列表  在动物类中的 其他函数比如 放入动物们和获得动物们中也可以调用
        self._animals = []
        # 定义一个数组  获得10个房间里的 全部的动物
    def putAnimal(self, animal):# 传入动物参数是因为动物是个变量
        self._animals.append(animal)# 将每个动物都放入动物列表中


    def getAnimals(self):# 在房间类中 定义一个方法获得动物列表
        return self._animals


# 饲养员类
class Zookeeper:
    def __init__(self):
        self._rooms = [] # 实例化一个10 个房间的房子

    def putAnimalInRooms(self):
        for _ in range(10):#  10个房间里都需要放入动物
            num = random.randint(1, 2)# 使用1和2代表随机水的范围
            if num == 1: # 当1时放入 老虎
                animal = Tiger()
            else:# 非1时放入 羊
                animal = Sheep()
            room = Room() # 实例化出来一个房间room
            room.putAnimal(animal)# 将动物放到这个房间
            self._rooms.append(room) # 将实例化的房间放到10个房子中

    def feedAnimals(self):# 定义一个喂动物的动作
        count=0 # 房间号
        for room in self._rooms: # 遍历每个房间
            count += 1 # 房间号
            print(f'第{count}个房间')
            animals = room.getAnimals() # 调用房间类的获得动物方法
            for animal in animals: # 遍历全部的动物
                animal.getWeight() # 获得体重
                animal.cries() # 动物叫
                food = animal._food # 给动物喂食物
                animal.eat(food) # 动物吃食物
                animal.getWeight() # 动物获得体重



zookeeper = Zookeeper() # 实例化饲养员
zookeeper.putAnimalInRooms() # 饲养员将动物放入房间
zookeeper.feedAnimals() #饲养员喂养动物