ZetCode

Pygame 矩阵数字雨动画

最后修改于 2025 年 2 月 25 日

Pygame 是一个强大的 Python 库,用于创建 2D 游戏和多媒体应用程序。在本教程中,我们将使用 Pygame 创建一个类似《黑客帝国》的数字雨动画。这种效果模仿了《黑客帝国》电影中看到的下落的绿色字符。

动画涉及渲染随机的片假名字符(绿色),它们像雨一样向下屏幕落下。背景逐渐淡化以产生拖尾效果。

设置动画

此示例演示了如何创建《黑客帝国》数字雨动画。

matrix_animation.py
import pygame
import random

# Initialize Pygame
pygame.init()

# Set up the display
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Matrix Digital Rain")

# Colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
FADE_ALPHA = 13  # Equivalent to rgba(0, 0, 0, 0.05) with 255 scale (0.05 * 255 ≈ 13)

# Font setup
FONT_SIZE = 13
font = pygame.font.SysFont("MS Gothic", FONT_SIZE)

def random_katakana():
    return chr(0x30A0 + int(random.random() * 96))

# Calculate columns based on screen width and font size
COLUMNS = WIDTH // FONT_SIZE

# Adjust font size if it's too big for the screen
if COLUMNS < 10:
    FONT_SIZE = 12
drops = [0] * COLUMNS  # Starting y-position for each column

# Create a surface for fading background
fade_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
fade_surface.fill((0, 0, 0, FADE_ALPHA))

# Game loop
clock = pygame.time.Clock()
running = True

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

    # Apply fading background
    screen.blit(fade_surface, (0, 0))

    # Draw and update drops
    for i in range(len(drops)):
        # Randomly select a character
        char = random_katakana()
        x = i * FONT_SIZE  # Calculate x position based on column index
        y = drops[i] * FONT_SIZE  # Calculate y position based on drop position

        # Render character in green with antialiasing
        text = font.render(char, True, GREEN)  # Antialiasing enabled
        text_rect = text.get_rect(topleft=(x, y))
        screen.blit(text, text_rect)

        # Increment drop position
        drops[i] += 1

        # Adjust the reset condition to be slightly more frequent
        if y > HEIGHT and random.random() > 0.95:
            drops[i] = random.randint(-20, 0)
        # Reset drop if it goes off-screen with a small random chance
        if y > HEIGHT and random.random() > 0.975:
            drops[i] = 0

    # Update display
    pygame.display.flip()
    clock.tick(20)  # 20 FPS (~50ms interval like JS setInterval)

# Quit Pygame
pygame.quit()

该程序通过使用 random_katakana 函数生成随机片假名字符来模拟《黑客帝国》效果,这些字符随着其在 drops 列表中的位置更新而向下屏幕落下。一个半透明的黑色表面 fade_surface 通过在屏幕上混合来创建拖尾效果。程序还监听 QUIT 事件以优雅地退出。

drops 列表跟踪每列字符的垂直位置。fade_surface 通过在屏幕上混合一个半透明的黑色表面来创建淡化效果。

来源

Pygame 文档

在本文中,我们探讨了如何使用 Pygame 创建一个类似《黑客帝国》的数字雨动画。这种效果是学习 Pygame 中的渲染、事件处理和动画的好方法。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写超过 1,400 篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 Python 教程