Menu
CoddyTech

A Scene of Shapes

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 11 of 32.

A picture in a game is often many small shapes. A tree here is a brown trunk with a green circle on top. Draw several and you have a forest.

When the same group of shapes appears more than once, put it in a function that takes the position. Each call draws one tree:

def draw_tree(x, y):
    pygame.draw.rect(screen, (120, 80, 40), (x - 5, y, 10, 30))
    pygame.draw.circle(screen, (60, 170, 90), (x, y), 20)

draw_tree(80, 250)
draw_tree(240, 250)

Every shape in the function is placed from x and y, so moving a tree means changing one call.

Order still matters inside the function. The trunk starts at the circle's centre, and the circle is drawn second, so it covers the top of the trunk. Swap the two lines and the trunk shows through the leaves.

challenge icon

Challenge

Easy
  1. In draw_tree, after the trunk, draw the crown: a green (60, 170, 90) circle centred at (x, y) with radius 20.
  2. Below draw_tree(80, 250), call it twice more, for trees at (240, 250) and (400, 250).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Forest")
clock = pygame.time.Clock()


def draw_tree(x, y):
    pygame.draw.rect(screen, (120, 80, 40), (x - 5, y, 10, 30))


running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 46))
    pygame.draw.circle(screen, (240, 240, 210), (70, 60), 24)
    pygame.draw.rect(screen, (40, 90, 50), (0, 280, 480, 80))
    draw_tree(80, 250)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground