Reputation:
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 !
Upvotes: 2
Views: 285
Reputation: 306
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
Upvotes: 3
Reputation: 319
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:
Upvotes: 2