分享

用 Python 实现黑客帝国中的数字雨落既视感

 Python技术 2021-06-17

来源:Python 技术「ID: pythonall」

说起黑客帝国,相信大家即使没看过系列影片也应该会听过这个名字,该系列最新一部是 2003 年上映的,距现在已经有 10 几年了,如果大家看过影片的话,应该会对里面的数字雨有印象。

如果你没看过影片不了解数字雨是什么样的也没关系,我放一张图你就知道了。

就是上图那个样子,本文我们就使用 Python 来实现这个效果,当然这个不局限于数字,也可以是字母、图形等。

数字雨

代码的实现还是比较简单,基本就是使用 pygame 库创建窗口,再定义数字的生成并让其不断的在窗口上面显示,代码实现如下所示:

import random, pygame

FONT_PX = 15
pygame.init()
winSur = pygame.display.set_mode((500600))
font = pygame.font.SysFont('fangsong'20)
bg_suface = pygame.Surface((500600), flags=pygame.SRCALPHA)
pygame.Surface.convert(bg_suface)
bg_suface.fill(pygame.Color(00013))
winSur.fill((000))
# 数字
texts = [font.render(str(i), True, (02550)) for i in range(10)]
colums = int(500 / FONT_PX)
drops = [0 for i in range(colums)]
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
    pygame.time.delay(33)
    winSur.blit(bg_suface, (00))
    for i in range(len(drops)):
        text = random.choice(texts)
        winSur.blit(text, (i * FONT_PX, drops[i] * FONT_PX))
        drops[i] += 1
        if drops[i] * 10 > 600 or random.random() > 0.95:
            drops[i] = 0
    pygame.display.flip()

我们来看一下实现效果:

是不是有内味了。

字母雨

我们要实现的字母雨和数字雨的实现基本差不多,主要就是把数字换成了字母,代码实现如下所示:

import random, pygame

PANEL_width = 400
PANEL_highly = 500
FONT_PX = 15
pygame.init()
# 创建一个窗口
winSur = pygame.display.set_mode((PANEL_width, PANEL_highly))
font = pygame.font.SysFont('123.ttf'22)
bg_suface = pygame.Surface((PANEL_width, PANEL_highly), flags=pygame.SRCALPHA)
pygame.Surface.convert(bg_suface)
bg_suface.fill(pygame.Color(00028))
winSur.fill((000))
letter = ['q''w''e''r''t''y''u''i''o''p''a''s''d''f''g''h''j''k''l''z''x''c',
          'v''b''n''m']
texts = [
    font.render(str(letter[i]), True, (02550)) for i in range(26)
]
# 按窗口的宽度来计算可以在画板上放几列坐标并生成一个列表
column = int(PANEL_width / FONT_PX)
drops = [0 for i in range(column)]
while True:
    # 从队列中获取事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        elif event.type == pygame.KEYDOWN:
            chang = pygame.key.get_pressed()
            if (chang[32]):
                exit()
    # 暂停给定的毫秒数
    pygame.time.delay(30)
    # 重新编辑图像
    winSur.blit(bg_suface, (00))
    for i in range(len(drops)):
        text = random.choice(texts)
        # 重新编辑每个坐标点的图像
        winSur.blit(text, (i * FONT_PX, drops[i] * FONT_PX))
        drops[i] += 1
        if drops[i] * 10 > PANEL_highly or random.random() > 0.95:
            drops[i] = 0
    pygame.display.flip()

我们来看一下实现效果:

图形雨

除了数字和字母,我们还可以使用图片,图片我们就用福字吧,上面我们是利用 pygame 库来创建窗口的,这次我们使用 tkinter 库,来看一下具体实现代码:

from tkinter import *
import random, threading, time, os

# 初始雨滴纵坐标
INIT_HEIGHT = 1
# 雨滴创建
def rainmake(canvas, imagefile):
    rainlist = []
    for i in range(5):
        # 根据图片,创建一排福字
        rainlist.append(canvas.create_image(100 + 80 * i, INIT_HEIGHT, anchor=NE, image=imagefile))
    return rainlist

# 雨滴下落
def raindown(tk, canvas, imagefile, sec):
    # 线程间等待
    time.sleep(sec)
    rainlist = rainmake(canvas, imagefile)
    # 每个福字的纵坐标值
    height = [INIT_HEIGHT] * 10
    while True:
        # 每次移动前稍等一会
        time.sleep(0.2)
        # 5 个福字一起移动
        for i in range(5):
            # 如果福字到底了,则不继续移动
            if not height[i] == 0:
                # 设置下落步调
                rnd = random.randint(550)
                canvas.move(rainlist[i], 0, rnd)
                height[i] = height[i] + rnd
                tk.update()
        for i,h in enumerate(height):
            if h > 400:
                # 当福字走到最下方,则删除
                canvas.delete(rainlist[i])
                tk.update()
                # 清空该福的 height
                height[i] = 0
                print(i,h,height)
        # 全到底,则跳出循环
        if height == [0] * 5:
            print('break:',threading.current_thread().name)
            break

def lookloop(tk, canvas, thread):
    aliveflg = False
    while True:
        # 5s 检测一次
        time.sleep(5)
        for th in thread:
            if th.is_alive():
                aliveflg = True
            else:
                aliveflg = False
        if aliveflg == False:
            break
    canvas.create_text(100 , 200, text='雨停了...', fill='red')
    canvas.pack()
    time.sleep(5)
    tk.destroy()

def main():
    # 创建窗口对象
    tk = Tk()
    tk.title('送福雨')
    canvas_style = {
        'bg':'white',
        'height':'500',
        'width':'410',
        'cursor':'circle'
    }
    # 创建画布
    canvas = Canvas(tk,canvas_style)
    canvas.pack()
    # 图片素材
    if not os.path.exists('pic.gif'):
        raise Exception('pic.gif file does not exists.')
    imagefile = PhotoImage(file = 'pic.gif')
    thread = []
    for i in range(100):
       thread.append(threading.Thread(target=raindown, args=(tk, canvas, imagefile, i)))
    for t in thread:
        t.start()
    # 新开一个线程监控运行中的线程
    threading.Thread(target=lookloop, args=(tk, canvas, thread)).start()
    # 进入消息循环
    tk.mainloop()

我们来看一下实现效果:

总结

本文我们通过 Python 实现了数字、字母和图片的雨落效果,大家有兴趣的可以自己实现一下。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约