Menu
CoddyTech

Pygame Cheat Sheet

Last updated

Setup and the game loop

Every pygame program opens a window, then repeats one loop until the player quits.

OperationCode
Install pygame-cepython3 -m pip install pygame-ce
Import and start pygameimport pygame pygame.init()
Open a windowscreen = pygame.display.set_mode((640, 480))
Set the window titlepygame.display.set_caption("My Game")
Make a clockclock = pygame.time.Clock()
The game looprunning = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill("black") pygame.display.flip() clock.tick(60)
Shut down after the looppygame.quit()

Display

The screen is a Surface; nothing shows until you flip it.

OperationCode
Show the finished framepygame.display.flip()
Show only some areaspygame.display.update([rect1, rect2])
Clear the screenscreen.fill((30, 30, 46))
Window sizescreen.get_size(), screen.get_width()
The screen as a Rectscreen.get_rect()
Resizable windowpygame.display.set_mode((640, 480), pygame.RESIZABLE)
Fullscreen at the desktop sizepygame.display.set_mode((0, 0), pygame.FULLSCREEN)

Colors and drawing

pygame.draw functions take a surface, a color and a position. width=0 fills.

OperationCode
Color as RGB(255, 140, 0)
Color by name or hex"tomato", "#ff8c00", pygame.Color("gold")
Rectanglepygame.draw.rect(screen, "red", (x, y, w, h))
Outline and rounded cornerspygame.draw.rect(screen, "red", rect, width=2, border_radius=8)
Circle (by its center)pygame.draw.circle(screen, "blue", (cx, cy), radius)
Linepygame.draw.line(screen, "white", (x1, y1), (x2, y2), 3)
Polygonpygame.draw.polygon(screen, "green", [(0, 0), (40, 0), (20, 30)])
Ellipse in a boxpygame.draw.ellipse(screen, "purple", (x, y, w, h))

Rect

A Rect stores a position and a size as whole numbers.

OperationCode
Make a Rectplayer = pygame.Rect(x, y, width, height)
Position by any pointplayer.center = (320, 240), player.bottom = 400
Edges and cornersleft, right, top, bottom, topleft, midbottom
Move in placeplayer.move_ip(dx, dy)
Moved copymoved = player.move(dx, dy)
Keep inside the screenplayer.clamp_ip(screen.get_rect())
Grow around the centerbigger = player.inflate(20, 20)
Float positions (pygame-ce)pygame.FRect(10.5, 20.25, 40, 40)

Images, Surfaces and blit

Load images once, before the loop, then blit them every frame.

OperationCode
Load an image with transparencyimg = pygame.image.load("player.png").convert_alpha()
Load a solid imagebg = pygame.image.load("sky.png").convert()
Draw an imagescreen.blit(img, (x, y))
Draw centeredscreen.blit(img, img.get_rect(center=(320, 240)))
New blank Surfacepanel = pygame.Surface((200, 100))
Transparent Surfacelayer = pygame.Surface((200, 100), pygame.SRCALPHA)
Fade a whole Surfaceimg.set_alpha(128)
Cut a frame from a sheetframe = sheet.subsurface((0, 0, 32, 32))
Save a screenshotpygame.image.save(screen, "shot.png")

Transform

Each function returns a new Surface; transform the original, not the last result.

OperationCode
Resizepygame.transform.scale(img, (64, 64))
Scale by a factorpygame.transform.scale_by(img, 2)
Smooth resizepygame.transform.smoothscale(img, (64, 64))
Rotate (counterclockwise, degrees)pygame.transform.rotate(img, 45)
Rotate around the centerrotated = pygame.transform.rotate(original, angle) rect = rotated.get_rect(center=rect.center)
Mirror horizontallypygame.transform.flip(img, True, False)

Events and keyboard

Use events for single presses and get_pressed() for keys held down.

OperationCode
Read this frame's eventsfor event in pygame.event.get():
Window closedevent.type == pygame.QUIT
A key was pressedevent.type == pygame.KEYDOWN and event.key == pygame.K_SPACE
A key was releasedevent.type == pygame.KEYUP
Character typedevent.unicode
Keys held nowkeys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= 5
Direction from two keysdx = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
Keys pressed this frame (pygame-ce)pygame.key.get_just_pressed()[pygame.K_SPACE]
Key constantsK_a...K_z, K_0...K_9, K_UP, K_RETURN, K_ESCAPE, K_LSHIFT
Name of a keypygame.key.name(event.key)
Custom eventHIT = pygame.event.custom_type() pygame.event.post(pygame.event.Event(HIT))

Mouse

Buttons: 1 left, 2 middle, 3 right.

OperationCode
A button was pressedevent.type == pygame.MOUSEBUTTONDOWN and event.button == 1
Where it was pressedevent.pos
Pointer position nowx, y = pygame.mouse.get_pos()
Buttons held nowleft, middle, right = pygame.mouse.get_pressed()
Mouse movedevent.type == pygame.MOUSEMOTION, event.rel
Wheel turnedevent.type == pygame.MOUSEWHEEL, event.y
Clicked inside a buttonbutton_rect.collidepoint(event.pos)
Hide the pointerpygame.mouse.set_visible(False)

Sprites and groups

A sprite keeps an image and a rect; a group updates and draws many.

OperationCode
Sprite classclass Coin(pygame.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = coin_img self.rect = self.image.get_rect(center=pos)
Make a groupcoins = pygame.sprite.Group()
Add to a groupcoins.add(Coin((100, 50)))
Update every spritecoins.update()
Draw every spritecoins.draw(screen)
Remove a sprite from all groupscoin.kill()
Group holding one spriteplayer = pygame.sprite.GroupSingle(Player())

Collisions

Rects collide when they overlap; touching edges do not count.

OperationCode
Two rectanglesa.colliderect(b)
Point insiderect.collidepoint(x, y)
First of manyrect.collidelist(walls) # index or -1
Sprite against a grouphits = pygame.sprite.spritecollide(player, coins, True)
Any hit at allpygame.sprite.spritecollideany(player, enemies)
Group against grouppygame.sprite.groupcollide(bullets, enemies, True, True)
Pixel-perfectpygame.sprite.spritecollide(a, group, False, pygame.sprite.collide_mask)
Circlespygame.Vector2(a).distance_to(b) < r1 + r2

Text and fonts

Render text to a Surface, then blit it.

OperationCode
Default fontfont = pygame.font.Font(None, 36)
System fontfont = pygame.font.SysFont("arial", 24)
Font filefont = pygame.font.Font("pixel.ttf", 32)
Render texttext = font.render("Score: 10", True, "white")
Draw it centeredscreen.blit(text, text.get_rect(center=(320, 40)))
Wrap long text (pygame-ce)font.render(story, True, "white", None, 400)
Size without renderingfont.size("Hello")
Installed fontspygame.font.get_fonts()

Sound and music

Load sounds once. Music streams one track from its file.

OperationCode
Load a soundjump = pygame.mixer.Sound("jump.ogg")
Play itjump.play()
Sound volumejump.set_volume(0.5)
Load musicpygame.mixer.music.load("theme.ogg")
Loop music foreverpygame.mixer.music.play(-1)
Pause and resumepygame.mixer.music.pause(), pygame.mixer.music.unpause()
Stop the musicpygame.mixer.music.stop()

Time and timers

Ticks are in milliseconds.

OperationCode
Cap the frame rateclock.tick(60)
Delta time in secondsdt = clock.tick(60) / 1000
Current frame rateclock.get_fps()
Milliseconds since initpygame.time.get_ticks()
Repeating timer eventSPAWN = pygame.event.custom_type() pygame.time.set_timer(SPAWN, 1000)
One-shot timerpygame.time.set_timer(SPAWN, 2000, loops=1)
Stop a timerpygame.time.set_timer(SPAWN, 0)

Vector2

Floats for positions and velocities.

OperationCode
Make a vectorpos = pygame.Vector2(100, 200)
Move by a velocitypos += velocity * dt
Lengthvelocity.length()
Same speed on diagonalsif direction.length() > 0: direction = direction.normalize()
Distance between pointspos.distance_to(target)
Rotatevelocity.rotate(90)
Step toward a point (pygame-ce)pos.move_towards_ip(target, 5)

The pygame code you reach for while making a 2D game in Python, grouped by task: the game loop, the display, colors and drawing, Rect, images and blit, scaling and rotating, keyboard and mouse input, sprites and groups, collisions, text, sound, timers and Vector2. Each row is a short snippet to paste, next to what it does.

Everything here is written for pygame-ce 2.5, the community edition of pygame, which you still import with import pygame. Rows marked pygame-ce use its additions; every other row also works in the original pygame. Try any snippet in the pygame playground, which runs pygame in your browser with nothing to install. New to Python itself? Start with the Python cheat sheet.

Pygame cheat sheet FAQ

Is this pygame cheat sheet free?

Yes. It is free with no sign-up. Bookmark it, or print it to PDF from your browser, and come back whenever you need the exact call for a sprite group, a sound or a collision check.

Does this cheat sheet work with pygame and pygame-ce?
Yes. Both are imported with import pygame and share almost the whole API. The rows marked pygame-ce (FRect, scale_by, get_just_pressed, text wrapping and move_towards_ip) need pygame-ce, and everything else runs on either.
Why does my pygame window not respond?
The game loop is not reading events. Call pygame.event.get() once every frame, even if you ignore the events, and end each frame with pygame.display.flip() and clock.tick(60).
Should I use events or key.get_pressed() for input?
Use a KEYDOWN event for actions that happen once per press, such as jumping or opening a menu. Use pygame.key.get_pressed() for actions that last while a key is held, such as walking.
Coddy programming languages illustration

Learn Pygame with Coddy

Get started