Repeat with For
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 15 of 32.
A for loop repeats its lines, once for each value it is given:
for i in range(8):
pygame.draw.circle(screen, (255, 255, 255), (40 + i * 80, 80), 5)range(8) gives the numbers 0, 1, 2 and so on up to 7: eight numbers, starting at 0 and stopping before 8. The loop stores each one in i in turn and runs the indented lines. So the first star is at x 40, the next at 120, then 200, up to 600.
The indented lines are the loop's body, as with an if. The first line after the body, back at the outer indent, runs once the loop is done.
This loop sits in the draw part of the game loop, so all eight stars are drawn again on every frame. It is short and finishes at once, so the frame still ends on time.
i is a common name for a counting variable, but any name works: for n in range(8): counts the same.
Challenge
EasyReplace the single star with a for loop over range(8) that draws 8 white stars of radius 5 at (40 + i * 80, 80).
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.circle(screen, (255, 255, 255), (40, 80), 5)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
4Loops That Draw
Repeat with ForStart, Stop and StepUse the Loop VariableA Loop in a LoopCount with While2Numbers and Variables
Name a ValueDo the MathsMove Every FrameWords on the ScreenWhole and Half NumbersPractice on your own: Pygame playground