文本冒险游戏布尔变量对我不起作用

Text Adventure Game boolean variable doesn't work for me

我的文字冒险游戏有点问题。这个想法是从客厅开始,走到地下室拿钥匙,当你再次进入客厅时你应该赢了。当我执行我的代码时,它只是让我进入房间,布尔值应该告诉 if 语句 has_key = true 但它总是不起作用。有什么想法吗?

def welcomeMessage():
    print "Welcome to my game!!"

def winnerMessage():
    print "You're a winner!! Congratulations!!"
    userQuit()

def userQuit(): 
    print "Thanks for playing!"

def living_room():
    # This part isn't executing (Boolean doesn't work here)
    # I want the if statement to execute, not the else statement
    if has_key == True:
        winnerMessage()
        userQuit()
    else: 
        print ("\nYou are in the living room. The paint from the walls is tearing off."
        +" There is a door near you, but it seems to be locked. To your west is the"
        +" kitchen, where you can eat some tasty snacks and to your south is a bedroom. ")
        direction = raw_input("Which direction would you like to go? (W)est or (S)outh? You also have the option to (Q)uit. ")
        if direction == "W":
            kitchen()
        elif direction == "S":
            bed_room()
        elif direction == "N":
            print "Sorry, you can't go north here."
            living_room()
        elif direction == "E":
            print "Sorry, you can't go east here."
            living_room()
        elif direction == "Q":
            userQuit()
        else:
            print "Sorry, that's not a valid direction."
            living_room()


def kitchen():
    print ("\nYou are in the kitchen. The water from the sink is slightly running. All of the"
    +" cupboards in the kitchen have been left open, like someone has searched through them."
    +" To your south is the dining room, and to your east is the living room. ")
    direction = raw_input("Which direction would you like to go? (S)outh or (E)ast? You also have the option to (Q)uit. ")
    if direction == "S":
        dining_room()
    elif direction == "E":
        living_room()
    elif direction == "N":
        print "Sorry, you can't go north here."
        kitchen()
    elif direction == "W":
        print "Sorry, you can't go west here."
        kitchen()
    elif direction == "Q":
        userQuit()  
    else:
        print "Sorry, that's not a valid direction."
        kitchen()


def bed_room():
    print ("\nYou are in the bedroom. One of the windows in the room is slightly ajar. The other window"
    +" is shattered with a brick laying on the floor next to it. To your west is the dining room and"
    +" to your north is the living room.")
    direction = raw_input("Which direction would you like to go? (W)est or (N)orth? You also have the option to (Q)uit. ")  
    if direction == "W":
        dining_room()
    elif direction == "N":
        living_room()
    elif direction == "E":
        print "Sorry, you can't go east here."
        bed_room()
    elif direction == "S":
        print "Sorry, you can't go south here."
        bed_room()
    elif direction == "Q":
        userQuit()
    else:
        print "Sorry, that's not a valid direction."
        bed_room()

def dining_room():
    print ("\nYou are in the dining room. It is very hard to see in here due to the dim lighting. You notice a staircase is the"
    +" in the center of the room. To your north is the kitchen, and to your east is the bedroom.")
    direction = raw_input("Which direction would you like to go? (N)orth or (E)ast or go (D)own the staircase? You also have the option to (Q)uit. ")
    if direction == "N":
        kitchen()
    elif direction == "E":
        bed_room()
    elif direction == "D":
        basement()
    elif direction == "S":
        print "Sorry, you can't go south here."
        dining_room()
    elif direction == "W":
        print "Sorry, you can't go west here."
        dining_room()
    elif direction == "Q":
        userQuit()
    else:
        print "Sorry, that's not a valid direction."
        dining_room()

def basement():
    print ("\nYou are now in the basement. A cloud of dust passes by you and makes it hard to breath. You move away from the area"
    +" and you notice a key on the floor. You pick up the key and hold onto it. You may use it for later. ")
    direction = raw_input("Press U to go upstairs. You also have the option to (Q)uit. ")
    if direction == "U":
        has_key = True
        dining_room()
    elif direction == "Q":
        userQuit()
    else:
        print "Sorry, the only place you can go is back upstairs."
        basement()

welcomeMessage()
has_key = False
living_room()

虽然has_key是在调用living_room()之前定义的,但它的作用域并没有渗透到从 living_room() 调用的例程中定义的任何同名变量。那是因为在 Python 中,函数体是一个局部作用域块。在函数体中声明或分配的任何变量都是该函数的局部变量,除非明确声明为全局变量。

特别是,在 basement() 中定义的 has_keybasement 的本地作用域()。这是一个不同的新局部变量。

basement() 中对 has_key 所做的状态更改不会反映在 has_key最初是在调用living_room()之前定义的。他们在不同的范围。

尽管一种选择是在其状态将被更改的例程中声明 has_key 变量为全局变量(如 basement()),但通常不考虑全局变量最佳实践。更改函数中全局变量的状态可能会导致难以发现错误。可能更好的做法是让地下室 return 它的状态并在其调用者中检查该状态。

我注意到您的几个函数是递归的,不确定在这种情况下这是最佳选择,但这是另一个问题。

http://spartanideas.msu.edu/2014/05/12/a-beginners-guide-to-pythons-namespaces-scope-resolution-and-the-legb-rule/ 视为有关 Python 变量作用域的一个教程。

basement() 函数中更改 has_key 的值之前插入此行:

global has_key

它将告诉 Python 将值分配给全局作用域 has_key 而不是在函数内部创建一个新的局部作用域 has_key

Python 必须被告知您的 has_key 变量是全局类型:

def basement():
    global has_key
    ...
    if direction == "U":
        has_key = True

稍作重写,您可以使用 message passing 来控制玩家当前所在的位置。

因此,living_room 函数可以 return 您的 "game loop" 接下来应该调用:

def game_loop():
    first_room = living_room

    next_room = first_room()
    while callable(next_room):
        next_room = next_room()

典型的游戏代码看起来比你的更像这样。它有几个优点,首先是涉及的递归较少,因此 "stack" 不会那么深。其次,它允许您在房间之间应用一些通用逻辑,例如追踪玩家去过的地方。

您还可以使整个程序更加面向对象并将 has_key 设置为对象的属性。只需要添加一个class,一个init方法来初始化self.has_key = False,把所有的函数都花掉一堆自己的。 为了防止你大量复制和粘贴,我已经为你做了。

 class TextAdventure(object):
    def __init__(self):
        self.has_key = False

    def welcomeMessage(self):
        print "Welcome to my game!!"

    def winnerMessage(self):
        print "You're a winner!! Congratulations!!"
        self.userQuit()

    def userQuit(self): 
        print "Thanks for playing!"

    def living_room(self):
        # This part isn't executing (Boolean doesn't work here)
        # I want the if statement to execute, not the else statement
        if self.has_key == True:
            self.winnerMessage()
            self.userQuit()
        else: 
            print ("\nYou are in the living room. The paint from the walls is tearing off."
            +" There is a door near you, but it seems to be locked. To your west is the"
            +" kitchen, where you can eat some tasty snacks and to your south is a bedroom. ")
            direction = raw_input("Which direction would you like to go? (W)est or (S)outh? You also have the option to (Q)uit. ")
            if direction == "W":
                self.kitchen()
            elif direction == "S":
                self.bed_room()
            elif direction == "N":
                print "Sorry, you can't go north here."
                self.living_room()
            elif direction == "E":
                print "Sorry, you can't go east here."
                self.living_room()
            elif direction == "Q":
                self.userQuit()
            else:
                print "Sorry, that's not a valid direction."
                self.living_room()


    def kitchen(self):
        print ("\nYou are in the kitchen. The water from the sink is slightly running. All of the"
        +" cupboards in the kitchen have been left open, like someone has searched through them."
        +" To your south is the dining room, and to your east is the living room. ")
        direction = raw_input("Which direction would you like to go? (S)outh or (E)ast? You also have the option to (Q)uit. ")
        if direction == "S":
            self.dining_room()
        elif direction == "E":
            self.living_room()
        elif direction == "N":
            print "Sorry, you can't go north here."
            self.kitchen()
        elif direction == "W":
            print "Sorry, you can't go west here."
            self.kitchen()
        elif direction == "Q":
            self.userQuit()  
        else:
            print "Sorry, that's not a valid direction."
            self.kitchen()


    def bed_room(self):
        print ("\nYou are in the bedroom. One of the windows in the room is slightly ajar. The other window"
        +" is shattered with a brick laying on the floor next to it. To your west is the dining room and"
        +" to your north is the living room.")
        direction = raw_input("Which direction would you like to go? (W)est or (N)orth? You also have the option to (Q)uit. ")  
        if direction == "W":
            self.dining_room()
        elif direction == "N":
            self.living_room()
        elif direction == "E":
            print "Sorry, you can't go east here."
            self.bed_room()
        elif direction == "S":
            print "Sorry, you can't go south here."
            self.bed_room()
        elif direction == "Q":
            self.userQuit()
        else:
            print "Sorry, that's not a valid direction."
            self.bed_room()

    def dining_room(self):
        print ("\nYou are in the dining room. It is very hard to see in here due to the dim lighting. You notice a staircase is the"
        +" in the center of the room. To your north is the kitchen, and to your east is the bedroom.")
        direction = raw_input("Which direction would you like to go? (N)orth or (E)ast or go (D)own the staircase? You also have the option to (Q)uit. ")
        if direction == "N":
            self.kitchen()
        elif direction == "E":
            self.bed_room()
        elif direction == "D":
            self.basement()
        elif direction == "S":
            print "Sorry, you can't go south here."
            self.dining_room()
        elif direction == "W":
            print "Sorry, you can't go west here."
            self.dining_room()
        elif direction == "Q":
            self.userQuit()
        else:
            print "Sorry, that's not a valid direction."
            self.dining_room()

    def basement(self):
        print ("\nYou are now in the basement. A cloud of dust passes by you and makes it hard to breath. You move away from the area"
        +" and you notice a key on the floor. You pick up the key and hold onto it. You may use it for later. ")
        direction = raw_input("Press U to go upstairs. You also have the option to (Q)uit. ")
        if direction == "U":
            self.has_key = True
            self.dining_room()
        elif direction == "Q":
            self.userQuit()
        else:
            print "Sorry, the only place you can go is back upstairs."
            self.basement()

def main():
    t = TextAdventure()
    t.welcomeMessage()
    t.living_room()

if __name__ == "__main__":
    main()

很棒的游戏。玩得很开心。虽然有点短,但感谢分享并继续努力! 如果你让它更面向对象,你也可以提供一些用户操作。 :)

class TextAdventure(object):

    def __init__(self):
        self.has_key = False

    def use(self):
        print 'You used something'

    def eat(self):
        print 'You ate something'

    def drink(self):
        print 'You drank something'


def main():
    t = TextAdventure()
    actions = { 'use' : t.use, 'eat' : t.eat, 'drink' : t.drink }
    a, b, c = actions.keys()
    action = raw_input('Choose what to do [{0}, {1}, {2}]'.format(a,b,c))
    if action in actions:
        actions[action]()