我是一個初學者,試圖撰寫一個簡單的基于文本的游戲,其中用戶在不同的房間之間移動,從每個房間拿起一個專案,并以遇到 Boss 結束。事情似乎進展順利,除非我嘗試在主函式中呼叫函式 status()。我不斷收到未定義變數的錯誤。任何幫助將不勝感激。
# Create a function for the opening menu
def show_menu():
print('You are about to play a text based game.\n')
print('The goal of the game is to collect all seven items before encountering the ghost.\n')
print('These items contain information about the ghost that can finally put them to rest.\n')
print('If you approach the ghost without all of the items you will be possessed and the game will end.\n')
print('The commands are: move North, move South, move East, move West, menu, and quit.\n')
print('When you find an item, to add it to your inventory enter: get Item')
# Create a function that outputs current room, current room inventory and users current inventory
def status():
print('You are currently in the: {}.'.format(current_room))
print('The item currently in this room is {}.'.format(rooms[current_room]['item]']))
print('Your current inventory is: {}.'.format(inventory))
control = input('What would you like to do? move North, move South, move East, move West, menu, or quit.')
return control
def movement_error():
print('You look around and realize that you wanted to move through a wall, try a different direction.')
control = input('What would you like to do? move North, move South, move East, move West, menu, or quit.')
return control
def main():
# Create Dictionary linking rooms and items
rooms = {
'Foyer': {'East': 'Office', 'South': 'Cafeteria', 'item': 'Newspaper Article'},
'Office': {'West': 'Foyer', 'item': 'Student Report'},
'Cafeteria': {'North': 'Foyer', 'West': 'English Classroom', 'South': 'Math Classroom', 'East': 'Band Room',
'item': 'Crumpled Paper'},
'English Classroom': {'East': 'Cafeteria', 'item': 'Student Journal'},
'Math Classroom': {'East': 'Girls Bathroom', 'item': 'Itinerary'},
'Girls Bathroom': {'West': 'Math Classroom', 'item': 'Notebook'},
'Band Room': {'East': 'Cafeteria', 'North': 'Basement', 'item': 'Picture'},
'Basement': {'South': 'Band Room'}, # Ghost Room
}
directions = ['North', 'East', 'South', 'West']
control = ''
current_room = 'Foyer'
while control != 'exit':
inventory = []
while current_room != ['Basement']:
status()
if control in directions and contol in current_room:
current_room = rooms[current_room][control]
uj5u.com熱心網友回復:
這些名稱僅在main. 將它們傳遞給您的函式:
def status(rooms, current_room, inventory):
# ...
使用:
control = status(rooms, current_room, inventory)
注意對 的賦值control。目前,您的status函式回傳的值未使用。
uj5u.com熱心網友回復:
您還可以像global在主函式中一樣宣告變數:
def main():
global current_room
global inventory
global rooms
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377458.html
