У меня проблема с получением ключа из значения словаря в мой класс. Пока я могу получить значения того, что хочу, но не могу также получить ключ, откуда они берутся. Я думаю, это из-за способа создания класса. Я просто передаю ключ в качестве аргумента, но я не могу сохранить ключ.
У этого проекта есть ограничения. Я не могу изменить способ, которым комнаты связаны друг с другом, или методы. Сейчас есть три файла, с которыми я работаю, чтобы попытаться решить эту проблему.
#I am using this to get the room set to the player
class Player:
def __init__(self, room, **kwargs):
self.room = room
self.key = str(kwargs)
def getRoom(self):
return self.room, self.key
, так что, как вы можете видеть, это простой класс. Я попытался использовать ** kwargs здесь, чтобы получить то, что передается, хотя я могу не понять, как это работает правильно и полностью. Я просмотрел документацию, но не могу найти ответ, который имеет для меня смысл. К остальным
#Again a simple class
class Room:
def __init__(self, name, desc):
self.name = name
self.desc = desc
Наконец, где происходит c магов:
from room import Room
from player import Player
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
'narrow': Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),
'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}
# Link rooms together
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']
def load_room():
return player.getRoom()
def update_room(room):
global player
player = Player([room])
print("\n*** Welcome to the room explorer")
print("*** You can enter 1, 2, 3, 4 to navigate the corresponding cardinal direction")
print("*** Select 9 to quit\n")
current_room = load_room()
print("this is current room: %s" % (player.key))
print("*** Choose a direction: ***")
user = int(input("[1] North [2] South [3] East [4] West [9] Quit\n"))
while not user == 9:
if user == 1:
if room[current_room.key[0]].n_to:
update_room(room[str(current_room[0])].n_to)
elif user == 2:
if room[current_room.key[0]].s_to:
update_room(room[str(current_room[0])].s_to)
elif user == 2:
if room[current_room.key[0]].e_to:
update_room(room[str(current_room[0])].e_to)
elif user == 2:
if room[current_room.key[0]].w_to:
update_room(room[str(current_room[0])].w_to)
else:
print("\nThere is dead-end, try again")
print(current_room)
print("Please choose to continue...")
user = int(input("[1] North [2] South [3] East [4] West [9] Quit\n"))
Я уверен, что есть кое-что, что я упускаю из виду. Logi c в while l oop изменится, как только я смогу получить доступ к имени ключа.