Call It Many Times
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 23 of 32.
Call a function in a loop and it draws a pattern. The loop works out the arguments, the function does the drawing:
for i in range(8):
draw_star(60 + i * 70, 60 + i * 45)Each pass is 70 pixels right of the last and 45 pixels lower, so the stars run in a line from (60, 60) to (550, 375). Change 70 or 45 and every star follows.
This is why functions are worth writing. The lines that draw a star exist once. To change how every star looks, longer rays or another colour, you change the function's body, and every call draws the new star.
Name a function after what it does, often with a verb: draw_star, move_comet, reset_game. Then a line that calls it reads like a sentence.
Challenge
EasyDraw a line of stars: replace the single call with for i in range(8): calling draw_star(60 + i * 70, 60 + i * 45). The 8 stars run from (60, 60) to (550, 375).
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.
def draw_star(x, y):
pygame.draw.line(screen, (255, 240, 200), (x - 10, y), (x + 10, y), 2)
pygame.draw.line(screen, (255, 240, 200), (x, y - 10), (x, y + 10), 2)
pygame.draw.circle(screen, (255, 240, 200), (x, y), 4)
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.
draw_star(60, 60)
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
Practice on your own: Pygame playground