0% found this document useful (0 votes)
47 views

Beginners Python Cheat Sheet PCC Pygame BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Beginners Python Cheat Sheet PCC Pygame BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Beginner's Python

Starting a game (cont.) Pygame rect objects (cont.)


Setting a custom window size Creating a rect object
The display.set_mode() function accepts a tuple that defines the You can create a rect object from scratch. For example a small rect

Cheat Sheet - Pygame screen size.


screen_dim = (1500, 1000)
object that’s filled in can represent a bullet in a game. The Rect()
class takes the coordinates of the upper left corner, and the width
and height of the rect. The draw.rect() function takes a screen
self.screen = pygame.display.set_mode( object, a color, and a rect. This function fills the given rect with the
screen_dim)
What is Pygame? given color.

Pygame is a framework for making games using Setting a custom background color bullet_rect = pygame.Rect(100, 100, 3, 15)
Colors are defined as a tuple of red, green, and blue values. Each color = (100, 100, 100)
Python. Making games is fun, and it’s a great way value ranges from 0-255. The fill() method fills the screen with the
to expand your programming skills and knowledge. color you specify, and should be called before you add any other pygame.draw.rect(screen, color, bullet_rect)
Pygame takes care of many of the lower-level tasks in elements to the screen.
building games, which lets you focus on the aspects of def __init__(self): Working with images
your game that make it interesting. --snip-- Many objects in a game are images that are moved around
self.bg_color = (225, 225, 225) the screen. It’s easiest to use bitmap (.bmp) image files, but
Installing Pygame you can also configure your system to work with jpg, png,
Installing Pygame with pip def run_game(self):
and gif files as well.
while True:
$ python -m pip install --user pygame for event in pygame.event.get(): Loading an image
--snip--
ship = pygame.image.load('images/ship.bmp')
Starting a game
self.screen.fill(self.bg_color) Getting the rect object from an image
The following code sets up an empty game window, and
pygame.display.flip()
starts an event loop and a loop that continually refreshes the ship_rect = ship.get_rect()
screen.
Pygame rect objects Positioning an image
An empty game window With rects, it’s easy to position an image wherever you want on
Many objects in a game can be treated as simple rectangles,
import sys rather than their actual shape. This simplifies code without the screen, or in relation to another object. The following code
import pygame positions a ship at the bottom center of the screen, by matching the
noticeably affecting game play. Pygame has a rect object
midbottom of the ship with the midbottom of the screen.
that makes it easy to work with game objects.
class AlienInvasion: ship_rect.midbottom = screen_rect.midbottom
"""Overall class to manage the game.""" Getting the screen rect object
We already have a screen object; we can easily access the rect Drawing an image to the screen
def __init__(self): object associated with the screen. Once an image is loaded and positioned, you can draw it to the
pygame.init() screen with the blit() method. The blit() method acts on
self.screen_rect = self.screen.get_rect()
self.clock = pygame.time.Clock() the screen object, and takes the image object and image rect as
Finding the center of the screen arguments.
self.screen = pygame.display.set_mode(
(1200, 800)) Rect objects have a center attribute which stores the center point. # Draw ship to screen.
pygame.display.set_caption( screen_center = self.screen_rect.center screen.blit(ship, ship_rect)
"Alien Invasion")
Useful rect attributes Transforming an image
def run_game(self): Once you have a rect object, there are a number of attributes The transform module allows you to make changes to an image
while True: that are useful when positioning objects and detecting relative such as rotation and scaling.
for event in pygame.event.get(): positions of objects. (You can find more attributes in the Pygame rotated_image = pygame.transform.rotate(
if event.type == pygame.QUIT: documentation. The self variable has been left off for clarity.) ship.image, 45)
sys.exit() # Individual x and y values:
screen_rect.left, screen_rect.right
pygame.display.flip() screen_rect.top, screen_rect.bottom
self.clock.tick(60) screen_rect.centerx, screen_rect.centery Python Crash Course
screen_rect.width, screen_rect.height A Hands-on, Project-Based
if __name__ == '__main__':
# Make a game instance, and run the game. Introduction to Programming
# Tuples
ai = AlienInvasion() screen_rect.center ehmatthes.github.io/pcc_3e
ai.run_game() screen_rect.size
Working with images (cont.) Responding to mouse events Pygame groups (cont.)
The blitme() method Pygame’s event loop registers an event any time the mouse Removing an item from a group
Game objects such as ships are often written as classes. Then a moves, or a mouse button is pressed or released. It’s important to delete elements that will never appear again in the
blitme() method is usually defined, which draws the object to the game, so you don’t waste memory and resources.
Responding to the mouse button
screen.
for event in pygame.event.get(): bullets.remove(bullet)
def blitme(self):
if event.type == pygame.MOUSEBUTTONDOWN:
"""Draw ship at current location.""" Detecting collisions
ship.fire_bullet()
self.screen.blit(self.image, self.rect)
You can detect when a single object collides with any
Finding the mouse position
member of a group. You can also detect when any member
Responding to keyboard input The mouse position is returned as a tuple.
of one group collides with a member of another group.
Pygame watches for events such as key presses and mouse mouse_pos = pygame.mouse.get_pos()
actions. You can detect any event you care about in the Collisions between a single object and a group
event loop, and respond with any action that’s appropriate Clicking a button The spritecollideany() function takes an object and a group,
You might want to know if the cursor is over an object such as a and returns True if the object overlaps with any member of the
for your game.
button. The rect.collidepoint() method returns True when a group.
Responding to key presses point overlaps a rect object.
if pygame.sprite.spritecollideany(ship, aliens):
Pygame’s main event loop registers a KEYDOWN event any time a key if button_rect.collidepoint(mouse_pos): ships_left -= 1
is pressed. When this happens, you can check for specific keys.
start_game()
for event in pygame.event.get(): Collisions between two groups
if event.type == pygame.KEYDOWN: Hiding the mouse The sprite.groupcollide() function takes two groups, and two
if event.key == pygame.K_RIGHT: booleans. The function returns a dictionary containing information
pygame.mouse.set_visible(False)
about the members that have collided. The booleans tell Pygame
ship_rect.x += 1
whether to delete the members of either group that have collided.
elif event.key == pygame.K_LEFT:
ship_rect.x -= 1
Pygame groups collisions = pygame.sprite.groupcollide(
elif event.key == pygame.K_SPACE: Pygame has a Group class which makes working with a bullets, aliens, True, True)
ship.fire_bullet() group of similar objects easier. A group is like a list, with
elif event.key == pygame.K_q: some extra functionality that’s helpful when building games. score += len(collisions) * alien_point_value
sys.exit() Making and filling a group
Responding to released keys An object that will be placed in a group must inherit from Sprite. Rendering text
When the user releases a key, a KEYUP event is triggered. from pygame.sprite import Sprite, Group You can use text for a variety of purposes in a game. For
example you can share information with players, and you
for event in pygame.event.get():
class Bullet(Sprite): can display a score.
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT: ... Displaying a message
ship.moving_right = False def draw_bullet(self): The following code defines a message, then a color for the text
... and the background color for the message. A font is defined using
def update(self): the default system font, with a font size of 48. The font.render()
The game is an object ... function is used to create an image of the message, and we get the
In the overall structure shown here (under Starting a Game), rect object associated with the image. We then center the image on
the entire game is written as a class. This makes it possible bullets = Group() the screen and display it.
to write programs that play the game automatically, and
msg = "Play again?"
it also means you can build an arcade with a collection of new_bullet = Bullet()
msg_color = (100, 100, 100)
games. bullets.add(new_bullet)
bg_color = (230, 230, 230)
Looping through the items in a group
Pygame documentation The sprites() method returns all the members of a group. f = pygame.font.SysFont(None, 48)
The Pygame documentation is really helpful when building msg_image = f.render(msg, True, msg_color,
for bullet in bullets.sprites(): bg_color)
your own games. The home page for the Pygame project is
bullet.draw_bullet() msg_image_rect = msg_image.get_rect()
at pygame.org/, and the home page for the documentation is
at pygame.org/docs/. Calling update() on a group msg_image_rect.center = screen_rect.center
The most useful part of the documentation are the screen.blit(msg_image, msg_image_rect)
Calling update() on a group automatically calls update() on each
pages about specific parts of Pygame, such as the Rect() member of the group.
class and the sprite module. You can find a list of these
bullets.update() Weekly posts about all things Python
elements at the top of the help pages. mostlypython.substack.com

You might also like