Pygame – Hello World
”;
First step is to import and initialize pygame modules with the help of init() function.
import pygame pygame.init()
We now set up Pygame display window of preferred size, and give it a caption.
screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Hello World")
This will render a game window which needs to be put in an infinite event loop. All event objects generated by user interactions such as mouse movement and click etc. are stored in an event queue. We shall terminate the event loop when pygame.QUIT is intercepted. This event is generated when user clicks the CLOSE button on the title bar.
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit()
Complete code for displaying Pygame window with Hello World caption is as follows −
import pygame, sys pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Hello World") while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
Save above script as hello.py and run to get following output −
This window will be closed only if the close (X) button is clicked.
”;