3

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

4 回答 4

2

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

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

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 变量范围的教程之一。

于 2015-10-10T01:37:55.137 回答
2

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

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

通过少量重写,您可以使用消息传递来控制播放器当前所在的位置。

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

def game_loop():
    first_room = living_room

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

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

于 2015-10-10T01:51:06.210 回答
1

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

global has_key

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

于 2015-10-10T01:42:22.477 回答
0

您还可以使整个程序更加面向对象,并将 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]()
于 2015-10-10T02:58:46.813 回答