这是一个一直困扰我的问题。这些年来我多次重新制作了这个程序,但结果都是一样的;程序会忽略所有 if 语句。就好像它知道我正在尝试编写的程序并拒绝执行。
使用打印命令,位置设置准确。没有理由忽略它。这是我制作这个程序的最新尝试:
topLeft='topLeft'
top='top'
topRight='topRight'
midLeft='midLeft'
mid='mid'
midRight='midRight'
botLeft='botLeft'
bot='bot'
botRight='botRight'
location=mid
def printError():
print("You can't go that way!")
def topLeft():
userInput=input('You can go south or east.')
if userInput=='s':
location=midLeft
elif userInput=='e':
location=top
else:
printError()
def top():
userInput=input('You can go south, east, or west.')
if userInput=='s':
location=mid
elif userInput=='e':
location=topRight
elif userInput=='w':
location=topLeft
else:
printError()
def topRight():
userInput=input('You can go south or west.')
if userInput=='s':
location=midRight
elif userInput=='w':
location=top
else:
printError()
def midLeft():
userInput=input('You can go north, south or east.')
if userInput=='n':
location=topLeft
elif userInput=='s':
location=botLeft
elif userInput=='e':
location=mid
else:
printError()
def mid():
userInput=input('You can go north, south, east, and west.')
if userInput=='n':
location=top
elif userInput=='s':
location=bot
elif userInput=='e':
location=midRight
elif userInput=='w':
location=midLeft
else:
printError()
def midRight():
userInput=input('You can go north, south, west.')
if userInput=='n':
location=topRight
elif userInput=='s':
location=botRight
elif userInput=='w':
location=mid
else:
printError()
def botLeft():
userInput=input('You can go north or east.')
if userInput=='n':
location=midLeft
elif userInput=='e':
location=bot
else:
printError()
def bot():
userInput=input('You can go north, east, or west.')
if userInput=='n':
location=mid
elif userInput=='e':
location=botLeft
elif userInput=='w':
location=botRight
else:
printError()
def botRight():
userInput=input('You can go north or west.')
if userInput=='n':
location=midRight
elif userInput=='w':
location=bot
else:
printError()
while True:
print(location)
if location==topLeft:
topLeft()
elif location==top:
top()
elif location==topRight:
topRight()
elif location==midLeft:
midLeft()
elif location==mid:
mid()
elif location==midRight:
midRight()
elif location==botLeft:
botLeft()
elif location==bot:
bot()
elif location==botRight:
botRight()
希望代码是不言自明的。为什么这样的程序总是拒绝工作?没有其他这样的循环会忽略 if 语句。它在其他情况下也会这样做,但这是唯一具有模式的情况。我尝试制作一个基于文本的角色扮演游戏,但无论我做什么,它都会立即失败。为什么要这样做? while 循环不喜欢大量的 if 语句吗?即使选项只有两个,它甚至也会这样做。我是否触发了某种故障保护?这是怎么回事?
您将每个位置(顶部、中间等)定义为字符串和函数。函数定义稍后出现,因此优先。这意味着
while
循环中的每个条件都将失败,因为它们都试图将字符串与函数进行比较。
您必须重命名函数或字符串。我个人会选择这些函数,因为您可以查找并替换“top()”而不会弄乱太多,但这取决于您。