Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Beginner's Python Starting a game (cont.

)
Setting a custom window size
Pygame rect objects (cont.)
Creating a rect object

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

Pygame documentation Looping through the items in a group f = pg.font.SysFont(None, 48)


The sprites() method returns all the members of a group. msg_image = f.render(msg, True, msg_color,
The Pygame documentation is really helpful when building bg_color)
your own games. The home page for the Pygame project is for bullet in bullets.sprites():
msg_image_rect = msg_image.get_rect()
at http://pygame.org/, and the home page for the bullet.draw_bullet()
msg_image_rect.center = screen_rect.center
documentation is at http://pygame.org/docs/.
Calling update() on a group screen.blit(msg_image, msg_image_rect)
The most useful part of the documentation are the pages
Calling update() on a group automatically calls update() on
about specific parts of Pygame, such as the Rect() class each member of the group.
and the sprite module. You can find a list of these More cheat sheets available at
elements at the top of the help pages. bullets.update() ehmatthes.github.io/pcc_2e/

You might also like