Python代码函数无法正确更新变量

时间:2018-10-19 22:35:38

标签: python function variables

我正在尝试首先制作一个基于文本的简单的基于房间的游戏,您可以在一个房间到另一个房间之间进行游戏,它为您提供了描述并且可以四处走动。输入1后,输出将相应工作。在它要求您再次输入并输入方向后,程序什么也不做。 我在代码前面定义了每个不同的room1,room2等。我认为这与我的方向函数和x y变量有关,但我不确定问题出在哪里

import time
import sys
x=1
y=1
def direction():
    global x
    global y

    prompt = input("\nChoose a direction using AWSD:\n")
    if prompt == "a" or prompt == "A":
        x -= 1
    elif prompt == "s" or prompt == "S":
        y -= 1
    elif prompt == "w" or prompt == "W":
        y += 1
    elif prompt == "d" or prompt == "D":
        x += 1

def stutter(text):
    for c in text:
        print(c, end="")
        sys.stdout.flush()
        time.sleep(.04)
stutter(""""You wake up in a dark room with a rusty iron door. There is a small
circular window casting a dim light across the room. Theres two doors leading
out. One forward and one to the right.""")
direction()






if x==1 and y==1:
    stutter(room1)
    direction()
elif x==1 and y==2:
    stutter(room2)
    direction()
elif x==1 and y==3:
    stutter(room3)
    direction()
elif x==2 and y==1:
    stutter(room4)
    direction()
elif x==2 and y==2:
    stutter(room5)
    direction()
elif x==2 and y==2:
    stutter(room6)
    direction()
elif x==3 and y==1:
    stutter(room7)
    direction()
elif x==3 and y==2:
    stutter(room8)
    direction()
elif x==3 and y==3:
    stutter(room9)
    direction()
else:
    stutter("You hit a wall")
    direction()

1 个答案:

答案 0 :(得分:0)

您必须像这样引入while循环:

while(True):
    if x==1 and y==1:
        stutter(room1)
    elif x==1 and y==2:
        stutter(room2)
    elif x==1 and y==3:
        stutter(room3)
    elif x==2 and y==1:
        stutter(room4)
    elif x==2 and y==2:
        stutter(room5)
    elif x==2 and y==2:
        stutter(room6)
    elif x==3 and y==1:
        stutter(room7)
    elif x==3 and y==2:
        stutter(room8)
    elif x==3 and y==3:
        stutter(room9)
    else:
        stutter("You hit a wall")
    direction()

否则,它只会询问一次,因为不会再次调用stutter()

在旁注中,您应该尝试理解数组以及字典,因为它们可以摆脱冗长的坐标检查列表。