0

I am making an escape room text adventure game and for each instance of my Room class I have a dictionary containing instances of my Door class. The class looks like this:

class Door:
  def __init__(self, to, open=False):
    self.to = to
    self.open = open

The to variable references another instance of my Room class. I cannot for the life of me figure out how to define the rooms whilst referencing other ones in the doors. For example, there is a door that goes from room A to room B and is defined in each of the rooms doors (the door in A has a .to of class B and vice versa). But I can't give the door in room A a .to of room B as it isn't defined yet. The same goes the other way around. Is there a way to do this that i'm not seeing?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Maybe have the constructor for Door take as arguments two previously-constructed rooms? – Mark Lavin Aug 23 '21 at 15:48
  • 2
    As you suspect, there is no way to simultaneously have all three instances (representing room A, room B and the door), all have the necessary references at initialization time. There is necessarily one instance that will need to be initialized first, before either of the other instances are initialized. The solution is either to 1) make your class associations unidirectional (a door points to a room, but a room does not point to a door, or vice-versa) or 2) omit a reference for the constructor of one of the classes, and set it after initialization with a setter (it will be `None` initially). – zr0gravity7 Aug 23 '21 at 15:48
  • Why are there two doors between rooms A and B? – wjandrea Aug 23 '21 at 19:17
  • 1
    @zr0gravity7 Please don't post answers in the comments, post an answer instead. I'd upvote :) – wjandrea Aug 23 '21 at 19:18
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Aug 23 '21 at 19:18
  • 1
    Related, possibly duplicates: [How to instantiate classes that depend on each other?](/q/44884497/4518341), [instantiating two classes with references to each other](/q/43643734/4518341) – wjandrea Aug 23 '21 at 19:25

0 Answers0