【练习12】面向对象的小练习

动物园里面有10个房间,房间号从1 到10。每个房间里面可能是体重200斤的老虎或者体重100斤的羊。游戏开始后,系统随机在10个房间中放入老虎或者羊。 然后随机给出房间号,要求游戏者选择敲门还是喂食。
如果选择喂食:喂老虎应该输入单词 meat,喂羊应该输入单词 grass。喂对了,体重加10斤。 喂错了,体重减少10斤
如果选择敲门:敲房间的门,里面的动物会叫,老虎叫会显示 ‘Wow !!’,羊叫会显示 ‘mie~~’。 动物每叫一次体重减5斤。
游戏3分钟结束后,显示每个房间的动物和它们的体重。

from random import randint
import time

#老虎类
class Tiger:
    animal_name = '老虎'
    def __init__(self,weight = 200):
        self.weight = weight

    def feed(self,food):
        if food == 'meat':
            self.weight += 10
            print('投食正确,体重+10')
        else:
            self.weight -= 10
            print('投食错误,体重-10')

    def roar(self):
        print('Wow!!')
        self.weight -= 5

#羊类
class Sheep:
    animal_name = '羊'

    def __init__(self, weight=100):
        self.weight = weight

    def feed(self, food):
        if food == 'grass':
            self.weight += 10
            print('投食正确,体重+10')
        else:
            self.weight -= 10
            print('投食错误,体重-10')

    def roar(self):
        print('mie~~')
        self.weight -= 5

# 房间类 房间的编码、动物
class Room:
    def __init__(self,roomNo,room_animal):
        self.roomNo = roomNo
        self.room_animal = room_animal

rooms = []
for i in range(10):
    if randint(0,1):
        room = Room(i,Tiger(200))
    else:
        room = Room(i,Sheep(100))
    rooms.append(room)

startTime = time.time()
while True:
    endTime = time.time()
    if (endTime-startTime)>180:
        print('\n\n==========Game Over==========\n\n')
        for No,animal in enumerate(rooms):
            print(f'{No+1}号房间:【{animal.room_animal.animal_name}】的体重为:{animal.room_animal.weight} 斤')
        break
    game_room = randint(1,10)  #用于显示房间号
    roomNo = rooms[game_room-1]
    userChose1 = input(f'当前是{game_room}房间,要敲房门吗?[y/n]')
    if userChose1 == 'y':
        roomNo.room_animal.roar()
    userChose2 = input(f'请给动物投食: [meat/grass]')
    roomNo.room_animal.feed(userChose2.strip())

猜你喜欢

转载自blog.csdn.net/weixin_45128456/article/details/112125623