Advertisement

Multiple Python Files Structure

Started by February 25, 2017 11:53 PM
3 comments, last by rip-off 8 years ago

hello,

I have a question on how to organise files in Python - I'm trying to build a text based game.

At present I have 3 .py files :

stuff.py (some global lists and some universal methods like "display inventory"

room1.py (starting point for the program (each room is basically a function in it's own file)

room2.py (function is called when player exits room 1)

all was going great with using import stuff, room2 into room1 - however when I then got to programming room2, and the facility to go back to room1 (thus requiring an import of room1.py to enable its function call - I get errors.

I think I'm more familiar with headers and function prototypes in there, which the source files can then define and be called from anywhere if they all import the header - I'm not sure how to setup a similar thing in python?

thanks

The work around is to put the imports that you're having trouble resolving into the function rather than at module level.


def foo():
  from room1 import bar
  bar()

That said, it sounds like you're implementing state in a really weird way and you may be inviting stack overflow if you try representing the current room by what function is currently executing.

Advertisement

You could introduce a 'world' file, that imports all rooms, and then calls one of them. When it is done, the room function returns, telling the world what to do next, like ("goto", "room2") or ("quit",)

This assumes every room has a unique name, but likely you have that already.

Thanks SiCrane, that has fixed the problem.

I suppose it is weird using functions for rooms, I did consider classes and the traditional game loop - I just find them too restrctive for the amount of content and possibilities I want to have in each room - most likely because I'm just a beginner though.

I'll have a look at using files Alberth, thanks

Maybe show us some of your room code? These restrictions can probably be dealt with by another mechanism.

This topic is closed to new replies.

Advertisement