In this Pygame article we want to learn about Pygame Init: Getting Started with Pygame, Pygame is popular Python module that is used for game development. it is an open source module that provides easy functions for game development, graphics, sound and event handling. Pygame is cross platform and can be used on Windows, macOS and Linux.
First of all we need to install pygame library and we can use pip for that
1 |
pip install pygame |
For using Pygame, we need to initialize Pygame module. this is done by calling pygame.init() function. this function initializes all the Pygame modules and prepares them for use.
1 2 3 |
import pygame pygame.init() |
After that first thing we want to do is creating Pygame window. this is done by calling pygame.display.set_mode() function. this function takes two arguments, width and height of the window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import pygame pygame.init() # Set width and height of screen screen_size = (640, 480) screen = pygame.display.set_mode(screen_size) # Set title of the window pygame.display.set_caption("GeeksCoders.com - Pygame Window") # Run game loop running = True while running: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Fill background with white screen.fill((255, 255, 255)) # Draw here # Update the screen pygame.display.flip() # Quit the game pygame.quit() |
In the above code we have created Pygame window with a size of 640 by 480 pixels. we set the title of the window. we have also created a game loop that will run until the user closes the window. inside game loop we handle events using pygame.event.get() function. we fill background of the window with white using screen.fill() function. we have also updated the screen using pygame.display.flip() function.
Run the complete code and this will be the result