【发布时间】:2022-06-15 01:15:58
【问题描述】:
我对 Python 相当陌生,并且正在开发基于文本的游戏。我无法弄清楚如何为“get_item”创建函数。现在在运行代码时,当调用“get_item”函数时,位置和方向存储在“inventory”字典中。任何帮助将不胜感激。
import sys
# Dictionary of areas
rooms = {
'Main Street': {'North': 'Run Down Burger Shack', 'South': 'Strange Hut', 'East': 'Eerie House',
'West': 'Abandoned Motel'},
'Strange Hut': {'North': 'Main Street', 'East': 'Back Room', 'Item': 'Great Staff'},
'Back Room': {'West': 'Strange Hut', 'Item': 'Shield'},
'Abandoned Motel': {'East': 'Main Street', 'Item': 'Duct Tape'},
'Run Down Burger Shack': {'South': 'Main Street', 'East': 'Burned Down Car', 'Item': 'Mysterious Burger'},
'Burned Down Car': {'West': 'Run Down Burger Shack', 'Item': 'Sharp Metal Piece'},
'Eerie House': {'West': 'Main Street', 'North': 'Red Room', 'Item': 'Flashlight'},
'Red Room': {'South': 'Eerie House', 'Villain': 'Serial Killer'}
}
inventory = {}
# Starting location of the player
location = 'Main Street'
# No direction, will prompt for it
playerMove = ''
def get_item(playerMove):
for playerMove in rooms[location]:
rooms[location].pop('Item')
inventory.update(rooms[location])
return inventory
def playerinfo(location, inventory, rooms):
# Display current inventory and location
print('Inventory:', inventory)
print(f"You are at the : \033[1;31;40m{location}\033[1;32;40m")
# Introduction to the game
while True:
# Change the color of the text
print('\n\033[1;32;40mWelcome to the abandoned city of Winchester')
play = input('Would you like to explore? y/n: ').strip().capitalize()
# Branches to continue with game
if play == 'Y':
print('At any point in the game if you would like\n'
'to quit just type "exit" to exit the game')
print('Good luck and stay safe!\n')
break
elif play == 'N':
print("Good! You wouldn't survive anyway!")
sys.exit()
else:
print('Invalid input')
# Game Loop
while playerMove != 'Exit':
playerinfo(location, inventory, rooms)
# Shows the user possible inputs
choices = rooms[location].keys()
print("Possible Directions:", *choices)
# Ask for user input, strip away whitespace and capitalize input
playerMove = input("What would you like to do? ").strip().capitalize()
# Change color of text
print(f'You chose: \033[1;31;40m{playerMove}\033[1;32;40m\n')
# System exit if user inputs 'Exit'
if playerMove == 'Exit':
print('You exited the game')
sys.exit()
# Call function to retrieve item
if playerMove == 'Item':
get_item(playerMove)
# Call function to move between rooms
if playerMove in rooms[location]:
location = rooms[location][playerMove]
else:
print('Invalid movement command.')
【问题讨论】:
-
get_item应该做什么? -
get_item 应该在每个特定房间中检索一个项目并将其添加到用户的库存中,除了起始房间之外,然后到达最后一个房间与老板战斗。
标签: python