PyGame
Pygame is a versatile Python library specifically designed for creating video games. It offers a comprehensive set of tools for handling graphics, sound, and user input. With Pygame, developers can easily design and implement various game elements, from simple 2D games to more complex projects. Its cross-platform compatibility ensures that games created with Pygame can run on multiple operating systems.
Pygame Basics
A basic Pygame application typically follows a structured format. It begins with
importing the pygame
module and initializing it to set up the library.
Next, a game window is created and its dimensions specified. A game loop is then
established, which continuously runs until the user decides to quit.
Key Points:
pygame.init()
: Initializes all Pygame modules.pygame.display.set_mode()
: Creates a display surface.pygame.display.set_caption()
: Sets the title of the window.while
loop: Used to keep the window open until the user closes it.pygame.event.get()
: Checks for events, such as the user clicking the close button.pygame.display.flip()
: Updates the display.pygame.quit()
: Quits Pygame.
## PYGAME BASICS EXAMPLE ##
import pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = SCREEN_SIZE = 800, 600
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Pygame Basics")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
Note: Pygame is not a built-in module for python. If you don't have the Pygame module installed yet on your computer, use the following command in a terminal.
python -m pip install pygame
Drawing Shapes
Pygame provides a versatile toolkit for drawing various shapes on the screen. To render a shape, you'll need to specify the target surface and the desired color. Additionally, each shape function requires specific parameters to define its geometry and appearance.
Basic Python Shapes:
Rectangle
pygame.draw.rect(surface, color, rect, width=0)
surface
: The surface to draw on.color
: The color of the rectangle.rect
: A tuple representing the rectangle's position and dimensions (x, y, width, height).width
: Optional width of the rectangle's border. If 0, the rectangle is filled.
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.rect(screen, (255,0,0), (200,200,20,40), width=0)
pygame.display.flip()
pygame.quit()
Circle
pygame.draw.circle(surface, color, center, radius, width=0)
surface
: The surface to draw on.color
: The color of the circle.center
: A tuple representing the circle's center coordinates (x, y).radius
: The radius of the circle.width
: Optional width of the circle's border. If 0, the circle is filled.
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.circle(screen, (255,0,0), (200,200), 25, width=0)
pygame.display.flip()
pygame.quit()
Line
pygame.draw.line(surface, color, start_pos, end_pos, width=1)
surface
: The surface to draw on.color
: The color of the line.start_pos
: A tuple representing the starting point of the line.end_pos
: A tuple representing the ending point of the line.width
: The width of the line.
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.line(screen, (255,0,0), (0,0), (200,200), width=5)
pygame.display.flip()
pygame.quit()
Polygon
pygame.draw.polygon(surface, color, points, width=0)
surface
: The surface to draw on.color
: The color of the polygon.points
: A list of tuples representing the polygon's vertices.width
: Optional width of the polygon's border. If 0, the polygon is filled.
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.polygon(screen, (0,0,255), [(0,0),(200,100),(200,300),(0,400)], width=0)
pygame.display.flip()
pygame.quit()
Using Images
Images are the lifeblood of most Pygame games. They provide the visual elements that make games engaging and immersive. Without images, games would be limited to text-based interfaces, significantly reducing their appeal.
Key Points:
- Sprites: These are individual images representing characters, objects, or enemies in a game.
- Backgrounds: These images form the backdrop of the game world.
- UI Elements: Images can be used to create buttons, menus, health bars, and other interactive elements.
- Particle Effects: Small images can be used to create dynamic effects like explosions, smoke, or rain.
How to use images:
Load Image
img = pygame.image.load("image.png")
Resize Image
img = pygame.transform.scale(img, (new_width , new_height))
Blit Image to Screen
screen.blit(img, (x_pos, y_pos))
## IMAGE EXAMPLE ##\
import pygame, random
x_pos = random.randint(0,263)
y_pos = random.randint(0,368)
delta_x = .02
delta_y = .02
pygame.init()
screen = pygame.display.set_mode((400,400))
img = pygame.image.load("ap-csp-logo.png").convert()
img = pygame.transform.scale(img, (137 , 32))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
x_pos += delta_x
y_pos += delta_y
if x_pos < 0 or x_pos > 263:
delta_x *= -1
if y_pos < 0 or y_pos > 368:
delta_y *= -1
screen.fill((0, 0, 0))
screen.blit(img, (x_pos, y_pos))
pygame.display.flip()
pygame.quit()
Event Handling
Event handling is a crucial mechanism that allows your game to respond to user input and system events. It's like a listener, constantly monitoring for actions like key presses, mouse clicks, or window closures.
Common Event Types:
pygame.QUIT
: Indicates the user has closed the window.-
pygame.KEYDOWN
andpygame.KEYUP
: Represent key presses and releases, respectively. Attributes includekey
(the key code),mod
(modifiers like shift or control), andunicode
(the character associated with the key). -
pygame.MOUSEBUTTONDOWN
andpygame.MOUSEBUTTONUP
: Represent mouse button presses and releases. Attributes includebutton
(the button number),pos
(the mouse position), andrel
(the relative movement of the mouse). -
pygame.MOUSEMOTION
: Represents mouse movement. Attributes includepos
(the new mouse position),rel
(the relative movement), andbuttons
(a tuple indicating which mouse buttons are pressed)
## EVENT HANDLING EXAMPLE ##
import pygame, random
circ_pos_x, circ_pos_y = circ_pos = 200, 200
circ_color = (255, 255, 255)
pygame.init()
screen = pygame.display.set_mode((400,400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEMOTION:
circ_pos_x, circ_pos_y = event.pos[0], event.pos[1]
elif event.type == pygame.MOUSEBUTTONUP:
circ_color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP]:
circ_pos_y -= .1
if keys_pressed[pygame.K_DOWN]:
circ_pos_y += .1
if keys_pressed[pygame.K_LEFT]:
circ_pos_x -= .1
if keys_pressed[pygame.K_RIGHT]:
circ_pos_x += .1
if(circ_pos_x < 0):
circ_pos_x = 0
elif(circ_pos_x > 400):
circ_pos_x = 400
if(circ_pos_y < 0):
circ_pos_y = 0
elif(circ_pos_y > 400):
circ_pos_y = 400
circ_pos = circ_pos_x, circ_pos_y
screen.fill('black')
pygame.draw.circle(screen, circ_color, tuple(circ_pos), 25, width=0)
pygame.display.flip()
pygame.quit()
Note: The pygame.key.get_pressed()
gets all keys currently
being held down. This allows for adding movement continuously.