6.1.1 - Μία νιφάδα χιονιού

Ξέρουμε ήδη πως να σχεδιάσουμε ένα αντικείμενο και να το κάνουμε να κινείται αλλάζοντας τη θέση του. Καταφέραμε να κάνουμε να κινούνται παραπάνω από ένα αντικείμενα, αλλά στον κώδικα που χρησιμοποιήσαμε, πολλές εντολές επαναλαμβάνονταν και ο κώδικας κατέληξε να είναι πολύπλοκος. Τι θα γινόταν αν θέλαμε να δημιουργήσουμε πάνω από 3 αντικείμενα; Πάμε να δοκιμάσουμε να δημιουργήσουμε 50 νιφάδες χιονιού σε τυχαίες θέσεις μέσα στην οθόνη μας.

Κάντε λήψη του προτύπου για νιφάδες χιονιού της pygame, αποθηκεύστε το στον φάκελλο με τα έργα σας και ανοίχτε το με το Thonny.

Θυμηθείτε ότι η random είναι μία βιβλιοθήκη έτσι πρέπει να την εισαγάγουμε πριν την χρησιμοποιήσουμε. Στην αρχή του κώδικα μας κάτω από την εντολή import pygame (γραμμή 7) γράψτε:

import random

Αν το υπόβαθρο είναι άσπρο αλλάξτε το σε μαύρο, αλλιώς δε θα μπορούμε να βλέπουμε τις άσπρες χιονινιφάδες στο άσπρο υπόβαθρο,

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