Menu
CoddyTech

Use the Loop Variable

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

The loop variable is a number like any other, so you can do arithmetic with it and change more than the position. Here each planet is bigger and more yellow than the one before:

for i in range(6):
    x = 70 + i * 100
    radius = 5 + i * 5
    colour = (255, 80 + i * 30, 120)
    pygame.draw.circle(screen, colour, (x, 240), radius)

Work through it for i = 2: x is 270, the radius 15, the colour (255, 140, 120). For i = 5: x 570, radius 30, colour (255, 230, 120).

Variables made inside the body, such as x and radius, get new values on every pass. Naming the parts first keeps the draw line short and clear.

Keep every colour number between 0 and 255. Here the largest green is 80 + 5 * 30, which is 230, so it is safe.

challenge icon

Challenge

Medium

Make each planet bigger and more yellow than the one before.

  1. Keep planet i centred at (70 + i * 100, 240).
  2. Give it radius 5 + i * 5, from 5 to 30.
  3. Give it colour (255, 80 + i * 30, 120).

Press Play: six planets, each bigger and more yellow. Then Check.

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.
    for i in range(6):
        pygame.draw.circle(screen, (255, 80, 120), (70 + i * 100, 240), 10)

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground