5

I were making a simple game in pygame and I realized I need a bunch of markers, counts and all sorts of global staff. So I decided to define a class and use it like this:

class Staff(): def __init__(self): self.modes={'menu':True,'spawning':False,'sprite_change':False} self.timer=pygame.time.Clock() self.tick_count=0 

and in my game loop I just give one variable to all my functions:

def main_loop(): staff=Staff() while not done: update_positions(staff) clear_background(staff) draw_sprites(staff) 

I know this method is working and quite convenient (for me), but I wonder how's this going to affect speed of my game, may be I'm doing something horrible? Many thanks for answering.

2 Answers 2

2

Please, do yourself a favour and rethink your design.

Firstly you might think that is easier for you to use global variables. You can pass around values and you can access them from every function without passing it to them using parameters. But when it comes to debugging or finding errors or just looking into your code after a while global variables are turning into a nightmare. Because you easily forget where these variables will take impact on other functions or classes. So, do yourself a favour and rethink your design.

A good place for your "global" variables could be for example the main class or function. Where it all begins. I guess there is a loop where some things will be repeated permanently. from there you can pass it to the specific classes or functions. I don't know your architecture, but it is seldom useful to have global variables at all.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for words of wisdom, I'll try to get rid of 'em.
If you're trying to optimize your code (e.g. time or memory space) there is one thing you should always do: Measurements. If there is no huge improvement then use the version that is more comprehensible!
1

While I don't know python at all, globals in general are a bad idea. I suggest the Singleton pattern. While it's not the greatest idea either, it's certainly better than globals: Python and the Singleton Pattern

Other than that, your approach seems fine to me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.