pythonpygame

What exactly does pygame.init() do?


Every pygame tutorial I have ever read/seen have said to squeeze 'pygame.init()' into your code before you think about doing anything else. Apparently, it initializes pygame modules or something, which seems pretty important.

This was until I thought to remove the 'pygame.init()' line from my code, just to see what would happen. Lo and behold, my game works exactly the same.

I took to the web and once again, every where I went, I was told 'pygame.init()' is necessary. But no, it is clearly not, as I just took it out of my code which works just fine.

So, needless to say, I am pretty confused. I would really appreciate it if someone explained:

a) the function of pygame.init()

b) whether or not it is required in a pygame program. if it is, then why did my game work and if it is not, then when is it needed?

c) any other things you think I should know


Solution

  • From www.pygame.org

    pygame.init() initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init()initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.

    Furthemore, here we can see that it's safe to do it in the beginning:

    It is safe to call this init() more than once as repeated calls will have no effect. This is true even if you have pygame.quit() all the modules.

    And finally, the main reason in my opinion as for why it is always used in the beginning:

    This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do.

    So the main conclusion is that pygame.init() safely initializes all imported pygame modules regardless if the modules actually need to be initialized; but since it does for the ones that do, it saves the trouble of manually initializing each module individually.