Start, Stop and Step
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 16 of 32.
range takes up to three numbers: range(start, stop, step).
range(5): 0, 1, 2, 3, 4range(2, 6): 2, 3, 4, 5range(60, 200, 40): 60, 100, 140, 180
It starts at the start, adds the step each time, and stops before it reaches the stop. The stop value itself is never in the range.
With a start and a step, the loop variable can be the position itself, with no sum needed:
for x in range(60, 600, 40):
pygame.draw.circle(screen, (255, 160, 60), (x, 420), 8)To end a row at 580, the stop must be past it: range(60, 580, 40) ends at 540. A step can be negative to count down: range(10, 0, -2) is 10, 8, 6, 4, 2.
Challenge
EasyUnder the stars, draw a row of lanterns with one for loop:
- Orange
(255, 160, 60)circles of radius 8 at y420. - x from 60 to 580, every 40 pixels: 14 lanterns.
- Use
rangewith a start, a stop and a step, and replace the single lantern.
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(8):
pygame.draw.circle(screen, (255, 255, 255), (40 + i * 80, 80), 5)
pygame.draw.circle(screen, (255, 160, 60), (60, 420), 8)
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