需要帮助调整我的代码,我无法移动到其他房间,我只能向北和向南移动,没有其他房间被识别。目标是能够在房间之间来回走动。使用中的房间如下:阁楼、客厅、门厅、前廊、卧室、地下室、厨房、餐厅。
设计模式如下: (从阁楼开始)
阁楼(开始)- 向南走到客厅
客厅 - 向西到餐厅,向北回到阁楼,向东到门厅
门厅 - 西到客厅,北到卧室,南到前廊
卧室 - 向南走到门厅
前廊 - 向北前往门厅
餐厅 - 向东到客厅,向北到厨房,向南到地下室
厨房 - 向南走到餐厅
地下室 - 向北走到餐厅
我的代码如下:
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')
你的代码应该是这样的。我注意到 if 语句是不必要的。
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 = ", ".join(list(rooms[location].keys()))
print("Options: ", *moves)
location = 'Attic'
Direction = ''
while True:
print('You are in the ', location)
possible_moves()
direction = input("Which way would you like to go?\n>> ")
while direction.title() not in list(rooms[location].keys()):
direction = input('invalid direction\n>> ')
location = rooms[location][direction.title()]
紧凑而简单的解决方案。
如果你想要 if 语句,只需将
location == rooms[location][direction.title()]
替换为以下代码:
if direction.title() == "South":
location = rooms[location]["South"]
然后重复四次。