In this PyGame lesson we want to talk about Creating an Empty PyGame Window, so first of all let’s talk about PyGame.
What is Pygame ?
Pygame is cross platform set of Python modules, You can use PyGame for writing video games in Python programming language. PyGame provides different functionalities for creating 2D games with graphics, sound and user input. Pygame is built on top of the SDL (Simple DirectMedia Layer) library, SDL provides low level access to audio, keyboard, mouse, joystick and graphics hardware. it means that you can run PyGame games in multiple platforms like Windows, macOS, Linux and Raspberry Pi. Pygame provides different features for game development, including support for image and sound loading and playback, sprite animation, input handling and game loop management.
How to Install Pygame?
You can install PyGame using pip, open your command prompt or terminal and write this command.
1 |
pip install pygame |
Creating an Empty PyGame Window
Now let’s create our empty window using PyGame, For creating an empty PyGame window you need to import pygame library and initialize its video system using pygame.init() function. after that you can create display surface using pygame.display.set_mode() function and set the title of the window using pygame.display.set_caption() function. and at the end you will need to create game loop to keep the window open until you close it.
This is an example of how to create an empty PyGame 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 |
import pygame # initialize pygame library pygame.init() # set window size window_size = (800, 600) # create window screen = pygame.display.set_mode(window_size) # set title of the window pygame.display.set_caption("Codeloop.org - Empty Window") # run the game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # update the display pygame.display.update() # quit pygame pygame.quit() |
In this example, pygame.init() function is used to initialize pygame library and pygame.display.set_mode() function is used to create window with size of 800×600 pixels. pygame.display.set_caption() function is used to set title of the window.
The game loop checks for the QUIT event, and it is used when the user closes the window, pygame.display.update() function is called at the end of each iteration of the loop to update the display. and lastly pygame.quit() function is called to quit pygame library and clean up its resources when the loop is finished.
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email