Draw Tree Function
Goals
Draw a tree
Draw two trees
Reference every position to single
(x, y)
pointDefine the
draw_tree
functionVary the
y
position. Need to create a list outside the game loop.
Starter code
What you need to do
Make a blue background
Move the trees down and draw a single cloud (composed of multiple circles)
Extract an x and y coordinate for the cloud and have every circle reference that point.
Define a draw_cloud function that takes an x and y value.
Draw multiple clouds in the sky
Create a list for the cloud locations. And use this list to draw the clouds (with a for loop).
In the game updates section, loop through the cloud locations and update only the x component (+= 3). Also in this loop, to prevent the clouds from traveling too far off screen, reset the x position if it goes too far.
Final Code
1import random
2
3import pygame
4from pygame.locals import K_ESCAPE, KEYDOWN, QUIT
5
6
7def draw_tree(x: int, y: int):
8 pygame.draw.rect(screen, (150,75,0), (x, y, 25, 150)) # trunk
9 pygame.draw.circle(screen, (0, 175, 0), (x + 12, y - 50), 75) # leaves
10
11
12pygame.init()
13
14WIDTH = 640
15HEIGHT = 480
16SIZE = (WIDTH, HEIGHT)
17
18screen = pygame.display.set_mode(SIZE)
19clock = pygame.time.Clock()
20
21# ---------------------------
22# Initialize global variables
23
24tree_locations = []
25
26for x in range(50, WIDTH, 50):
27 y = 200 + random.randrange(-20, 20)
28 location = [x, y]
29 tree_locations.append(location)
30
31# ---------------------------
32
33running = True
34while running:
35 # EVENT HANDLING
36 for event in pygame.event.get():
37 if event.type == KEYDOWN:
38 if event.key == K_ESCAPE:
39 running = False
40 elif event.type == QUIT:
41 running = False
42
43 # GAME STATE UPDATES
44
45 # DRAWING
46 screen.fill((255, 255, 255)) # always the first drawing command
47
48
49 for location in tree_locations:
50 x = location[0]
51 y = location[1]
52
53 draw_tree(x, y)
54
55
56 # Must be the last two lines
57 # of the game loop
58 pygame.display.flip()
59 clock.tick(30)
60 #---------------------------
61
62
63pygame.quit()