python实现字幕雨效果实现

1,185 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第27天,点击查看活动详情

先看最终实现的效果图: 在这里插入图片描述

使用python实现以上字幕雨效果,用到的主要库是pygame;

pygame不是内置模块,需要先安装一下:

安装pygame

安装方式推荐有很多种,推荐使用pip;

pip 是 Python 的包安装程序。其实,pip 就是 Python 标准库(The Python Standard Library)中的一个包,只是这个包比较特殊,用它可以来管理 Python 标准库(The Python Standard Library)中其他的包。pip 是一个命令行程序。 安装 pip 后,会向系统添加一个 pip 命令,该命令可以从命令提示符运行。

安装pip:

  • 安装python; 这个是必须安装的;

  • 下载pip:

    官网地址:pypi.org/project/pip…; 下载完毕后,解压

  • 打开命令行窗口,进入到pip解压后的目录;执行代码

    python3 setup.py install
    进行安装, 安装完成后,将pip加入到系统环境变量中

  • 验证 打开命令行窗口,输入pip list 或者pip3 list 在这里插入图片描述

以上只针对于windows系统,其他系统也可以参考;

  • 安装所需库: 打开命令行窗口,输入执行以下代码,并回车

    pip install pygame

    等待提示第三库安装成功既可;

开发思路:

  • 实例化窗口并设置窗口大小

pygame.init() resolution = width,height = 800,600 #设置窗口大小和标题 windowSurface = pygame.display.set_mode(resolution)

  • 定义字符列表,设置单个字的大小
str1 = "月光下的玉兰树,亭亭玉立,幽静而神秘,微风拂过,树影婆娑,树叶低喁,让人心静如水。月光下的玉兰花,透出淡淡的光晕,暗香泘动,令人心醉神迷。你可以揣个5G手机,避开嘈杂的人群,独自坐在玉兰树下的小石凳上,静静地聆听着花开的声音,在玉兰花的幽香里,挥洒小资情调,放纵思绪横飞。。"
    letter = list(str1)
    font_height = 15
    font = pygame.font.Font("c:\windows\Fonts\simhei.ttf", font_height)
    texts = [
            font.render(str(letter[i]), True, (0, 255, 0)) for i in range(len(letter))
    ]
  • 根据字符大小和窗口大小,计算出列数

column = int(width / font_height) drops = [0 for i in range(column)]

  • 循环每列,画出字符到屏幕
 for i in range(len(drops)):
            text = random.choice(texts)
            windowSurface.blit(text, (i * font_height, drops[i] * font_height))
            drops[i] += 1
            # 超过界面高度或随机数,下雨位置置0
            if drops[i] * font_height > height or random.random() > 0.95:
                drops[i] = 0
  • 实时更新屏幕

pygame.display.flip()

完整代码实现:

import pygame, sys,random

pygame.init()
width,height = 800,600 #设置窗口大小和标题
windowSurface = pygame.display.set_mode(resolution) #设置分辨率
pygame.display.set_caption("字符雨")#设置标题

if __name__ == '__main__':
    str1 = "月光下的玉兰树,亭亭玉立,幽静而神秘,微风拂过,树影婆娑,树叶低喁,让人心静如水。月光下的玉兰花,透出淡淡的光晕,暗香泘动,令人心醉神迷。你可以揣个5G手机,避开嘈杂的人群,独自坐在玉兰树下的小石凳上,静静地聆听着花开的声音,在玉兰花的幽香里,挥洒小资情调,放纵思绪横飞。。"
    letter = list(str1)
    font_height = 15
    font = pygame.font.Font("c:\windows\Fonts\simhei.ttf", font_height)
    texts = [
            font.render(str(letter[i]), True, (0, 255, 0)) for i in range(len(letter))
    ]

    column = int(width / font_height)
    drops = [0 for i in range(column)]
    bg_suface = pygame.Surface((width, height), flags=pygame.SRCALPHA)
    pygame.Surface.convert(bg_suface)
    bg_suface.fill(pygame.Color(0, 0, 0, 28))
    
    while True:
        pygame.time.delay(60)
        windowSurface.blit(bg_suface, (0, 0))
        for i in range(len(drops)):
            text = random.choice(texts)
            windowSurface.blit(text, (i * font_height, drops[i] * font_height))
            drops[i] += 1
            if drops[i] * font_height > height or random.random() > 0.95:
                drops[i] = 0
  

        pygame.display.flip()