我正在写一个程序,这是一个小文本冒险游戏排序,但我似乎遇到了一些问题,我的代码。我是一个比较新的编程作为一个整体,所以如果你能解释你的答案深入将是很大的帮助。你知道吗
代码如下:
#text_adventure_game.py
#python_ver == 3.5
verbs = ["get",
"put",
"drop",
"use",
"enter",
"leave",
"walk",
"search",
"attack",
"defend"]
nouns = ["journal",
"magnifier",
"glasses",
"knife",
"kite",
"table",
"chair",
"key"]
inventory = ""
user_input = input("What would you like to do?\n")
#checking if there are a set of two instructions
if(len(user_input.split())==2):
counter = 0
for token in user_input.split():
print(token)
print(counter)
if(counter==0):
if(token not in verbs):
print("I did not understand the verb entered.")
#removing square brackets and single quote marks from the array
print("Please use:", ", ".join(verbs))
counter = counter + 1
elif(token in verbs):
print("Recognized verb entered.")
counter = counter + 1
if(counter==1):
if(token not in nouns):
print("I did not understand the noun entered.")
print("Please use:", ", ".join(nouns))
counter = counter + 1
elif(token in nouns):
print("Recognized verb entered.")
counter = counter + 1
我的问题是它无法识别我在“nomnes”数组中输入的名词。你知道吗
它是这样编译的:
>>>
What would you like to do?
get journal
get
0
Recognized verb entered.
I did not understand the noun entered.
Please use: journal, magnifier, glasses, knife, kite, table, chair, key
journal
2
如果有更有效的方法来做这样的事情,那也会有帮助。你知道吗
谢谢。你知道吗
不需要
for
循环和计数器。您可以更简单地执行以下操作:如果您想在失败后重复,可以将代码放在
while
块下。你知道吗不管怎样,原始代码中的问题是,如果第一个动词正确,则必须插入continue:
当您找到动词时,您将递增计数器,因此在递增标记之前执行if(counter==1)行(当counter==1块执行时,标记仍然包含“get”)。你知道吗
最简单的解决办法就是
变成elif:
或者,如果您希望友好而明确,您可以在每次成功处理令牌时添加一个“continue”,循环将进入下一次迭代,而不再处理循环体:
(注意,我还更改了if/elif测试,因为您正在测试两个互斥的布尔条件-“in”和“not in”。)
希望有帮助。你知道吗
问题是在“if(counter==0)”中增加计数器变量 从0到1。因为后面还有另一个if语句(“if(counter==1):”),两个if语句都将在同一个迭代中执行,这意味着输入“get key”时,您将检查“get”是否在动词中,也检查“get”是否在名词中。我建议把第二个if改成这样的elif:
相关问题 更多 >
编程相关推荐