【问题标题】:Text Adventure Game boolean variable doesn't work for me文本冒险游戏布尔变量对我不起作用
【发布时间】:2016-01-08 01:16:27
【问题描述】:

我的文字冒险游戏有点问题。这个想法是从起居室开始,到地下室去拿钥匙,当你再次进入起居室时,你应该赢了。但是,当我执行我的代码时,它只是让我进入房间,布尔值应该告诉 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()

【问题讨论】:

  • 提醒:如果您对答案感到满意,请单击投票控件旁边的复选标记以接受它。欢迎使用 StackOverflow!

标签: python text adventure


【解决方案1】:

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

 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]()

【讨论】:

  • 非常感谢你们。我仍然是 Python 的初学者并制作游戏,所以我一定会努力进一步改进代码的结构和游戏本身!再见! :D
  • 代码不起作用,因为 TextAdventure.has_key 方法未定义。
  • 糟糕,你是对的。我编辑了它。 has_key 应该是布尔值而不是方法。
【解决方案2】:

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

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

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

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

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

查看 http://spartanideas.msu.edu/2014/05/12/a-beginners-guide-to-pythons-namespaces-scope-resolution-and-the-legb-rule/ 作为 Python 变量范围的教程。

【讨论】:

    【解决方案3】:

    必须告诉 Python 你的 has_key 变量是全局类型的:

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

    通过轻微的重写,您可以使用message passing 来控制播放器当前的位置。

    因此,living_room 函数可以返回您的“游戏循环”接下来应该调用的函数,而不是调用 living_room() 函数并让它通过从内部调用该函数来控制玩家的去向:

    def game_loop():
        first_room = living_room
    
        next_room = first_room()
        while callable(next_room):
            next_room = next_room()
    

    典型的游戏代码看起来比你的更像这样。它有几个优点,首先是涉及的递归更少,因此“堆栈”不会那么深。其次是它可以让你在房间之间应用一些常见的逻辑,例如跟踪玩家的位置。

    【讨论】:

      【解决方案4】:

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

      global has_key
      

      它将告诉 Python 将该值分配给全局范围的 has_key,而不是在函数内部创建一个新的局部范围的 has_key

      【讨论】:

      • 您只在修改全局变量的函数中定义了全局声明。
      • 谢谢,我不知道!
      猜你喜欢
      • 2016-08-25
      • 2013-07-08
      • 2021-10-26
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多