This Python script simulates the iconic digital rain from The Matrix in your terminal using the curses
library. Green characters cascade down your screen, and press any key to exit the mesmerizing effect.
Click to view script…
import curses
import random
import time
def matrix_rain(stdscr):
# Hide the cursor and set non-blocking input
curses.curs_set(0)
stdscr.nodelay(True)
stdscr.timeout(50)
# Initialize colors if supported
if curses.has_colors():
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
sh, sw = stdscr.getmaxyx() # Get screen height and width
# Initialize each column with a random starting row
columns = [random.randint(0, sh - 1) for _ in range(sw)]
while True:
stdscr.erase() # Clear the screen for fresh drawing
for x in range(sw):
y = columns[x]
# Generate a random printable ASCII character
char = chr(random.randint(33, 126))
try:
if curses.has_colors():
stdscr.addch(y, x, char, curses.color_pair(1))
else:
stdscr.addch(y, x, char)
except curses.error:
# Ignore errors when drawing outside of the screen bounds
pass
# Move the column down; reset to the top if at the bottom
columns[x] = y + 1 if y < sh - 1 else 0
stdscr.refresh()
time.sleep(0.05) # Adjust the speed of the rain
# Exit the loop if any key is pressed
if stdscr.getch() != -1:
break
def main():
curses.wrapper(matrix_rain)
if __name__ == '__main__':
main()