Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
To draw and move things, you need to understand coordinates and Rect (rectangle) objects.
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.
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.
You can read the position with:
rect.x and rect.yrect.left, rect.right, rect.top, rect.bottom (edges)rect.centerx, rect.centery (centre)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)
In your game loop, after screen.fill(...):
pygame.draw.rect(screen, (255, 0, 0), rect)
Next: 5.3 Keyboard input and moving a rect — move the square with arrow keys.