需要帮助调整我的代码,我无法移动到其他房间,我只能向北和向南移动,没有其他房间被识别。目标是能够在房间之间来回走动。使用中的房间如下:阁楼、客厅、门厅、前廊、卧室、地下室、厨房、餐厅。
我想找出一种方法来解决当前代码,使其不循环,是否有我可以添加的语句,以便它可以在房间之间来回移动?我想尝试找出一种方法来保留此代码,而不会为了知识而对其进行过多更改。
设计模式如下:(从阁楼开始)
阁楼(开始)- 向南走到客厅
客厅 - 向西到餐厅,向北回到阁楼,向东到门厅
门厅 - 西到客厅,北到卧室,南到前廊
卧室 - 向南走到门厅
前廊 - 向北前往门厅
餐厅 - 向东到客厅,向北到厨房,向南到地下室
厨房 - 向南走到餐厅
地下室 - 向北走到餐厅
我的代码如下:
rooms = {
'Attic': {'South': ' Living Room'},
'Living Room': {'East': 'Foyer', 'West': 'Dining Room','North': 'Attic'},
'Foyer': {'North': 'Bedroom', 'South': 'Front Porch', 'West': 'Living Room'},
'Bedroom': {'South': 'Foyer'},
'Dining Room': {'East': 'Living Room', 'North': 'Kitchen', 'South': 'Basement'},
'Kitchen': {'South': 'Dining Room'},
'Basement': {'North': 'Dining Room'},
'Front Porch': {'North': 'Foyer'},
}
def possible_moves():
moves = rooms[location].keys()
print("Option:", *moves)
location = 'Attic'
Direction = ''
while True:
print('You are in the', location)
possible_moves()
direction = input("Which way would you like to go? ")
if direction == 'Exit' or Direction == 'exit':
print('Thank you for playing!')
break
elif direction == 'South' or direction == 'south':
location = 'Living Room'
print('You are in the', location)
possible_moves()
direction = input("Which way would you like to go? ")
if direction == 'East' or direction == 'east':
location = 'Foyer'
print('You are in the', location)
possible_moves()
direction = input("Which way would you like to go? ")
elif direction == 'North' or direction == 'north':
location = 'Attic'
print('You are in the', location)
possible_moves()
direction = input("Which way would you like to go? ")
else:
print('Invalid')
我想这应该做你想做的事:
ROOMS = {'Attic': {'South': 'Living Room'},
'Living Room': {'East': 'Foyer', 'West': 'Dining Room','North': 'Attic'},
'Foyer': {'North': 'Bedroom', 'South': 'Front Porch', 'West': 'Living Room'},
'Bedroom': {'South': 'Foyer'},
'Dining Room': {'East': 'Living Room', 'North': 'Kitchen', 'South': 'Basement'},
'Kitchen': {'South': 'Dining Room'},
'Basement': {'North': 'Dining Room'},
'Front Porch': {'North': 'Foyer'},
}
location = 'Attic'
while True:
print(f'You are in {location}')
print('Options:', *ROOMS[location].keys(), 'Exit') # print the possible moves
direction = input('Which way would you like to go? ').capitalize()
if direction == 'Exit':
break
try:
location = ROOMS[location][direction]
except KeyError:
print('Invalid')