如何从不同函数中的函数调用变量?

时间:2016-04-27 18:36:51

标签: python python-2.7

我目前正在尝试创建基于文本的游戏。 我正在尝试这样做,当你拿起你有变量的项目,读取'True',这样你就可以在不同的房间里使用这些项目。 我目前的问题是在一个房间你杀死了一个怪物所以我创建了一个变量,其中monster_is_dead = True,但是一旦我移动到另一个函数,该脚本忘记了monster_is_dead.it很难解释很多脚本到粘贴但我会尝试挑选出我遇到问题的脚本部分。

def room_2():
riddle_monster_alive = True
while riddle_monster_alive:
    print 'As you step into the room, you feel someone watching you.. You close the door behind you and hear the door click.\n you are locked in!'
    print "You look up into the center of the room to be greeted by a strange creature,a Kappa"
    print 'the creature calls out to you "You are lost here, You could die here. I could kill you now for my Master, but that is no fun."'
    print '"How about we play a game? if you win, I will go, if you lose, I will eat you right now"'
    import random
    a = 'rock'
    b = 'paper'
    c = 'scissors'
    rockpaperscissorlist = [a,b,c]
    print 'The Kappa are known for their trickery and games, you best play his game'
    print '"Rock,paper and scissors we play till one of us loses"'
    game_choice = raw_input('Pick A:Rock B:Paper C:Scissors [a/b/c]\n>').lower()
    kappa_choice = random.choice(rockpaperscissorlist)
        elif game_choice == 'a' and kappa_choice == c:
        print 'Kappa picks scissors'
        print 'You Win!'
        riddle_monster_alive = False
        break
riddle_monster_alive == False
room_2a()

所以我在2号房间有一个新功能,怪物已经死了。然而,剧本变得复杂,因为我让玩家移回房间,因为他们将再次进入功能室_2(),并且必须再次与怪物对战。

def room_2a():
print 'The air is still as the Kappa has now vanished.'
print 'You see a door the right and a door to the left'
print 'What will you do?\n A:Take the door to the right\n B:Take the door to the left?\n C:Go back the way you came\n D:Search the room'
room2choice = raw_input('> ').lower()
if room2choice == 'a':
    room_10()
elif room2choice == 'b':
    room_3()
elif room2choice == 'c':
    room_1a()
elif room2choice == 'd':
    print 'You searched but found nothing but a puddle of water from where the Kappa once stood'
    room_2a()

我觉得我要把它变得比必要的更复杂。

1 个答案:

答案 0 :(得分:2)

您不能从函数外部将变量 local 调用到函数(仅在该函数的上下文中定义)。这违反了范围规则。函数中声明的变量与外部定义的变量不同

例如,

x = 10 # global variable, defined outside function
def f():
    x = 5 # creates a new local variable, defined inside function
    return # local variable is destroyed
f()
print(x)
>>>> 10 # global variable is returned and unaffected

您需要使用global关键字声明您希望变量是全局变量(即在任何地方都可访问)。

e.g。

x = 10
def f():
    global x # lets Python know you want to assign a value to a global variable
    x = 5 # now you're changing global variable x, outside the function
    return
f()
print(x)
>>>> 5 # global variable is changed

在您的情况下,您想要

def room_2():
    global riddle_monster_alive # declares this variable global, so room_2() can change the global value
    riddle_monster_alive = False # makes this variable False everywhere
    ... # continue as before.

被说出来......

使用全局变量是一种已知的反模式。你应该尽量避免使用这个结构。

Matt S.在评论中指出,使用对象和类是一个更好的解决方案。