Draw a Square
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 3 of 32.
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
EasyAfter 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()
All lessons in The Game Loop
1Move a Square
Open a WindowFill the BackgroundPractice on your own: Pygame playground