我在一个初级编程班上是个python新手,我被一个作业困住了。我应该创建一个文本游戏的最基本的开始,在这个游戏中我可以在房间里移动。我已经设法让移动工作了,但是“无效命令”和“退出游戏”命令不起作用。
rooms = {
'Foyer': {'name': 'Foyer', 'South': 'Dining Hall', 'North': 'Hallway', 'West': 'Courtyard', 'East': 'Grand Hall'},
'Dining Hall': {'name': 'Dining Hall', 'South': 'Servants Quarters', 'East': 'Kitchen', 'North': 'Foyer',
'West': 'Drawing Room'},
'Servants Quarters': {'name': 'Servants Quarters', 'North': 'Dining Hall'},
'Drawing Room': {'name': 'Drawing Room', 'East': 'Dining Hall'},
'Kitchen': {'name': 'Kitchen', 'West': 'Dining Hall'},
'Courtyard': {'name': 'Courtyard', 'East': 'Foyer'},
'Grand Hall': {'name': 'Grand Hall'},
'Hallway': {'name': 'Hallway', 'South': 'Foyer', 'East': 'Private Library'},
'Private Library': {'name': 'Private Library', 'West': 'Hallway', 'East': 'Master Bedroom'},
'Master Bedroom': {'name': 'Master Bedroom', 'West': 'Private Library'}
}
directions = ['North', 'South', 'East', 'West']
player_room = rooms['Foyer']
# turn below into definition that can be called on later
while True:
print()
print('You have entered the {}.'.format(player_room['name']))
command = input('\nEnter a direction: North, South, East, or West')
if command in directions:
if command in player_room:
player_room = rooms[player_room[command]]
else:
print("You face a wall. There is no doorway here.")
elif command == "Exit" or "exit":
print("Play again soon.")
break
else:
print("Type a cardinal direction to move. Directions are case-sensitive.")
这是我目前为止的代码。每当我测试输入一个无效命令时,比如一个数字或一个随机单词,它只会给我一个“退出”文本并结束程序。我认为问题出在命令的顺序上,所以我把它们交换了一下,并对语句进行了一些混乱。但是,即使我键入“退出”,它也会反复给予我错误文本。我如何阻止一个总是优先于另一个?
2条答案
按热度按时间mzillmmw1#
改变你的elif如下
ibps3vxo2#
问题出在
elif
语句中的条件上:command == "Exit" or "exit"
。它实际上总是计算为True,因为字符串"exit"
总是被认为是真值。您可以通过将条件更改为
command == "Exit" or command == "exit"
来解决此问题。这样,只有当输入为"Exit"
或"exit"
时,条件才为True。您还可以将命令存储在列表中,并使用
lower()
方法将用户输入转换为小写,使其不区分大小写。