2

I have another issue. When I try to to run my code, pygame launches and then stops immediately.

Here's my code :

import pygame
import os 
import time 
import random

pygame.init()
pygame.font.init()




def main():

    clock = pygame.time.Clock()

    win = pygame.display.set_mode((Win_Width, Win_Height))

    run = True
    while run:

        clock.tick(40)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

Thank you to help me. Bye !

3 Answers3

3

Your pygame loop is contained within the method main. But main is never called anywhere. Consider adding the following block to the very bottom of your file

if __name__ == "__main__":
  main()

this block is basically just checking if you are calling this file directly, and if so, calling your main method.

Core taxxe's answer does a great job explaining this functionality of python in greater detail

Bitsplease
  • 306
  • 2
  • 12
2

Unfortunately I'm not allowed to comment yet, though I will answer your question this way.

Before executing code, the Python interpreter reads a source file and defines a few special variables/global variables. If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “main”. If this file is being imported from another module, __name__ will be set to the imported module’s name. The module’s name is available as the value of the __name__ global variable.

In your case you could run your code either with an if etc. or with a direct main() call.

print "Always executed"

if __name__ == "__main__": 
    print "Executed when invoked directly"
else: 
    print "Executed when imported"

I hope that was understandable and helpful. For further information here are a few sources:

Kingsley
  • 14,398
  • 5
  • 31
  • 53
Core taxxe
  • 299
  • 2
  • 12
0

you need to call main()

so :

if __name__ == "__main__": main()