Pygame Theory of Operation

Pygame Theory

Pygame module has several modules and associated methods. The details of modules, functions, the concept of Pygame Surface, and Color Theory are presented.

Concept of Surface in Pygame

What is a Surface in Pygame?

Think of the Surface as paper.  In pygame apps, Surface is used to draw lines and shapes just like you would do it on paper. When you write an app or write a game using pygame, Surface is your app’s or game’s main display. This is the display on which you write text, draw shapes, fill shapes with color, load images, and copy images from or to it. You can rotate and scale the images, and manipulate the pixels of an image on the Surface.

The surface is similar to Canvas we used in the tkinter chapter. Pygame represents images as Surface Objects. The Surface in Pygame is an object.

The following are a few methods we will use in the next program.

How Do We Create a Surface in Pygame

Pygame has method pygame.display.set_mode().You create a surface by calling pygame.display.set_mode() method.

How to Load an Image on a Surface:

The pygame.image module has a load() function. You can load images on the Surface by using pygame.image.load() function.

How to Create a Surface with Text on It

Pygame has a method font.render(). To create a Surface that has text on it, you can do it with the font.render()method.

How to Create a Blank Surface()

The surface () command will give you a  blank Surface with nothing on it. The program in the next sections explains how to add images on the blank surface.

>>> surface()

We will cover the Pygame theory of operation in the section below. Befire we do that, let us introduce how computers display colors.

How Does Computer Display Colors

Your computer uses three primary colors, RED (R), GREEN (G), and BLUE (B). If you mix equal amounts of RED, GREEN, and BLUE colors, you get the WHITE color.

If you mix different amounts of RED, GREEN, and BLUE colors, you get different colors. This is how the computer generates various colors you see on your computer screen. Each pixel on the display is mixed with different amounts of RED, GREEN, and BLUE colors to get the desired color.

RGB Tuple

In the computer memory, each of the three primary colors, R, G, and B are represented by one byte (8 bits).  As explained in the binary numbering system in Appendix, an 8-bit number is equivalent to 2**8 decimal, which is equal to 256 combinations.  These RGB combinations are numbered from 0 to 255 (2**8).

The “R” ,(RED) in the RGB tuple represents 2**8 = 256 values (shades) of RED color – 0 for no RED color, 1 for slightly more RED color, and so on, with 255 representing the maximum RED color.

The “G” (GREEN) in the RGB tuple represents 2**8 = 256 values (shades) of GREEN color – 0 for no GREEN color, 1 for slightly more GREEN color, and so on, with 255 representing the max GREEN color.

The “B” (BLUE) in the RGB tuple represents 2**8 = 256 values (shades) of BLUE color – 0 for no BLUE color, 1 for the slightly more BLUE color, and so on, with 255 representing the max BLUE color.

The computer can mix different quantities of each of the RED, GREEN, and BLUE colors (from 0 to 255) to make a pixel color. 

Thus, the computer can generate a total of 256*256*256 = 16,777,216 different colors, that is about 16 million colors.  This means any pixel on your screen can be one of 16 million colors.

The pixel color is represented as an RGB tuple of three integers.

The red color is represented by a tuple (255, 0, 0). 

The green color is represented by a tuple (0, 255, 0).

The blue color is represented by the tuple (0, 0, 255). 

If all integers of the tuple are zero (0, 0, 0), the black color is created.

The black color is represented by the tuple (0, 0, 0).

White color is represented by the tuple (255, 255, 255).

Note: Tuples were discussed on the Python Data Types page.

The table below lists a few colors with corresponding RGB values. combinations of a few colors.

Pygame: Color R, G, B Values

COLORR,G,B VALUE
Black(  0,   0,   0)
White(255, 255, 255)
Red(255,   0,   0)
Green(  0, 255,   0)
Blue(  0,   0, 255)
Yellow(255, 255,   0)
Cyan(0,  255,  255)
Magenta(255,  0,  255)
Gray(127, 127, 127)
Purple(127,   0, 127)
RGB Color Values for a Few Colors
Pygame Mixing different amounts of R, G, b colors can produce 16 million colors
Pygame Color Mix

In the above figure, if we mix RED and GREEN in equal amounts, we get YELLOW color.  If we mix RED and BLUE in equal amounts, we get a Magenta color. And if we mix GREEN and BLUE in equal amounts, we get CYAN color.  If we mix RED, GREEN, and BLUE in equal amounts, then we get WHITE color.

We will explain the theory of operations of pygame later afer we have introduced the the concepts through on this page through a real program to display an image.

How to Display an Image

Now we will write an actual program to display an image. This will help in explaining the pygame’s basic concepts.

When pygame is imported, it imports all the modules belonging to pygame.   Pygame module contains a display module called pygame.display.  The pygame.display module has a method associated with it called load() that can load an image file from your computer memory to the Surface

We will use the display module pygame.display and load() method in the program “Display an Image” to load an image.

In our first pygame program, we will write a simple program to display the image of a soccer ball on the screen. We will explain what each line of the code does. 

Note that the image file you want to load must reside in the same folder where your program resides.

Below is the program.

PROGRAM EXAMPLE: DISPLAY AN IMAGE

Program: pygame_ball_display.py        

Image: ball.png

import pygame					# 1)
from pygame.locals import *			#1a)
pygame.init()					# 2)
#
screen = pygame.display.set_mode((200, 200))	# 3)
BLACK = (0, 0, 0)				# 4)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#
pygame.display.set_caption('BallDisplay')	# 5)
#
clock = pygame.time.Clock()			# 6)
#
ballImage = pygame.image.load('ball.png')	# 7)
#
x = 50						# 8)
y = 50

def ball(x, y):
    screen.blit(ballImage, (x, y))		# 9)
    
#Main Loop					# 10)
while True:
    screen.fill(WHITE)				# 11)
    ball(x, y)					# 12)
    pygame.display.update()			# 13)
    clock.tick(60)				# 14)

pygame.quit()					# 15)
quit()

Detailed Line-by-line Explanation of the Program:

  1. import pygame and 1a) from pygame.locals import *
    • The first step in any pygame program is to import the pygame module so our program can use the modules and functions in it.
  2. pygame.init()
    • After we import the pygame module, we make a function call pygame.init(). This is a necessary step that will initialize the Pygame module, and allow you to use the various Pygame modules.
  3. screen = pygame.display.set_mode((200, 200))
    • This statement defines our main display (called Surface). This is analogous to “Canvas” in Tkinter. The program will draw the image on this surface. This statement names it “screen”.  You can choose any name you like.
    • The argument (200, 200) is a tuple and defines the width of the surface as 200 pixels wide and 200 pixels high.
    • Learn more about pygame.display.set_mode((200, 200)) in a later section.
  4. In this step, we define the RGB values of three colors, BLACK, WHITE, and RED.  The numbers in parenthesis such as (255, 0, 0) is a tuple.
  5. pygame.display.set_caption()
    • It is nice to give our display a name.  We use the set_caption() method to give a name to our Surface window. In this example, we define our display’s caption as “ballDisplay”.  The name “ballDisplay” will appear at the top of the Surface window.
    • The set_caption() method is discussed in a later section.
  6. clock = pygame.time.Clock() function provides the clock for our app. It is the main loop’s main clock.
  7. ballImage = pygame.image.load('ball.png')
    • In this step, we define a variable called “ballImage”.
    • This statement calls the pygame.image.load(‘ball.png’) function that returns a new Surface with the loaded image. The image name (‘ball.png’) is specified within the parenthesis in the function as a parameter.
  8. x = 50 and y = 50
    • In this step, we define the Cartesian coordinates (x, y), where we would like to place our ball image.
    • In this example, the ball’s top-left corner is set to x=50 pixels and y=50 pixels on the screen, which is 200 pixels wide and 200 pixels high.
  9. def ball(x,y):
    • In this step, we define a function called ball(x,y). In this function, there is only one statement screen.blit(ballImage, (x, y))
    • The blit method draws the ball image on the display at location (x, y), which is specified in step 8). 
    • In step 13), we will make the ball visible by using the function pygame.display.update(). We will explain the blit and display.update function in a later Section.
  10. while True:
    • This is the application’s main loop.  The statements in the while loop continue to loop because we use True as the condition. As long as the condition is True, all the following statements in the while loop will iterate in an infinite loop that keeps on running forever or until we quit the application or until the user closes the window.
    • The loop iterates 60 times per second as defined in step 14).
  11. screen.fill(WHITE)
    • The first step in the while loop is to fill the display screen with WHITE color by using the function screen.fill(WHITE). The Pygame.Surface.fill() function is explained in later section.
  12. ball(x, y) Step 12) calls the ball(x,y) function we defined in step 9).
  13. pygame.display.update()
    • The display.update() function updates the display with the ball image that we wrote in step 9.
    • The while loop iterates 60 times per second. A new position of the ball image is created in each loop. The new position of the ball is displayed after each loop.
    • Note that the first statement in the while loop fills the screen with white color, thus erasing the ball’s image from the previous loop. This step to fill the screen with white color is necessary, otherwise, we will see the previous positions on the ball from each preceding loop. Try it by commenting out the screen.fill(WHITE)statement in the program. You will see a trace of all previous positions of the ball.
  14. clock.tick(60) The last statement in the while loop sets the frame-per-second to 60. The while loop will loop 60 times in one second.
  15. pygame.quit() Outside the main loop, we run pygame.quit(), which ends the pygame instance. The following quit() statement exits Python and the application is closed.

If you run this program, you will see the following output on your screen.

Pygame Display an Image
Pygame Display An Image
Verified by MonsterInsights