Your Own Function
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 21 of 33.
A function is a named group of lines you can run whenever you want. def makes one:
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)def, the name, round brackets and a colon; the body is indented under it. Defining a function draws nothing: Python only remembers the lines under the name.
To run them, call the function: write its name with brackets.
draw_star()Define functions in the setup part, before the game loop, and call them in the loop where you need them. You have called functions since the first lesson: print() and pygame.draw.circle() are functions too, written by others.
pygame.draw.line(screen, colour, start, end, width) draws a line between two points.
Challenge
MediumPut the star in a function.
- In the setup part, make
def draw_star():and move the three star lines into its body. - In the draw part, call
draw_star().
Press Play: the star still shows in the middle. Then Check.
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.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)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
Practice on your own: Pygame playground