5.2 Coordinates and drawing

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

5.2 Coordinates and drawing

To draw and move things, you need to understand coordinates and Rect (rectangle) objects.

Pygame coordinates

The screen uses the bottom-left part of a normal graph: x increases to the right, but y increases downward. So:

So “up” on the screen means decreasing y; “down” means increasing y.

Rect (rectangle) objects

A Rect represents a rectangle: where it is and how big it is. You create one with position and size:

# Four numbers: x, y, width, height
rect = pygame.Rect(100, 150, 20, 20)

# Or two tuples: (x, y) and (width, height)
rect = pygame.Rect((200, 200), (20, 20))

So: location_x, location_y, width, height.

Reading and changing position

You can read the position with:

You can update the position by assigning to these:

rect.x = 50
rect.y = 100
# Or move relative to current position:
rect.x += 5   # move 5 pixels right
rect.y -= 3   # move 3 pixels up (y is flipped)

Drawing the rect

In your game loop, after screen.fill(...):

pygame.draw.rect(screen, (255, 0, 0), rect)

Project: A square on the screen

  1. Create a Rect at (200, 200) with size (20, 20).
  2. In the game loop, fill the screen then draw the rect in a bright colour.
  3. Run the program and confirm you see one square that stays still (we’ll move it in the next lesson).

Next: 5.3 Keyboard input and moving a rect — move the square with arrow keys.