艰难学Python,第43个练习

3 投票
1 回答
1610 浏览
提问于 2025-04-17 10:38

我现在正在学习Zed Shaw的《Learn Python the Hard Way》。我在第43个练习上遇到了困难,这个练习让我创建一个文本游戏,要求如下:

  • 使用多个文件
  • 每个“房间”用一个类来表示

到目前为止,我已经开始了两个文件,一个是游戏运行的文件,另一个是房间的文件:

game_runner.py

from game_map import *

class Runner(object):
    def __init__(self, start):
        self.start = start

    def play(self):
        next_room = self.start

        while True:
            print '\n'
            print '-' * 7
            print next_room.__doc__
            next_room.proceed()

firstroom = Chillin()

my_game = Runner(firstroom)

my_game.play()

game_map.py

from sys import exit

class Chillin(object):
    """It's 8pm on a Friday night in Madison. You're lounging on the couch with your 
roommates watching Dazed and Confused. What is your first drink?
    1. beer
    2. whiskey
    3. vodka
    4. bowl
"""
    def __init__(self):
        self.prompt = '> '

    def proceed(self):
        drink = raw_input(self.prompt)

        if drink == '1' or drink == 'beer':
            print '\n Anytime is the right time.'
            print 'You crack open the first beer and sip it down.'
            room = Pregame()
            return room
        #rest of drinks will be written the same way


class Pregame(object):
    """It's time to really step up your pregame.
How many drinks do you take?
"""

    def proceed(self):
        drinks = raw_input('> ')
    #and so on

我遇到的问题是,游戏运行的文件无法进入下一个房间。当我运行它时,它在第一个房间里无限循环:打印Chillin()的文档字符串,询问输入,然后重复这个过程。

我该如何修改我的运行文件和/或地图,以便在第一个房间输入正确的回答后,能够返回下一个类,比如Pregame()呢?

1 个回答

6

我觉得你只需要把这个部分:

next_room.proceed()

改成这个:

next_room = next_room.proceed()

因为在你的 while True: 循环里,你从来没有重新给你用的那个变量赋值,所以它的行为会一直保持不变。

撰写回答