Menu
CoddyTech

Parameters

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

A function that always draws at (320, 240) is of little use. Parameters let the caller choose. Name them in the brackets of the def and use them in the body like variables:

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)

Each call passes values, the arguments, in the same order: draw_star(120, 100) runs the body with x 120 and y 100. draw_star(520, 90) runs it again with other values. One definition, as many stars as you call.

The parameters exist only inside the function while it runs. Outside it, x and y mean nothing, or whatever you stored under those names there.

challenge icon

Challenge

Medium

Let the caller place the star:

  1. Change the definition to def draw_star(x, y): and draw around (x, y): the lines from x - 10 to x + 10 and from y - 10 to y + 10, the dot at (x, y).
  2. Call it three times: at (120, 100), (320, 180) and (520, 90).

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():
    pygame.draw.line(screen, (255, 240, 200), (310, 240), (330, 240), 2)
    pygame.draw.line(screen, (255, 240, 200), (320, 230), (320, 250), 2)
    pygame.draw.circle(screen, (255, 240, 200), (320, 240), 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()

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground