Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 41 ยท Drawing and Images

Colors and Rects

Work with pygame.Color and pygame.Rect - RGB, names, hex, HSVA and lerp, plus Rect position attributes, move_ip, inflate, clamp, union, clip and the collision methods.

Two small classes appear in nearly every line of Pygame code: Color and Rect. A Color describes how a pixel looks, and a Rect describes where a rectangle sits and how big it is. Learning their conveniences saves you pages of arithmetic. Both work without a window, so every example here runs in the browser.

Colors

The simplest color is a tuple of red, green, blue values from 0 to 255, optionally with a fourth alpha value:

Python
RED = (255, 0, 0)
SKY = (135, 206, 235)
GLASS = (255, 255, 255, 80)

pygame.Color wraps these and adds helpers:

Python
c = pygame.Color(255, 128, 0)
c = pygame.Color("orange")          # named colors
c = pygame.Color("#ff8800")         # hex string
c.r, c.g, c.b, c.a                  # components (a defaults to 255)

Useful methods: lerp(other, t) blends two colors, grayscale() returns a gray version, normalize() gives floats from 0 to 1, and hsva / hsla convert to hue, saturation and value for rainbow effects.

Python Color tricks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Lerping is how you make a health bar change from green to red, or fade a background from day to night: GREEN.lerp(RED, 1 - health / max_health).

Tip: Define your palette as named constants at the top of the file (BACKGROUND, PLAYER, DANGER). Changing a color then takes one edit, and your game looks consistent.

The Rect

A Rect stores x, y, width and height as integers and computes everything else from them. You create one with Rect(left, top, width, height) or from a position and size tuple:

Python
r = pygame.Rect(100, 50, 80, 40)
r = pygame.Rect((100, 50), (80, 40))

Surfaces give you rects with surface.get_rect(**anchor), where the anchor is any rect attribute:

Python
player_rect = player_image.get_rect(center=(400, 300))
hud_rect = hud.get_rect(topright=(screen_width - 10, 10))

Position attributes

Every one of these is both readable and writable, and changing one updates the others:

Group Attributes
Edges left, right, top, bottom (also x, y)
Corners topleft, topright, bottomleft, bottomright
Midpoints midtop, midleft, midbottom, midright
Center center, centerx, centery
Size size, width, height, w, h

Setting r.center = (400, 300) moves the rectangle so that its center sits there; setting r.midbottom = (400, 550) is perfect for something standing on a floor.

Python Rect attributes stay in sync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Moving and resizing

Many methods come in pairs: one returns a new rect, the _ip ("in place") version changes the rect itself.

Method Meaning
move(dx, dy) / move_ip(dx, dy) Shift by an offset
inflate(dw, dh) / inflate_ip Grow or shrink around the center
scale_by(factor) Resize by a factor around the center
clamp(other) / clamp_ip Move inside another rect
fit(other) Resize to the largest size with this rect's aspect ratio that fits in other
union(other) Smallest rect containing both
clip(other) The overlapping area (empty if none)
normalize() Fix negative width or height
Python
player.move_ip(speed, 0)
player.clamp_ip(screen_rect)      # keep the player on screen: one line!
hitbox = player.inflate(-20, -10) # a forgiving hitbox, smaller than the sprite

Testing overlaps

Method Returns
collidepoint(x, y) True if the point is inside
colliderect(other) True if the rectangles overlap
contains(other) True if other is entirely inside
collidelist(list) Index of the first overlapping rect, or -1
collidelistall(list) Indexes of all overlapping rects
collidedict(dict) First key/value pair whose rect overlaps
Python Move, clamp and collide

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rect gotchas

  • Integers only. A Rect rounds coordinates, so rect.x += 0.5 does nothing visible. For slow or precise movement keep a float position (for example a Vector2) and write it into the rect each frame. pygame-ce also offers pygame.FRect with float coordinates.
  • Edges are exclusive. A rect at (0, 0, 10, 10) has right == 10, but the last pixel inside is 9. Two rects touching edge to edge (a.right == b.left) do not collide.
  • Truthiness. A Rect with zero width or height is falsy (bool(Rect(0,0,0,5)) is False).
  • Copy before mutating. other = rect shares the same object; use rect.copy().
  • Rects are not tied to surfaces. image.get_rect() gives a fresh rect at (0, 0). Move that rect and blit the image at it: screen.blit(image, rect).

You will use rects heavily for the next lessons: drawing shapes takes rects as arguments, sprites carry a rect, and collision detection is built on colliderect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression creates a Color from a color name?

    pygame.Color accepts named colors, hex strings and numbers.
  2. 2. What does rect.midbottom = (400, 550) do?

    Assigning an anchor attribute moves the rectangle so that anchor lands on the given point.
  3. 3. What is the difference between move() and move_ip()?

    The _ip variants mutate the rect and return None.
  4. 4. Two rects have a.right == b.left. What does a.colliderect(b) return?

    Edges are exclusive, so rects that only touch do not overlap.
  5. 5. How do you keep a player rect inside the screen with one call?

    clamp_ip moves the rect (without resizing it) to lie within the other rect.

Summary

  • Colors are RGB(A) tuples or pygame.Color objects (names, hex, lerp, HSV).
  • A Rect has many synchronized attributes: edges, corners, midpoints, center, size.
  • get_rect(center=...) builds a positioned rect from a surface.
  • _ip methods change the rect in place; others return a new one.
  • colliderect, collidepoint, collidelist and friends test overlaps; touching edges do not collide.
  • Rects hold integers; keep float positions separately.

Next: Drawing Shapes