#๐Ÿ”’ Simple game leads to circular import error, i cannot figure out how to fix it .. :(

30 messages ยท Page 1 of 1 (latest)

rocky creekBOT
#

@deep shard

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

deep shard
#

Room code:

from rpg.inspectable import Inspectable
from rpg.door import Door


class Room(Inspectable):

    '''
    A class to represent a room in the RPG game.

    '''
    def __init__(self, description: str):
        '''
        Constructs all the necessary attributes for the room object.

        Parameters:
        ---------
        description : str
            A descriptive string that defines the room.

        '''
        self.description = description
        self.doors = []   # Empty list of doors in the room

    def inspect(self) -> None:
        '''
        Prints the description of the room

        This method outputs the room's descriptive text when called.
        '''
        print("You see: " + self.description)
        if len(self.doors) == 1:
            print(" There is 1 door in this room.")
        else:
            print(f" There are {len(self.doors)} doors in this room.")
            # Prints the number of doors in the insepcted room

    def add_door(self, new_door: Door) -> None:
        '''
        Adds a door to the room.

        Parameters:
        -----------
        door : Door
            A door object to be added to the room.
        '''
        self.doors.append(new_door)

    def list_doors(self):
        '''
        Prints all the doors in the current room for player to inspect.
        '''
        if len(self.doors) == 0:
            print("There are no doors in this room.")
        else:
            print("you see:")
            for i in range(len(self.doors)):
                print(f"({i}) {self.doors[i].description}")

#

Player code:

from rpg.room import Room


class Player:
    '''
    A class to represent a player in the RPG game.

    '''
    def __init__(self, name: str, current_room: Room):
        '''
        Constructs all the necessary attributes for the player object.

        Parameters:
        ---------
        name : str
            The name of the player.
        current_room : Room
            The room the player is currently in, this must be an instance
            of the Room class (relationship between objects).
        '''
        self.name = name
        self.current_room = current_room

    def change_room(self, new_room: Room):
        '''
        Change the player's current room.
        '''
        self.current_room = new_room
stable gust
#

Hey

deep shard
#

Heyyyy

stable gust
#

Circular imports happen when a file file A imports file B, while file B imports file A

deep shard
#

Ah oke, but in some cases it is needed right?

stable gust
#

You can usually avoid it pretty easily

deep shard
#

Because in this case I am trying to implement the following:
A Door should be connected to a Room behind it.
Add an interact() method to Door. When this method is called, the player should move to the Room behind that Door.
The Player should be an argument of the interact() method.
The interaction menu should be augmented with an option to select a Door to go through after looking around.

stable gust
#

I see in the room code, you're only importing door for typehinting, so just not importing door will fix your issue

deep shard
#

Alright, I just did, and now I get this error:

Traceback (most recent call last):
  File "c:\Users\huizi\OneDrive\Desktop\AI BSc\RPG Game OOP Course\oop-24-25-assignment-2-joel-stijn\main.py", line 1, in <module>
    from rpg.player import Player
  File "c:\Users\huizi\OneDrive\Desktop\AI BSc\RPG Game OOP Course\oop-24-25-assignment-2-joel-stijn\rpg\player.py", line 1, in <module>
    from rpg.room import Room
  File "c:\Users\huizi\OneDrive\Desktop\AI BSc\RPG Game OOP Course\oop-24-25-assignment-2-joel-stijn\rpg\room.py", line 4, in <module>
    class Room(Inspectable):
  File "c:\Users\huizi\OneDrive\Desktop\AI BSc\RPG Game OOP Course\oop-24-25-assignment-2-joel-stijn\rpg\room.py", line 36, in Room
    def add_door(self, new_door: Door) -> None:
                                 ^^^^
NameError: name 'Door' is not defined
stable gust
#

Change the typehint to "Door", or remove it

#

or you can import annotations from __future__ import annotations

deep shard
#

Btw, I am using every class using a simple test code called main.py:

from rpg.player import Player
from rpg.room import Room
from rpg.door import Door
from rpg.game import Game

# Create a room
living_room = Room("A rather dusty room full of computers.")
dungeon = Room("A huge chest.")
casa_joel = Room("despacito tu madre me la lame despacito")

# Create doors
to_dungeon = Door("A large wooden front door.", dungeon)
to_casa_joel = Door("A sliding glass door to Casa Joel.", casa_joel)

# Create the player
player = Player("Stijn", current_room=living_room)

# Add the doors to the room
living_room.add_door(to_dungeon)
living_room.add_door(to_casa_joel)

# Initiate the game with the player and start
game = Game(player)
game.start()

deep shard
#

no way i think it is fixed

#

but for OOP i need to give typehints for everything, how can I typehint without importing it? using both your methods gives me an error

#

i am still new with a lot of things sorry haha

#

i still really appreciate your time and help โค๏ธ

stable gust
deep shard
#

alrightt

stable gust
#

yeah it didn't work

#

I think just keeping the typehint a string should work
or import annotations and you can make it not a string
in either case you can't import Door in Room

deep shard
#

alright

#

it did fix the problem tho

#

so

stable gust
#

๐Ÿ‘

rocky creekBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.