我正在写一个糟糕的基于文本的冒险,我无法弄清楚如何打破这个循环。我会尝试在这里发布相关的东西。如果我的评论没有充分解释我正在尝试做什么,请告诉我。
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()函数将启动。实际发生的是,终端只是继续打印“你在房间里”,并不断给我输入。
如果必须,我会发布完全未删节的代码,但我不愿意,因为实际的冒险并不完全......专业。
答案 0 :(得分:4)
break
正在做的是突破home()
函数中的循环。所以当它破裂时,它会回到
while finished == 0:
并将继续重复该输入。
您必须在break
(和home()
)之后提供club()
:
while finished == 0:
if current_room == 'home':
home()
break
if current_room == 'club':
club()
break
顺便说一句,你的代码非常混乱。虽然循环不应该用于这样的事情(除非您尝试获取exit
或leave
的输入)
你也可以摆脱最后的循环。
答案 1 :(得分:0)
我认为您需要将current_room
作为全局变量。因为current_room
中的变量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()
答案 2 :(得分:0)
虽然我从来没有真正理解代码对于这个有效的解决方案的意义。您还没有说明变量是全局变量还是本地变量,为什么在使用简单的 if-else 语句时会使用循环
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()