【发布时间】:2022-01-10 20:33:17
【问题描述】:
我的代码如下:
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
def show_instructions():
print('The instructions are as follows: go north, go south, go east, go west')
def move_rooms(direction, room='Great Hall'):
if direction == 'go south':
room = 'Bedroom'
return rooms[room]['South']
elif direction == 'go north':
if room == 'Great Hall' or 'Cellar':
return 'Invalid direction please try again.'
return rooms[room]['North']
elif direction == 'go east':
if room == 'Great Hall' or 'Cellar':
return 'Invalid direction please try again.'
return rooms[room]['East']
elif direction == 'go west':
if room == 'Bedroom' or 'Great Hall':
return 'Invalid direction please try again.'
return rooms[room]['West']
currentRoom = 'Great Hall'
gameInstructions = 'The instructions are as follows: go north, go south, go east, go west'
print(gameInstructions)
print(currentRoom)
userDirection = ''
while userDirection != 'exit':
userDirection = input("Pick a direction, or type exit to exit the game.")
if currentRoom == 'Great Hall':
if userDirection == 'go south':
currentRoom = move_rooms(userDirection, currentRoom)
show_instructions()
print(currentRoom)
else:
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
elif currentRoom == 'Bedroom':
if userDirection != 'go north' or 'go east':
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
elif userDirection == 'go north':
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
elif userDirection == 'go east':
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
elif 'Cellar' == currentRoom:
if userDirection != 'go west':
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
else:
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
else:
if userDirection == 'exit':
print('Thanks for playing the game!')
break
这是一个大型文本游戏的一小部分,我应该在大学课堂上开发它。该程序的目标是让用户输入在房间之间移动。我使用了给定的模板字典,并试图限制指令列表的输入,但单词“exit”除外。所以我遇到的主要问题是如何在我创建的函数中正确使用返回函数以产生正确的结果。 每次我尝试输入向南作为第一个方向时,它都会在控制台中给我一个“南”的“KeyError”。任何帮助将不胜感激。
【问题讨论】:
-
看起来像你的同学already asked ;)
标签: python loops dictionary if-statement