Count with While
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 19 of 32.
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many times to go round:
radius = 200
rings = 0
while radius > 10:
pygame.draw.circle(screen, (150, 190, 255), (320, 240), radius, 2)
radius = radius // 2
rings = rings + 1The radius halves each time: 200, 100, 50, 25, 12. // divides and drops what is after the point, so 25 // 2 is 12. Then it is 6, the condition is false, and the loop ends after 5 rings. rings counts them. The fifth number in the circle call, 2, draws an outline 2 pixels wide instead of a filled circle.
The game loop is a while loop too, one that runs until you close the window. A while loop inside a frame must end quickly, or the frame never ends. Leave out the line that halves the radius and the condition stays true forever: the game freezes, and Check says the game never reached its first frame.
Challenge
MediumIn the draw part, replace the single ring with a while loop:
- Start with
radius = 200andrings = 0. - While
radius > 10: draw an outline ring of colour(150, 190, 255), width 2, centred at (320, 240); halve the radius with//; add 1 torings. - After the loop, show
f"Rings: {rings}"at (20, 20). It readsRings: 5.
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.
font = pygame.font.Font(None, 36)
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, (150, 190, 255), (320, 240), 200, 2)
text = font.render("Rings: 1", True, (230, 230, 240))
screen.blit(text, (20, 20))
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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