[演習12]オブジェクト指向の小さな演習

動物園には10の部屋があり、部屋番号は1から10の範囲です。各部屋には、体重200kgのトラまたは体重100kgの羊がいます。ゲーム開始後、システムはトラや羊をランダムに10の部屋に配置します。次に、部屋番号をランダムに指定し、ドアをノックするか餌を与えるかをプレーヤーに選択してもらいます。
餌を与えることを選択した場合:トラに餌を与えるには肉という単語を入力し、羊に餌を与えるには草という単語を入力する必要があります。ちなみに、あなたの体重に10ポンドを追加します。ちょっと間違っ
ています。ノックを選択すると10ポンド減量します。部屋のドアをノックすると、動物と呼ばれ、トラは「うわー!!」と表示され、羊は「ミー~~」と表示されます。動物は呼び出されるたびに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