学习python艰难的方式练习42帮助

时间:2011-03-30 13:43:27

标签: python

嘿伙计们。我有点困在ex42:

from sys import exit
from random import randint

class Game(object):

    def __init__(self, start):
        self.quips = [
            "You died.  You kinda suck at this.",
             "Your mom would be proud. If she were smarter.",
             "Such a luser.",
             "I have a small puppy that's better at this."
        ]
        self.start = start

    def play(self):
        next = self.start

        while True:
            print "\n--------"
            room = getattr(self, next)
            next = room()


    def death(self):
        print self.quips[randint(0, len(self.quips)-1)]
        exit(1)


    def princess_lives_here(self):
        print "You see a beautiful Princess with a shiny crown."
        print "She offers you some cake."

        eat_it = raw_input("> ")

        if eat_it == "eat it":
            print "You explode like a pinata full of frogs."
            print "The Princess cackles and eats the frogs. Yum!"
            return 'death'

        elif eat_it == "do not eat it":
            print "She throws the cake at you and it cuts off your head."
            print "The last thing you see is her munching on your torso. Yum!"
            return 'death'

        elif eat_it == "make her eat it":
            print "The Princess screams as you cram the cake in her mouth."
            print "Then she smiles and cries and thanks you for saving her."
            print "She points to a tiny door and says, 'The Koi needs cake too.'"
            print "She gives you the very last bit of cake and shoves you in."
            return 'gold_koi_pond'

        else:
            print "The princess looks at you confused and just points at the cake."
            return 'princess_lives_here'

    def gold_koi_pond(self):
        print "There is a garden with a koi pond in the center."
        print "You walk close and see a massive fin poke out."
        print "You peek in and a creepy looking huge Koi stares at you."
        print "It opens its mouth waiting for food."

        feed_it = raw_input("> ")

        if feed_it == "feed it":
            print "The Koi jumps up, and rather than eating the cake, eats your arm."
            print "You fall in and the Koi shrugs than eats you."
            print "You are then pooped out sometime later."
            return 'death'

        elif feed_it == "do not feed it":
            print "The Koi grimaces, then thrashes around for a second."
            print "It rushes to the other end of the pond, braces against the wall..."
            print "then it *lunges* out of the water, up in the air and over your"
            print "entire body, cake and all."
            print "You are then pooped out a week later."
            return 'death'

        elif feed_it == "throw it in":
            print "The Koi wiggles, then leaps into the air to eat the cake."
            print "You can see it's happy, it then grunts, thrashes..."
            print "and finally rolls over and poops a magic diamond into the air"
            print "at your feet."

            return 'bear_with_sword'

        else:
            print "The Koi gets annoyed and wiggles a bit."
            return 'gold_koi_pond'


    def bear_with_sword(self):
        print "Puzzled, you are about to pick up the fish poop diamond when"
        print "a bear bearing a load bearing sword walks in."
        print '"Hey! That\' my diamond! Where\'d you get that!?"'
        print "It holds its paw out and looks at you."

        give_it = raw_input("> ")

        if give_it == "give it":
            print "The bear swipes at your hand to grab the diamond and"
            print "rips your hand off in the process.  It then looks at"
            print 'your bloody stump and says, "Oh crap, sorry about that."'
            print "It tries to put your hand back on, but you collapse."
            print "The last thing you see is the bear shrug and eat you."
            return 'death'

        elif give_it == "say no":
            print "The bear looks shocked.  Nobody ever told a bear"
            print "with a broadsword 'no'.  It asks, "
            print '"Is it because it\'s not a katana?  I could go get one!"'
            print "It then runs off and now you notice a big iron gate."
            print '"Where the hell did that come from?" You say.'

            return 'big_iron_gate'

    def big_iron_gate(self):
        print "You walk up to the big iron gate and see there's a handle."

        open_it = raw_input("> ")

        if open_it == 'open it':
            print "You open it and you are free!"
            print "There are mountains.  And berries! And..."
            print "Oh, but then the bear comes with his katana and stabs you."
            print '"Who\'s laughing now!?  Love this katana."'

            return 'death'

        else:
            print "That doesn't seem sensible.  I mean, the door's right there."
            return 'big_iron_gate'


a_game = Game("princess_lives_here")
a_game.play()

播放让我感到困惑,我得到了下一个获得第一个房间的方式,这个房间是在创建Game()的实例时传递的,但它是如何获得下一个房间的?

感谢

4 个答案:

答案 0 :(得分:2)

这部分:

   while True:
        # The following line accesses a class member without knowing
        # its name in advance. 
        # The name is stored in a string (next), and is initially
        # "princess_lives"here". So, for the first case, this would be like
        # room = self.princess_lives_here -> room is assigned a method from
        # this class.
        room = getattr(self, next)

        # Now, room has the method for the room we'll play. We call it, which in
        # the first case mentioned above would be like self.princess_lives_here()
        # and the return value is assigned to next. princess_lives_here returns
        # 'princess_lives_here', 'death', etc. That string will be the one used
        # in the getattr() call in the next iteration.
        next = room()

有关详细信息,请参阅getitem()的python文档和google“python函数的第一类对象”。

答案 1 :(得分:2)

好的代码。

看看这个snippt(它是play()的一部分):

while True:
            print "\n--------"
            room = getattr(self, next)
            next = room()

getattr()行获取名称为next的函数。 所以在开始时它是名为'princess_lives_here'

的函数

next = room()执行该功能并存储下一个房间的名称, 它将被映射到该函数并在下一轮中执行。

编辑:你们回答问题的速度非常快。 ;)

答案 2 :(得分:1)

每个方法都返回另一个方法的名称。

它通过从next对象获取名为self的属性来检索此方法。

getattr(self, next)

接下来,它调用此方法

room()

答案 3 :(得分:0)

通过getattr获得第一个房间。例如,如果查看princess_lives_here,它将返回函数的名称。 getattr检索此函数并将其放在空间中,然后调用它。 room然后返回下一个方法,依此类推。

它基本上是一个非常简单的状态机,其中方法的名称表示下一个状态。

然而,我会说这是一个非常糟糕的做法。函数是Python中的第一类,只能将下一个函数作为值返回。另一方面,我不知道这个练习的意图,我不熟悉它。