Ex24 - Composition?

Hi Zed, I just want to share a code refactoring of ex24 that helped me to understand a bit more what was going on with this method of the Game class:

addRoom(room) {
        this[room.name] = room;
        room.game = this;
    }

Basically a need a way to access the properties and methods of a Room instance from an instance of the Game class and viceversa.

Is this correct? Is this the concept of “Composition” that you talked about on the book Learn Python The Hard Way?

Thanks

Stefano

class Game {
    constructor() {
        this.hp = Math.floor(Math.random() * 10) + 1;
        
        // How can I access the properties and methods of a Room instance from an instance of the Game class?
        this.well = new Well("well");
        this.gold = new Gold("gold");
        this.spider = new Spider("spider");
        this.door = new Door("door");
        this.rope = new Rope("rope");

        // How can I access the properties and methods of the Game class fron an instance of the Room class?
        this.well.game = this;
        this.gold.game = this;
        this.spider.game = this;
        this.door.game = this;
        this.rope.game = this;        

    }
}

Yeah, you can do it that way, and in some ways it’s better since you are restricting what can happen. We call this “white listing” the allowed things. Eventually though this will become annoying as you add rooms.

Also, I believe in the video I go through and refactor this code quite a lot as it’s not optimal. It’s kind of “trashy” on purpose and then I show you how to refactor it in the video. Check it out.