【发布时间】:2021-10-15 21:05:13
【问题描述】:
对于我的第一个脚本项目,我必须创建一个基于文本的游戏,但我无法将我的游戏循环转换为函数(这是必需的)。我们假设在函数中包含我们的字典并将其命名为def main():。如果我的其他两个函数和它的变量出现错误,我无法弄清楚如何在我的一生中做到这一点。我在下面提供了我的工作代码。感谢您的帮助(python 的铁杆新手)!
def show_instructions():
print('\nWelcome to Cat and Mouse Adventure Game!\n')
print('Collect all 7 items to win the game, or else get eaten by the cat!')
print('Move commands: go North, go South, go East, go West')
print('Add item to Inventory: get \'item name\' ')
def player_stats():
print('_' * 20)
print('You are in the {}'.format(current_room))
print('Inventory: ' + str(inventory))
if 'item' in rooms[current_room]:
print('You see ' + rooms[current_room]['item'])
print('_' * 20)
rooms = {
'Living Room': {'South': 'Study', 'North': 'Kitchen', 'East': 'Bedroom', 'West': 'Bathroom'},
'Bedroom': {'North': 'Dining Room', 'West': 'Living Room', 'South': 'Sunroom', 'item': 'Glasses'},
'Dining Room': {'West': 'Kitchen', 'South': 'Bedroom', 'item': 'Napkin'},
'Kitchen': {'South': 'Living Room', 'East': 'Dining Room', 'West': 'Basement', 'item': 'Cheese'},
'Basement': {'East': 'Kitchen', 'South': 'Bathroom', 'item': 'Catnip'},
'Bathroom': {'East': 'Living Room', 'North': 'Basement', 'South': 'Walk-in Closet', 'item': 'Water'},
'Walk-in Closet': {'North': 'Bathroom', 'East': 'Study', 'item': 'Shoes'},
'Study': {'North': 'Living Room', 'East': 'Sunroom', 'West': 'Walk-in Closet', 'item': 'Cotton'},
'Sunroom': {'North': 'Bedroom', 'West': 'Study', 'item': 'Cat'} # villian room
}
current_room = 'Living Room'
inventory = []
show_instructions()
while True:
player_stats()
player_move = ''
while player_move == '':
player_move = input('Enter your move:\n').title()
if player_move == 'Go North' or player_move == 'Go South' or player_move == 'Go East' or player_move == 'Go West':
player_move = player_move[3:]
if player_move not in rooms[current_room]:
print('That is not a valid move, enter another.')
else:
current_room = rooms[current_room][player_move]
elif player_move[0:3] == 'Get':
if 'item' not in rooms[current_room] or player_move[4:] not in rooms[current_room]['item']:
print('Can\'t get {}!'.format(player_move[4:]))
else:
inventory += [player_move[4:]]
print(player_move[4:] + ' retrieved!')
del rooms[current_room]['item']
if current_room == 'Sunroom':
print('OH NO! The cat found you and ate you up!')
print('GAME OVER!')
exit(0)
if len(inventory) == 7:
print('\nCongratulations! You collected all 7 items to build a shelter and avoid the cat!')
exit(0)
if player_move == 'Exit':
print('Play again soon!')
exit(0)
【问题讨论】:
标签: python loops dictionary