Menu
CoddyTech

A Loop in a Loop

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 18 of 32.

A loop's body can hold another loop. The inner loop runs all the way through on each pass of the outer one:

for row in range(4):
    for col in range(8):
        x = 130 + col * 50
        y = 210 + row * 60
        pygame.draw.rect(screen, (255, 210, 90), (x, y, 20, 20))

For row 0 the inner loop draws 8 windows along the top. Then row becomes 1 and the inner loop draws 8 more, 60 pixels lower. Four rows of eight make 32 windows. A grid always has this shape: one loop for the rows, one for the columns.

pygame.draw.rect(screen, colour, (x, y, width, height)) draws a filled rectangle with its top left corner at (x, y).

Mind the indents: the inner for is indented under the outer one, and its body is indented again, 8 spaces in from the outer loop.

challenge icon

Challenge

Medium

Light up the whole building:

  1. Wrap the window loop in for row in range(4):.
  2. Set y = 210 + row * 60, so the rows sit at y 210, 270, 330 and 390.
  3. You get 32 windows: 4 rows of 8.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.

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

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.rect(screen, (40, 44, 70), (100, 180, 440, 300))
    for col in range(8):
        x = 130 + col * 50
        y = 210
        pygame.draw.rect(screen, (255, 210, 90), (x, y, 20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground