我正在写一个糟糕的基于文本的冒险,我不知道如何打破这个循环。我试着把相关的东西贴在这里。如果我的评论没有充分解释我想做什么,请告诉我。
chained = 1
finished = 0
# home() and club() act as rooms in the game
def home():
while chained == 1:
# there's a way to unchain yourself that works
chained = 0
while chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
break
def club():
print "this works"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
current_room = 'home'
while finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()预期的行为是将“退出”或“离开”或“俱乐部”输入到输入中,home()函数将结束,club()函数将启动。实际上,终端一直在打印“您在房间里”,并一直给我输入。
如果必要的话,我会发布我的完全没有删节的代码,但我宁愿不这样做,因为实际的冒险并不是exactly...professional。
发布于 2013-08-22 04:42:35
虽然我从来没有真正理解这段代码的含义,但是这里的解决方案是有效的。您还没有说明变量是全局的还是局部的,以及为什么可以使用简单的 if -语句时使用循环?
chained = 0
finished = 0
# home() and club() act as rooms in the game
def home():
global chained,current_room
if chained == 1:
# there's a way to unchain yourself that works
chained = 0
if chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
club()
# Not sure if finished is a local or global variable
def club():
global finished,current_room
print "this is messy code!!"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
current_room = 'home'
if finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()
home()发布于 2013-08-22 04:25:26
break正在做的是突破home()函数中的循环。因此,当这种情况发生时,它会追溯到
while finished == 0:将继续重复这一输入。
您还必须在home() (和club())之后提供一个club():
while finished == 0:
if current_room == 'home':
home()
break
if current_room == 'club':
club()
break顺便说一句,您的代码非常混乱。虽然循环不应该用于这种情况(除非您试图获得exit或leave的输入)
你还不如去掉最后的while循环。
发布于 2013-08-22 04:35:13
我认为您需要使current_room成为一个全局变量。因为home()中的变量home()和while finished中的变量有不同的作用域。
以下是你想要达到的目标。查找python变量范围
chained = 1
finished = 0
current_room = 'home'
# home() and club() act as rooms in the game
def home():
global chained
# without the following line current_room has local scope and updating its value will not be
# reflected in the while at the end
global current_room
while chained == 1:
# there's a way to unchain yourself that works
chained = 0
while chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
break
def club():
print "this works"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
while finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()https://stackoverflow.com/questions/18371608
复制相似问题