Pygame/GUI in Python

The original purpose of Python was to manage text input and output, including receiving and transmitting text to files, the user, and the internet. However, modern ideas like windows, mouse clicks, sounds, and visuals are not supported by the core Python language. A free and open-source external package called Pygame was created to enable Python to be used in the creation of interactive programs with graphical user interfaces, such as games. With the addition of functionality like window creation, image display, mouse movement and click recognition, sound playback, and more, Python programmers can now create programs that are recognisable to users of contemporary computers.
Pygame/GUI in Python is specifically utilised throughout the book to clarify and visualise some object-oriented programming (OOP) techniques. You may learn more about how to use OOP efficiently by using Pygame to make objects visible in a window and handling user interaction.
Creating a Pygame Application
There is a common procedure for making a Pygame/GUI in Python application, which frequently begins with a simple template. Even if Pygame is a big software, you don’t have to know everything to run a simple program. It include a 12-step structure that can be used as a foundation for any Pygame application. With the exception of the option to click the close button to end the session, this template opens a window and renders all of its contents dark.
Typically, pygame/GUI in Python applications loop continuously, looking for events. You may think of each pass through the main loop as a single animation frame.
The 12-step framework for writing Pygame programs is broken down here, along with an example of the code
Example:
# pygame demo 0 - window only
# 1 - Import packages
import pygame
from pygame.locals import *
import sys
# 2 - Define constants
BLACK = (0, 0, 0)
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
FRAMES_PER_SECOND = 30
# 3 - Initialize the world
pygame.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
clock = pygame.time.Clock()
# 4 - Load assets: image(s), sound(s), etc.
# 5 - Initialize variables
# 6 - Loop forever
while True:
# 7 - Check for and handle events
for event in pygame.event.get():
# Clicked the close button? Quit pygame and end the program
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 8 - Do any "per frame" actions
# 9 - Clear the window
window.fill(BLACK)
# 10 - Draw all window elements
# 11 - Update the window
pygame.display.update()
# 12 - Slow things down a bit
clock.tick(FRAMES_PER_SECOND)
Explanation of the Code Example
Import packages: The pygame package itself, constants from pygame.locals (declared inside pygame), and the sys package for program termination are all included in this section along with the required import lines.
Define constants: Here, you specify the parameters for your application, including the window’s width, height, and frame rate (FRAMES PER SECOND), as well as RGB values for colours (like BLACK). For clarity, colours are frequently defined as tuple constants (RGB values) up front.
Initialise the world: The Pygame environment is initialised in this section by calling pygame.init(). After that, you use pygame.display.set mode() to build the program’s window and pass in the required size. In order to help maintain the maximum frame rate at the conclusion of the main loop, you lastly build a clock object using pygame.time.Clock().
Load assets: This is a stand-in for loading external resources into memory, such as audio and pictures, from disc. This section is blank in the basic template. It is necessary to store images in external files (such as.png,.jpg, and.gif).
Initialise variables: This is a placeholder for setting up any variables that the application will employ. The basic template has it blank.
Loop forever: This initiates the while True infinite loop, which is the main loop. One frame is represented by each iteration.
Check for and handle events:The event loop is this. The code iterates through a list of events that have happened since the last check, which is retrieved using pygame.event.get(). Every event has a type attribute and is an object. This section is skipped if nothing happened. The pygame.QUIT event, which is produced when the user presses the close button, is checked for in the template. When this event is detected, sys.exit() is called to terminate the program and pygame.quit() is called to release resources. Pygame uses event-driven programming, which is distinct from standard text-based programs that might halt while awaiting input.
Do any “per frame” actions: A stand-in for code that must execute per frame, like collision detection or object movement.
Clear the window: The window is usually cleared, usually by filling it with a background colour, before creating the subsequent frame. window.fill(BLACK) applies black to the window.
Draw all window elements: Calls to draw forms, pictures, and other elements onto the window’s surface are contained in this section. In Pygame, drawing frequently takes place in an off-screen buffer. Examples include pygame and drawing images with blit().draw routines for lines, circles, and rectangles.
Update the window: pygame.display.update() (also known as pygame.display.flip()) allows the window to display everything that is drawn in the off-screen buffer.
Slow things down a bit:To make sure the application runs at a constant pace (the designated frame rate), regardless of the computer’s speed, clock.tick(FRAMES PER SECOND) pauses it.
Handling Events and Drawing
You include checks for event types other than quitting, like pygame, in the event loop (step 7).MOUSEBUTTONUP for keystrokes or mouse clicks. You might verify whether a mouse click falls inside a designated area, possibly established by a pygame.Pygame Rect object.Rect objects, which represent rectangular areas and provide practical properties and methods like collidepoint() for collision detection, are crucial in Pygame.
You can draw images at specific coordinates in the drawing section (step 10) by using functions like window.blit(image, position). Primitive forms can also be drawn using functions from the pygame.draw module. Since later elements are put on top of previous ones, the order in which calls are drawn important.
Moving Towards Object-Oriented Pygame
A rect object is an example of object-oriented code that is incorporated into Pygame, even though Chapter 5 mostly uses procedural code to illustrate the fundamentals of the game. Effective use of OOP methods in the Pygame framework is covered in detail in Chapter 6. In order to simplify the main program code, classes (such as a Ball class) are created to encapsulate data (position, speed, etc.) and behaviour (update, draw) linked to game objects.
Additionally, the OOP-built pygwidgets package offers implementations of common GUI widgets such as buttons, checkboxes, and text input/output fields, which facilitates the development of complete GUI apps and illustrates OOP ideas. As illustrations of creating reusable object-oriented GUI elements, widgets such as SimpleButton and SimpleText are presented. In order to use these widgets, you must first create instances of the widget classes, then call their handleEvent() method during the event loop, and then, at the end of the main loop, call their draw() method.
In conclusion, Pygame/GUI in Python is a crucial package for giving Python graphics capabilities so that interactive apps and games can be created. The 12-step template offers a methodical way to handle events, draw components, and create Pygame programs in a continuous loop. This framework successfully facilitates the introduction of OOP approaches for controlling game objects and GUI widgets, despite its initial procedural presentation.