Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
509 views

Beginners Python Cheat Sheet PCC Pygame PDF

The document provides an overview of Pygame and instructions for installing Pygame on different operating systems. It then summarizes some useful features of Pygame including creating and positioning rectangle objects to represent game objects, loading and positioning images, and getting the screen rectangle object.

Uploaded by

booklover2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
509 views

Beginners Python Cheat Sheet PCC Pygame PDF

The document provides an overview of Pygame and instructions for installing Pygame on different operating systems. It then summarizes some useful features of Pygame including creating and positioning rectangle objects to represent game objects, loading and positioning images, and getting the screen rectangle object.

Uploaded by

booklover2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

The following code sets up an empty game window, and

starts an event loop and a loop that continually refreshes Useful rect attributes
Once you have a rect object, there are a number of attributes that
the screen.
are useful when positioning objects and detecting relative positions
An empty game window of objects. (You can find more attributes in the Pygame
documentation.)
import sys
# Individual x and y values:
import pygame as pg
screen_rect.left, screen_rect.right
screen_rect.top, screen_rect.bottom
Pygame is a framework for making games using def run_game():
screen_rect.centerx, screen_rect.centery
Python. Making games is fun, and its a great way to # Initialize and set up screen.
screen_rect.width, screen_rect.height
expand your programming skills and knowledge. pg.init()
Pygame takes care of many of the lower-level tasks screen = pg.display.set_mode((1200, 800))
# Tuples
in building games, which lets you focus on the pg.display.set_caption("Alien Invasion")
screen_rect.center
aspects of your game that make it interesting. screen_rect.size
# Start main loop.
while True: Creating a rect object
# Start event loop. You can create a rect object from scratch. For example a small rect
Pygame runs on all systems, but setup is slightly different for event in pg.event.get(): object thats filled in can represent a bullet in a game. The Rect()
if event.type == pg.QUIT: class takes the coordinates of the upper left corner, and the width
on each OS. The instructions here assume youre using and height of the rect. The draw.rect() function takes a screen
Python 3, and provide a minimal installation of Pygame. If sys.exit()
object, a color, and a rect. This function fills the given rect with the
these instructions dont work for your system, see the more given color.
detailed notes at http://ehmatthes.github.io/pcc/. # Refresh screen.
pg.display.flip() bullet_rect = pg.Rect(100, 100, 3, 15)
Pygame on Linux color = (100, 100, 100)
$ sudo apt-get install python3-dev mercurial run_game() pg.draw.rect(screen, color, bullet_rect)
libsdl-image1.2-dev libsdl2-dev Setting a custom window size
libsdl-ttf2.0-dev The display.set_mode() function accepts a tuple that defines the
$ pip install --user screen size. Many objects in a game are images that are moved around
hg+http://bitbucket.org/pygame/pygame the screen. Its easiest to use bitmap (.bmp) image files, but
screen_dim = (1200, 800)
screen = pg.display.set_mode(screen_dim) you can also configure your system to work with jpg, png,
Pygame on OS X and gif files as well.
This assumes youve used Homebrew to install Python 3.
Setting a custom background color
$ brew install hg sdl sdl_image sdl_ttf Colors are defined as a tuple of red, green, and blue values. Each Loading an image
$ pip install --user value ranges from 0-255. ship = pg.image.load('images/ship.bmp')
hg+http://bitbucket.org/pygame/pygame bg_color = (230, 230, 230)
Getting the rect object from an image
Pygame on Windows screen.fill(bg_color)
Find an installer at ship_rect = ship.get_rect()
https://bitbucket.org/pygame/pygame/downloads/ or
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame that matches Positioning an image
your version of Python. Run the installer file if its a .exe or .msi file. Many objects in a game can be treated as simple With rects, its easy to position an image wherever you want on the
If its a .whl file, use pip to install Pygame: rectangles, rather than their actual shape. This simplifies screen, or in relation to another object. The following code
positions a ship object at the bottom center of the screen.
> python m pip install --user code without noticeably affecting game play. Pygame has a
pygame-1.9.2a0-cp35-none-win32.whl rect object that makes it easy to work with game objects. ship_rect.midbottom = screen_rect.midbottom

Testing your installation Getting the screen rect object


We already have a screen object; we can easily access the rect
To test your installation, open a terminal session and try to import
object associated with the screen.
Pygame. If you dont get any error messages, your installation was
successful. screen_rect = screen.get_rect()
$ python Covers Python 3 and Python 2
Finding the center of the screen
>>> import pygame Rect objects have a center attribute which stores the center point.
>>>
screen_center = screen_rect.center
Pygames event loop registers an event any time the
Drawing an image to the screen mouse moves, or a mouse button is pressed or released. Removing an item from a group
Once an image is loaded and positioned, you can draw it to the Its important to delete elements that will never appear again in the
screen with the blit() method. The blit() method acts on the screen Responding to the mouse button game, so you dont waste memory and resources.
object, and takes the image object and image rect as arguments.
for event in pg.event.get(): bullets.remove(bullet)
# Draw ship to screen. if event.type == pg.MOUSEBUTTONDOWN:
screen.blit(ship, ship_rect) ship.fire_bullet()
The blitme() method Finding the mouse position You can detect when a single object collides with any
Game objects such as ships are often written as classes. Then a The mouse position is returned as a tuple. member of a group. You can also detect when any member
blitme() method is usually defined, which draws the object to the of one group collides with a member of another group.
screen. mouse_pos = pg.mouse.get_pos()
def blitme(self):
Collisions between a single object and a group
Clicking a button The spritecollideany() function takes an object and a group, and
"""Draw ship at current location.""" You might want to know if the cursor is over an object such as a returns True if the object overlaps with any member of the group.
self.screen.blit(self.image, self.rect) button. The rect.collidepoint() method returns true when a point is
inside a rect object. if pg.sprite.spritecollideany(ship, aliens):
ships_left -= 1
if button_rect.collidepoint(mouse_pos):
Pygame watches for events such as key presses and start_game() Collisions between two groups
mouse actions. You can detect any event you care about in The sprite.groupcollide() function takes two groups, and two
Hiding the mouse booleans. The function returns a dictionary containing information
the event loop, and respond with any action thats
about the members that have collided. The booleans tell Pygame
appropriate for your game. pg.mouse.set_visible(False) whether to delete the members of either group that have collided.
Responding to key presses collisions = pg.sprite.groupcollide(
Pygames main event loop registers a KEYDOWN event any time a bullets, aliens, True, True)
key is pressed. When this happens, you can check for specific Pygame has a Group class which makes working with a
keys.
group of similar objects easier. A group is like a list, with score += len(collisions) * alien_point_value
for event in pg.event.get(): some extra functionality thats helpful when building games.
if event.type == pg.KEYDOWN:
Making and filling a group
if event.key == pg.K_RIGHT: An object that will be placed in a group must inherit from Sprite.
ship_rect.x += 1 You can use text for a variety of purposes in a game. For
elif event.key == pg.K_LEFT: from pygame.sprite import Sprite, Group example you can share information with players, and you
ship_rect.x -= 1 can display a score.
elif event.key == pg.K_SPACE: def Bullet(Sprite): Displaying a message
ship.fire_bullet() ... The following code defines a message, then a color for the text and
elif event.key == pg.K_q: def draw_bullet(self): the background color for the message. A font is defined using the
sys.exit() ... 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
Responding to released keys ... rect object associated with the image. We then center the image
When the user releases a key, a KEYUP event is triggered. on the screen and display it.

if event.type == pg.KEYUP: bullets = Group() msg = "Play again?"


if event.key == pg.K_RIGHT: msg_color = (100, 100, 100)
ship.moving_right = False new_bullet = Bullet() bg_color = (230, 230, 230)
bullets.add(new_bullet)
f = pg.font.SysFont(None, 48)
Looping through the items in a group msg_image = f.render(msg, True, msg_color,
The Pygame documentation is really helpful when building The sprites() method returns all the members of a group.
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/. screen.blit(msg_image, msg_image_rect)
The most useful part of the documentation are the pages Calling update() on a group
about specific parts of Pygame, such as the Rect() class Calling update() on a group automatically calls update() on each
member of the group.
and the sprite module. You can find a list of these elements More cheat sheets available at
at the top of the help pages. bullets.update()

You might also like