Menu
CoddyTech

Draw a Square

Lesson 3 of 40 in Coddy's Make Games with Pygame course.

Pygame measures the window in pixels from the top left corner. x grows to the right and y grows down, so (0, 0) is the top left corner.

pygame.draw.rect(surface, color, rect) draws a filled rectangle. The rect is (x, y, width, height), where x and y are its top left corner.

screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 0, 0), (10, 20, 100, 50))
pygame.display.flip()

This draws a red rectangle 100 wide and 50 tall, 10 pixels from the left edge and 20 from the top.

Order matters. Everything you draw covers what is already there, so draw after fill, or the fill paints over your shape.

challenge icon

Challenge

Easy

After the fill, draw a yellow (255, 196, 0) square, 40 by 40, with its top left corner at (220, 160).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 46))
    pygame.display.flip()

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground