python - Python代码函数没有正确更新变量
问题描述
我正在尝试首先制作一个简单的基于文本的基于房间的游戏,您可以在其中从一个房间走到另一个房间,它会为您提供描述,您可以四处走动。1 次输入后,输出相应地工作。在它要求您再次输入并且您输入方向后,程序什么也不做。我已经在代码前面定义了每个不同的房间 1、房间 2 等。我认为这与我的方向函数和 xy 变量有关,但我不完全确定问题出在哪里
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()
解决方案
你必须引入这样的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()
不会再次调用。
在旁注中,您应该尝试理解数组,也许还有字典,因为它们可以摆脱那长长的坐标检查列表。
推荐阅读
- rust - 别名具有生命周期的通用函数?
- sql - 加入两个查询以形成一个表 - 在 postgres
- typescript - 定义具有准确类型的对象数组
- python - Keras 权重平均
- python - 为什么下面的python代码会抛出内存错误?
- spring-boot - ClassNotFoundException:使用 MockRestServiceServer 时出现 org.junit.Assert 异常
- alexa - 如何将输入传递给handle()以及如何在alexa SDK V2 for Java中调用LaunchRequestHandler的handle()?
- css - 过渡延迟不适用于元素(:之前)CSS
- sql - 将 varchar 列转换为日期时间
- swift - 在 Series 4 上访问苹果跌倒检测