Module 6 - Section 1 - Loops and Animation

6.1.1 - A snowflake

We already know how to draw an object and animate it by changing its position. We managed to animate more than one objects but in the code we have used, many commands were repeated and our code turned to be complicated. What if we wanted to create more than 3 objects. Let's try to create 50 snowflakes in random position inside our screen.

Download the snowflakes template pygame file, save it in your projects folder and open it using Thonny.

Remember that random is a library so we have to import before using it. At the beginning of the script under the import pygame command (line 7) write:

import random

If the background is WHITE change it to BLACK otherwise we would not see the WHITE snowflakes on WHITE background.

Now you can use the random function to create snowflakes. The snowflakes will be white circles of radius of 2. So the command to draw one of them, in a random position, inside our screen is:

x = random.randrange(10, 690)
y = random.randrange(10, 490)
pygame.draw.circle(screen, WHITE, [x,y] , 2)

But where is the correct position of these three commands and why we haven't used randrange(0,700) and (0,500) for the two commands?

You can try to copy and paste the three lines around line 49 and test what is the result.



With this implementation, every time the main loop is executed, the variables x and y are reinitialized. We don't want this, so we have to take the first two command outside the main loop. Around line 29 write a comment:

# --- Initialization of variables

move the first two commands there, taking care of indentation, and rerun the script. Now we have one snowflake in a random position inside our screen.

If you haven't managed to create a working script download it from here and save it inside your project's folder as snow_flakes_1