我上个月在Python开始了一个高中计算机游戏编程课程,目前的项目是编写一个非常基本的文本冒险游戏。虽然我遇到了一些问题,但我还是通过阅读Python教程或阅读Stackoverflow上的过去问题找到了解决方案。但是,在过去的两天里,我一直无法解决这个问题。我一直试图将变量更改为输入,这通常可以无缝地工作。但是,在这种情况下,它似乎有一个相当短的内存,变量已被更改。也提前抱歉凌乱的代码以及在论坛上发布的任何错误;我是两个新手。
#actions for room one
def roomOne():
if adultDragon == "1": #later part of puzzle
print ("To be continued...") #change this later
elif clothes == "0" and bread == "0":
print ("You look around the room that you're in. It's very bare, with a tattered wood cabinet on the south wall right next to an opening that leads to the next room.")
time.sleep(3)
action = input ("You should probably find a way to get out of this cave. ") #should be saving variable??
while action != "go south" and action != "south" and action != "cabinet" and action != "open cabinet" and action != "door" and action != "open door":
action = input ("I don't understand. ")
#error here: as soon as input is equal to one of the options, it turns "action" into "look around" WHY? (Look around was a user input earlier in the script... but it should've been changed using the last user input)
#use a variable as a workaround? #it's remembering action from previous script... possible local/global issue? Trying different variable may work? (Edit: tried changing variable name eg. "actionOne" and result was the same. Last user input is not being stored.)
if action == "go south" and action == "south":
print ("You approach the wooden cabinet.")
elif action == "cabinet" and action == "open cabinet":
print ("You can't reach that from here. ")
elif action == "door" and action == "open door":
print ("You don't feel strong enough to leave the room yet. ")
roomOnePuzzle() #prompts for the room's puzzle
def roomOnePuzzle(): #Thinks action is what it was previously (see above)
print (action) #only for testing purposes to find out what it thinks "action" is at this point... appears to think it is the previous user input instead of current input.
我应该发布整个代码吗?以上是我认为与错误有关的1/3 ...因为你可以看到我还没有进入游戏的那么远。我讨厌寻求帮助,但我开始担心陷入僵局这么长时间,任务到期日快到了。
答案 0 :(得分:1)
怎么可能:
if action == "go south" and action == "south":
曾评估True
?相反,你需要:
if action == "go south" or action == "south":
# ^ note
或者更多Pythonic:
if action in ('go south', 'south'):
您也可以在循环中使用它:
while action not in ('go south', 'south', ...):
更好的是,使用字典:
actions = {'go south': "You approach the wooden cabinet.",
'south': "You approach the wooden cabinet.",
...}
action = input(...).lower()
while action not in actions:
action = input(...).lower()
print(actions[action]) # no need for if
room_one_puzzle(action) # note PEP-8 name and explicit argument
最后,不要依赖范围来访问您需要的值,重构显式参数和返回值;例如,clothes
和bread
可以位于传递给每个函数的inventory
字典中。