Snow雪花飘落效果

"""
简单的雪花飘落效果

比较卡的,可以用Sprite来改善?

Contributed to Python Arcade Library by Nicholas Hartunian

"""

import random
import math
import arcade

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Snow雪花飘落效果"

class Snowflake:
    """
    此类的实例代表一个雪花,用画圆形命令来显示.
    """
    def __init__(self):
        self.x = 0
        self.y = 0

    def reset_pos(self):
        # 重置雪花坐标
        self.y = random.randrange(SCREEN_HEIGHT, SCREEN_HEIGHT + 100)
        self.x = random.randrange(SCREEN_WIDTH)

class MyGame(arcade.Window):
    """ Main application class. """

    def __init__(self, width, height, title):
        """
        Initializer
        :param width:
        :param height:
        """
        # 调用父类方法新建窗口
        super().__init__(width, height, title)

        # 角色列表定义
        self.snowflake_list = None

    def start_snowfall(self):
        """ Set up snowfall and initialize variables. """
        self.snowflake_list = []

        for i in range(50):
            # 创建雪花实例
            snowflake = Snowflake()

            # 设置随机坐标
            snowflake.x = random.randrange(SCREEN_WIDTH)
            snowflake.y = random.randrange(SCREEN_HEIGHT + 200)

            # 设置雪花的其它属性
            snowflake.size = random.randrange(4)
            snowflake.speed = random.randrange(20, 40)
            snowflake.angle = random.uniform(math.pi, math.pi * 2)

            # 增加雪花到列表
            self.snowflake_list.append(snowflake)

        # 不显示鼠标指针
        self.set_mouse_visible(False)

        # 设置背景颜色
        arcade.set_background_color(arcade.color.BLACK)

    def on_draw(self):
        """
        Render the screen.
        """

        # 这个命令要在重绘其它对象之前运行
        arcade.start_render()

        # 画每个雪花
        for snowflake in self.snowflake_list:
            arcade.draw_circle_filled(snowflake.x, snowflake.y,
                                      snowflake.size, arcade.color.WHITE)

    def update(self, delta_time):
        """
        All the logic to move, and the game logic goes here.
        """
      
        # 遍历每片雪花,让它们往下移,角度也变化
        for snowflake in self.snowflake_list:
            snowflake.y -= snowflake.speed * delta_time

            # Check if snowflake has fallen below screen
            if snowflake.y < 0:
                snowflake.reset_pos()

            # Some math to make the snowflakes move side to side
            snowflake.x += snowflake.speed * math.cos(snowflake.angle) * delta_time
            snowflake.angle += 1 * delta_time


def main():
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
    window.start_snowfall()
    arcade.run()

if __name__ == "__main__":
    main()