用 Python 代码编织一场数字雨

当窗外的雨丝敲打着玻璃,你是否想过用代码在屏幕上编织一场属于自己的数字雨?今天我们将借助 Python 的 Pygame 库,打造一场晶莹剔透的雨滴模拟动画。这段代码不仅是对自然现象的技术复现,更是一场让 0 和 1 化作雨丝的编程艺术之旅。

雨幕背后的编程逻辑

模拟真实雨滴需要把握三个关键要素:随机性、物理运动和视觉层次感。我们的程序就像一位雨幕导演,让 300 个 "雨滴演员" 在 800×600 的舞台上演绎下落、消失与重生的循环。每个雨滴都有独特的 "生命轨迹"—— 从屏幕上方随机诞生,以不同速度坠落,触及底部后又悄然回到起点,形成永不停歇的雨幕效果。


import pygame, random, sys

class Raindrop:
    def __init__(self, screen_width, screen_height):
        self.screen_width  = screen_width
        self.screen_height = screen_height
        self.reset()

    def reset(self):
        self.x      = random.randint(0, self.screen_width)
        self.y      = random.randint(-self.screen_height, 0)
        self.length = random.randint(5, 15)
        self.speed  = random.uniform(4, 10) * (self.length / 10)

    def fall(self):
        self.y += self.speed
        if self.y > self.screen_height:
            self.reset()

    def draw(self, surface):
        end_y = self.y + self.length
        pygame.draw.line(surface, (180, 180, 255), (self.x, self.y), (self.x, end_y), 1)

def main():
    pygame.init()
    screen_width, screen_height = 800, 600
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Python 雨滴模拟")
    clock = pygame.time.Clock()

    raindrops = [Raindrop(screen_width, screen_height) for _ in range(300)]

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill((10, 10, 30))

        for drop in raindrops:
            drop.fall()
            drop.draw(screen)

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
        

雨滴的 "生命循环" 解析

雨滴类的魔法

Raindrop 类就像雨滴的 "生命孵化器",每个雨滴对象都拥有独立的生命周期:

主循环的雨幕导演

主函数则是这场雨幕的总导演:

让雨幕更生动的视觉密码

程序在视觉呈现上暗藏巧思:

动手定制你的专属雨景

想要调整雨势大小?只需修改这几个参数:

当你运行这段代码,看着屏幕上流淌的数字雨,或许会感叹:原来代码也能如此诗意 —— 那些在屏幕上跳跃的坐标点,那些循环往复的逻辑判断,最终化作了一场触手可及的数字雨景。这正是编程的魅力:用理性的代码,创造感性的艺术。