Advertisement
Osiris1002

Digital Stream

Feb 18th, 2024
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. """Digital Stream, by Al Sweigart al@inventwithpython.com
  2. A screensaver in the style of The Matrix movie's visuals.
  3. This code is available at https://nostarch.com/big-book-small-python-programming
  4. Tags: tiny, artistic, beginner, scrolling"""
  5.  
  6. import random, shutil, sys, time
  7.  
  8. # Set up the constants:
  9. MIN_STREAM_LENGTH = 6  # (!) Try changing this to 1 or 50.
  10. MAX_STREAM_LENGTH = 14  # (!) Try changing this to 100.
  11. PAUSE = 0.1  # (!) Try changing this to 0.0 or 2.0.
  12. STREAM_CHARS = ['0', '1']  # (!) Try changing this to other characters.
  13.  
  14. # Density can range from 0.0 to 1.0:
  15. DENSITY = 0.02  # (!) Try changing this to 0.10 or 0.30.
  16.  
  17. # Get the size of the terminal window:
  18. WIDTH = 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:
  21. WIDTH -= 1
  22.  
  23. print('Digital Stream, by Al Sweigart al@inventwithpython.com')
  24. print('Press Ctrl-C to quit.')
  25. time.sleep(2)
  26.  
  27. try:
  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)
  50. except KeyboardInterrupt:
  51.     sys.exit()  # When Ctrl-C is pressed, end the program.
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement