Ενότητα 6 - Τμήμα 1 - Επαναλήψεις και κινούμενα σχέδια
Ενότητα 6 - Τμήμα 1 - Επαναλήψεις και κινούμενα σχέδια
- δημιουργούν τυχαία κινούμενα σχήματα
- ξαναγράφουν τον κώδικα χρησιμοποιώντας βρόχους
- χρησιμοποιούν εμφωλευμένους βρόχους για συνεχή κίνηση
- προβλέψουν και να διορθώσουν τον κώδικα έτσι ώστε τα αντικείμενα να επανεμφανίζονται σε τυχαίες θέσεις
6.1.8 - Wind bursts
Next thing to do to create a realistic snow drop is to implement wind bursts. We will use our keyboard right and left buttons to blow the snowflakes.
Inside the main while loop of the program, we need to add some items to our event processing loop. In addition to looking for a pygame.QUIT event, the program needs to look for keyboard events. An event is generated each time the user presses a key.
A pygame.KEYDOWN event is generated when a key is pressed down. A pygame.KEYUP event is generated when the user lets up on a key. When the user presses the left key we will change the position of the the snowflake moving it to the left and moving it to the right when the user presses the right key.
The code that you have to copy to the main event loop is :
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
if event.key == pygame.K_LEFT:
for i in range(len(snow_list)):
snow_list[i][0] -= random.randrange(0,15)
elif event.key == pygame.K_RIGHT:
for i in range(len(snow_list)):
snow_list[i][0] += random.randrange(0,15)
With the above code we check if a key is pressed and after that if the key is LEFT or RIGHT we change the coordinates X of the snowflakes. It is not perfect but it is a start.
If we want to check other key presses or key releases then we can use the following code:
And if we wanted to use other keys there is a complete list of all the keys of the keyboard here.
The final script can be downloaded from here.