Falling Snow#
1"""
2Simple Snow
3Based primarily on:
4https://api.arcade.academy/en/latest/examples/sprite_collect_coins_move_down.html
5
6Contributed to Python Arcade Library by Nicholas Hartunian
7
8If Python and Arcade are installed, this example can be run from the command line with:
9python -m arcade.examples.snow
10"""
11
12import random
13import math
14import arcade
15
16SCREEN_WIDTH = 800
17SCREEN_HEIGHT = 600
18SCREEN_TITLE = "Snow"
19
20
21class Snowflake:
22 """
23 Each instance of this class represents a single snowflake.
24 Based on drawing filled-circles.
25 """
26
27 def __init__(self):
28 self.x = 0
29 self.y = 0
30
31 def reset_pos(self):
32 # Reset flake to random position above screen
33 self.y = random.randrange(SCREEN_HEIGHT, SCREEN_HEIGHT + 100)
34 self.x = random.randrange(SCREEN_WIDTH)
35
36
37class MyGame(arcade.Window):
38 """ Main application class. """
39
40 def __init__(self, width, height, title):
41 """ Initializer """
42 # Calls "__init__" of parent class (arcade.Window) to setup screen
43 super().__init__(width, height, title)
44
45 # Sprite lists
46 self.snowflake_list = None
47
48 def start_snowfall(self):
49 """ Set up snowfall and initialize variables. """
50 self.snowflake_list = []
51
52 for i in range(50):
53 # Create snowflake instance
54 snowflake = Snowflake()
55
56 # Randomly position snowflake
57 snowflake.x = random.randrange(SCREEN_WIDTH)
58 snowflake.y = random.randrange(SCREEN_HEIGHT + 200)
59
60 # Set other variables for the snowflake
61 snowflake.size = random.randrange(4)
62 snowflake.speed = random.randrange(20, 40)
63 snowflake.angle = random.uniform(math.pi, math.pi * 2)
64
65 # Add snowflake to snowflake list
66 self.snowflake_list.append(snowflake)
67
68 # Don't show the mouse pointer
69 self.set_mouse_visible(False)
70
71 # Set the background color
72 self.background_color = arcade.color.BLACK
73
74 def on_draw(self):
75 """ Render the screen. """
76
77 # This command is necessary before drawing
78 self.clear()
79
80 # Draw the current position of each snowflake
81 for snowflake in self.snowflake_list:
82 arcade.draw_circle_filled(snowflake.x, snowflake.y,
83 snowflake.size, arcade.color.WHITE)
84
85 def on_update(self, delta_time):
86 """ All the logic to move, and the game logic goes here. """
87
88 # Animate all the snowflakes falling
89 for snowflake in self.snowflake_list:
90 snowflake.y -= snowflake.speed * delta_time
91
92 # Check if snowflake has fallen below screen
93 if snowflake.y < 0:
94 snowflake.reset_pos()
95
96 # Some math to make the snowflakes move side to side
97 snowflake.x += snowflake.speed * math.cos(snowflake.angle) * delta_time
98 snowflake.angle += 1 * delta_time
99
100
101def main():
102 window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
103 window.start_snowfall()
104 arcade.run()
105
106
107if __name__ == "__main__":
108 main()