我正在制作示例游戏。这是一个玩家输入内容的游戏,根据他们输入的内容,会发生新的事情。这是所有if-else语句,但我无法弄清楚如何在短语中搜索多个单词而不是为同一结果制作多个elif语句。
def room_1(key):
Key = "False"
if key == "True":
room1_choice = raw_input("Enter Command > ")
if "door" in room1_choice:
print "\nThe door lock clicks, and opens...\n"
first_hall()
elif "exit" in room1_choice:
print "\nThe door lock clicks, and opens...\n"
first_hall()
elif "leave" in room1_choice:
print "\nThe door lock clicks, and opens...\n"
first_hall()
elif "lamp" in room1_choice:
print "\nNot sure what you want to do involving a key and a lamp...\n"
room_1("True")
else:
print "\nUnknown command. This is not that hard...\n"
room_1("True")
elif key == "False":
room1_choice = raw_input("Enter Command > ")
suicide = ['suicide', 'hotline']
if "tape" in room1_choice:
print "\nAs you remove the tape, the lamp falls on the ground."
print "The bottom of the lamp breaks off revealing a key inside.\n"
tape_removed("first")
elif "shoot" in room1_choice:
print "\nNo firearm located. That is dangerous...\n"
room_1(Key)
elif "kick" in room1_choice:
print "\nYou attempt using violence, violence is never the answer.\n"
room_1(Key)
elif "lamp" in room1_choice:
print "\nThe lamp is held to the wall using tape...\n"
room_1(Key)
elif "door" in room1_choice:
print "\nThe door is locked.\n"
room_1(Key)
elif "your" in room1_choice:
print "\nSuicide is never the answer.\n"
room_1(Key)
elif any(suicide in s for s in room1_choice):
print "\nSuicide is never the answer.\n"
room_1(Key)
elif "kill" in room1_choice:
print "\nNo! Killing is bad...\n"
room_1(Key)
else:
print "\nUnknown command. Try something else.\n"
room_1(Key)
elif key == "ignore":
ignoring_key()
在第8行和第12行,我想将这两者合并为一个if语句。我尝试使用“任何”功能,但它仍然无法正常工作。非常感谢你!
答案 0 :(得分:2)
您使用any
功能:
if any(d in room1_choice for d in ['door', 'exit', 'leave']):
print "\nThe door lock clicks, and opens...\n"
first_hall()
答案 1 :(得分:2)
对于具有相同结果的条件,您可以使用set.intersection
,例如:
if set(['door', 'exit', 'leave']).intersection([room1_choice]):
print "\nThe door lock clicks, and opens...\n"
first_hall()