I am currently working on a Pygame project and would like to seek your advice on best practices for organizing my code, particularly when it comes to creating additional scripts. I find myself indecisive with where to place certain functionalities, such as handling grid lines and GUI components. For example I created my Surface in main file (where the game loop is) and then made a separate file named grid.py with this code:

def draw_lines(screen: pg.Surface, scroll_x):
    screen.fill((255, 255, 255))

    for line in range(MAX_COL):
        pg.draw.line(screen, "black", (line * TILE_SIZE - scroll_x, 0),
         (line * TILE_SIZE - scroll_x, HEIGHT))
    for line in range(MAX_ROW):
        pg.draw.line(screen, "black", (0, line * TILE_SIZE), (WIDTH, line * TILE_SIZE))

then am calling this function every time I iterate through the game loop. (I also need to import this function into my main file)

What I find out about this approach is that am creating many files with usually just a few functions and I wonder if there is some more efficient and elegant way to handle this things. Im open to any suggestions!


1 Answer 1


Creating many files is not bad practice in personal projects. It allows you to keep your code easily maintainable. However I would recommend planning what is game stuff and what is engine stuff (in your case you said GUI components and grid lines). Thoroughly defining what each piece of code belongs to will give you a better idea on how to group them. Therefore you will know naturally when it's appropriate to create separate files.

Strictly my opinion that doesn't take into account what others say, I found out that from coding a lot that grouping things in classes tends to give me more understanding of how the code should look like in the future (for possible refactoring).

  • \$\begingroup\$ Thanks for the suggestion @Cherestes Radu, also would you recommend using classes even if it doesn't necessarily makes sense to implement them? E.g. they're used just once or have only one instance. I also think that the code is more readable but is it actually a good convention? \$\endgroup\$
    – anathrax
    Commented Nov 19, 2023 at 18:59
  • \$\begingroup\$ You're working on something personal, there are no guidelines, anything that makes it easier for you to code works! I found that making mistakes and learning from experience works best. For example you can read whole books about how to structure your code but if you've never shipped a finished product, advice from those books don't mean anything. You will never know how the code should look like if you don't write crappy code first. P.S. If you're feeling like one instance classes is overkill or you're acting like a smartass( I sometimes think of myself like that) then just ignore the thoughts \$\endgroup\$ Commented Nov 20, 2023 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .