Digital Stream

Tags: tiny, artistic, beginner, scrolling

This program mimics the “digital stream” visualization from the science fiction movie The Matrix. Random beads of binary “rain” stream up from the bottom of the screen, creating a cool, hacker-like visualization. (Unfortunately, due to the way text moves as the screen scrolls down, it’s not possible to make the streams fall downward without using a module such as bext.)

digital_stream.py
 1"""Digital Stream, by Al Sweigart al@inventwithpython.com
 2A screensaver in the style of The Matrix movie's visuals.
 3This code is available at https://nostarch.com/big-book-small-python-programming
 4Tags: tiny, artistic, beginner, scrolling"""
 5
 6import random, shutil, sys, time
 7
 8# Set up the constants:
 9MIN_STREAM_LENGTH = 6  # (!) Try changing this to 1 or 50.
10MAX_STREAM_LENGTH = 14  # (!) Try changing this to 100.
11PAUSE = 0.05  # (!) Try changing this to 0.0 or 2.0.
12STREAM_CHARS = ['0', '1']  # (!) Try changing this to other characters.
13
14# Density can range from 0.0 to 1.0:
15DENSITY = 0.02  # (!) Try changing this to 0.10 or 0.30.
16
17# Get the size of the terminal window:
18WIDTH = shutil.get_terminal_size()[0]
19# We can't print to the last column on Windows without it adding a
20# newline automatically, so reduce the width by one:
21WIDTH -= 1
22
23print('Digital Stream, by Al Sweigart al@inventwithpython.com')
24print('Press Ctrl-C to quit.')
25time.sleep(2)
26
27try:
28    # For each column, when the counter is 0, no stream is shown.
29    # Otherwise, it acts as a counter for how many times a 1 or 0
30    # should be displayed in that column.
31    columns = [0] * WIDTH
32    while True:
33        # Set up the counter for each column:
34        for i in range(WIDTH):
35            if columns[i] == 0:
36                if random.random() <= DENSITY:
37                    # Restart a stream on this column.
38                    columns[i] = random.randint(MIN_STREAM_LENGTH,
39                                                MAX_STREAM_LENGTH)
40
41            # Display an empty space or a 1/0 character.
42            if columns[i] > 0:
43                print(random.choice(STREAM_CHARS), end='')
44                columns[i] -= 1
45            else:
46                print(' ', end='')
47        print()  # Print a newline at the end of the row of columns.
48        sys.stdout.flush()  # Make sure text appears on the screen.
49        time.sleep(PAUSE)
50except KeyboardInterrupt:
51    sys.exit()  # When Ctrl-C is pressed, end the program.

https://inventwithpython.com/bigbookpython/project20.html