The cold winter is coming. Is it snowing there? If not, let Python show you a snow

Posted by pjoshi on Sun, 26 Dec 2021 06:48:17 +0100

Introduction: did you see the snow this winter solstice? Xiaobian is always painting videos of northern children playing with snow these days! As a southern child, I really envy you~ 😭😭 Let alone rolling happily in the snow, Xiaobian seldom sees snowflakes all over the sky here.

Since God doesn't give me the chance to see snow, I'll make a snowflake myself and share it with tiezhimeng at the same time~

If you want to get more complete source code or Python learning materials, you can send me a private letter or click this line of font

Xiaobian thought of creating a dynamic artificial snowfall in Python. So there is the following content 👇👇

Effect preview:

Snow preview video in Python

Specific introduction

The implementation of the dynamic version mainly depends on the pygame module, from drawing to realizing dynamic movement. The initial idea was to replace the aircraft with the Koch snowflake drawn last time according to the idea of aircraft war. I tried it myself, and the effect was very poor. I found pygame through Baidu Draw module, similar to turtle. Of course, random is indispensable. I did it myself Python interview question [BAT version] (02) Chinese random is a frequent visitor. When learning, I think it is just a random number generation. Recently, I slowly came into contact with randmo and found that randmo is powerful. No wonder it has become a necessary test for the company's interview.

code implementation

Because the first step to use pygame is initialization:

import pygame
2import random
3#initialization
4pygame.init()

Load the background image and set the screen length and width according to the size of the background image:

1SIZE = (1000, 500)
2screen = pygame.display.set_mode(SIZE)
3pygame.display.set_caption("It's snowing")
4#Load bitmap
5background = pygame.image.load('snow.jpg')

Next, we need to define a snowflake list and initialize snowflakes. Here, we need to use random numbers to set the coordinates and speed of the xy axis.

random.randrange

random. Random number ([start], stop [, step]): obtain a random number from a set within a specified range that is incremented by a specified cardinality.

random.randint(a,b): used to generate an integer within a specified range. Where parameter a is the lower limit, parameter B is the upper limit, and the generated random number n: a < = n < = B.

# Define a snowflake list
2snow = []
3# Initialize snowflake
4for i in range(300):
5    x = random.randrange(0, SIZE[0])
6    y = random.randrange(0, SIZE[1])
7    speedx = random.randint(-1, 2)
8    speedy = random.randint(3,8)
9    snow.append([x, y, speedx, speedy])

Friends who have done airplane wars or are familiar with pygame should know that the next thing to do is to set up the game loop and draw the previously loaded background image.

The Surface object has a method called blit (), which draws bitmaps

screen.blit(space, (0,0))

The first parameter is the bitmap after loading, and the second parameter is the starting coordinate of drawing.

done = False
2while not done:
3    # Message event loop, judge exit
4    for event in pygame.event.get():
5        if event.type == pygame.QUIT:
6            done = True
7    #draw bitmap
8    screen.blit(background, (0,0))

 

This step is the most important to draw snowflakes and set the cycle of snowflakes list.

Drawing snowflakes uses pyGame Draw module, which is used to draw some simple graphics on the Surface, such as points, lines, rectangles, circles, arcs, etc. We draw snowflakes using:

pygame.draw.circle

Prototype: pyGame draw. circle(Surface, color, pos, radius, width=0): return Rect

Purpose: used to draw circles. The third parameter pos is the position coordinate of the center of the circle, and radius specifies the radius of the circle.

The width parameter indicates the width of the line (brush). If the value is set to 0, it means to fill the whole figure. The snowflake we draw is filled with white. The color parameter is usually an RGB triple (R, G, B).

The cycle of snowflake list mainly depends on the length of snowflake list. The position of moving snowflakes is also set. The program also makes a judgment that if snowflakes fall out of the screen when they move down from the top, the position will be reset.

# Snowflake list loop
 2    for i in range(len(snow)):
 3        # Draw snowflakes, color, position and size
 4        pygame.draw.circle(screen, (255, 255, 255), snow[i][:2], snow[i][3])
 5
 6        # Move snowflake position (next cycle takes effect)
 7        snow[i][0] += snow[i][2]
 8        snow[i][1] += snow[i][3]
 9
10        # If snowflakes fall off the screen, reset the position
11        if snow[i][1] > SIZE[1]:
12            snow[i][1] = random.randrange(-50, -10)
13            snow[i][0] = random.randrange(0, SIZE[0])

By this time, the program is basically finished. You only need to add the time to refresh the screen and the game exit statement.

pygame.display.flip()
2    clock.tick(20)
3
4pygame.quit()

 

End

That's the end of this snow sharing ~ like iron juice, remember the third consecutive! The support of family members is the biggest driving force for Xiaobian to update 🤞

Topics: Python Back-end Programmer