提到编程,我想很多人的第一印象就是影片中的黑客形象,在黑色背景下敲击键盘,打出闪烁着绿光的字体,潜入破解一个个系统…
当然,真实情况与上述想象当然是毫不相干了,但是既然有了想象,为啥不去靠自己的尝试去实现一下呢?所以,我们这次就用非常简单的30行代码来实现一个代码雨的效果,满足一下我们的幻想和好奇心。
此次我们只是用pygame与random两个包,首先,将他们导入:
import pygame
import random
之后,我们进行pygame界面的初始化工作:
# 参数
SCREENSIZE=(600,600)
BLACK=(0,0,0,13)
# 初始化
pygame.init()
font = pygame.font.SysFont('宋体', 20)
screen = pygame.display.set_mode(SCREENSIZE)
surface = pygame.Surface(SCREENSIZE, flags=pygame.SRCALPHA)
pygame.Surface.convert(surface)
surface.fill(BLACK)
screen.fill(BLACK)
之后设置一下我们字体的相关内容:
# 内容
lib=[chr(i) for i in range(48,48+10)] + [chr(i) for i in range(97,97+26)] # [0-9 a-z]
texts = [font.render(l, True, (0, 255, 0)) for l in lib]
cols = list(range(40)) # 字体15, 窗口600
最后在一个循环中,更新界面并绘制出代码雨:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.time.delay(33)
screen.blit(surface, (0, 0))
for i in range(n:=len(cols)):
text = random.choice(texts)
# 绘制代码雨
screen.blit(text, (i * 15, cols[i] * 15))
cols[i] = 0 if cols[i] >80 or random.random() > 0.95 else cols[i]+1
pygame.display.flip()
import pygame
import random
# 参数
SCREENSIZE=(600,600)
BLACK=(0,0,0,13)
# 初始化
pygame.init()
font = pygame.font.SysFont('宋体', 20)
screen = pygame.display.set_mode(SCREENSIZE)
surface = pygame.Surface(SCREENSIZE, flags=pygame.SRCALPHA)
pygame.Surface.convert(surface)
surface.fill(BLACK)
screen.fill(BLACK)
# 内容
lib=[chr(i) for i in range(48,48+10)] + [chr(i) for i in range(97,97+26)] # [0-9 a-z]
texts = [font.render(l, True, (0, 255, 0)) for l in lib]
cols = list(range(40)) # 字体15, 窗口600
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.time.delay(33)
screen.blit(surface, (0, 0))
for i in range(n:=len(cols)):
text = random.choice(texts)
screen.blit(text, (i * 15, cols[i] * 15))
cols[i] = 0 if cols[i] >80 or random.random() > 0.95 else cols[i]+1
pygame.display.flip()