原文取自公众号(安费诺传感器学堂)
# Python-3.11
import curses
import random
import time
import keyboard
def main(stdscr):
# 设置颜色,我们使用绿色
try:
curses.curs_set(0) #消除鼠标位置闪动
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) #表示定义了一个颜色对,编号为1,前景色是绿色,背景色是黑色
# 获取屏幕的高度和宽度:y为行数方向,x为列方向
height, width = stdscr.getmaxyx()
# 为了让屏幕不显得拥挤,获取所有偶数列作为输出列
# 上面的截图是每列都输出的形式
even_columns_List = list(range(0, width, 2))
# 生成一个列表位置列组
drops = [0]*width # width,定义多了,其实是为了方便偷懒
while True:
# 随机选列
column = random.choice(even_columns_List)
# 生成随机字符,并设置颜色
matrix_char = chr(random.randint(33, 126))
#'drops[column]`:字符的 y 坐标(行号)
#`column`:字符的 x 坐标(列号)
#`matrix_char`:要显示的字符
#`curses.color_pair(1)`:字符的颜色
stdscr.addch(drops[column], column, matrix_char, curses.color_pair(1))
# 刷新屏幕
stdscr.refresh()
# 当列已经达最低,或者随机选中,则重置鼠标位置到0
if drops[column] >= height-2 or random.choice([True] + [False]*18):
# 清除该列内容,填空
for k in range(height-1):
stdscr.addch(k, column, ' ')
# 列位置归零
drops[column] = 0
# 刷新屏幕
stdscr.refresh()
else:
drops[column] += 1
if keyboard.is_pressed('q'): # 如果按键 'q'其实很难检测到, 通过:Ctrl+C 停止运行
break # 结束循环
time.sleep(0.002) # 控制字幕显示及刷新的速度
except Exception as e:
print(e)
if __name__ == "__main__":
curses.wrapper(main)
其中,curses的插件下载,windows中下载安装方式:
pip install windows-curses
(此图是AI生成)