"""Rope, a scrolling terminal animation by Al Sweigart.""" import math import random import shutil import sys import time # The pause between rows in seconds; smaller values scroll faster. DELAY = 0.04 # The number of character columns. None uses the terminal width. WIDTH = None # The number of strands woven into the rope. NUM_STRANDS = 3 # Characters assigned to successive strands. STRAND_CHARS = 'O@#&%$' # The oscillation frequency that determines braid tightness. FREQUENCY = 0.15 # The initial strand amplitudes and their later evolving range. INITIAL_AMPLITUDE_MIN = 2.0 INITIAL_AMPLITUDE_MAX = 5.0 MIN_AMPLITUDE = 1.5 MAX_AMPLITUDE = 6.0 def get_width(width=None): result = shutil.get_terminal_size()[0] if width is None else width if sys.platform == 'win32': result -= 1 return result def rope(delay=DELAY, width=WIDTH, num_strands=NUM_STRANDS): strands = [] for index in range(num_strands): strands.append({ 'phase': index * math.tau / num_strands, 'char': STRAND_CHARS[index % len(STRAND_CHARS)], 'amp': random.uniform(INITIAL_AMPLITUDE_MIN, INITIAL_AMPLITUDE_MAX), 'freq': FREQUENCY, }) t = 0.0 while True: current_width = get_width(width) center = current_width // 2 row = [' '] * current_width positions = [] for index, strand in enumerate(strands): angle = strand['freq'] * t + strand['phase'] x = center + int(strand['amp'] * math.sin(angle)) positions.append((x, math.cos(angle), strand['char'], index)) positions.sort(key=lambda position: position[1]) for x, _depth, char, _index in positions: if 0 <= x < current_width: row[x] = char for offset in (-1, 1): nearby_x = x + offset if 0 <= nearby_x < current_width and row[nearby_x] == ' ': row[nearby_x] = '.' print(''.join(row)) t += 1 time.sleep(delay) if random.random() < 0.01: for strand in strands: strand['amp'] = random.uniform(MIN_AMPLITUDE, MAX_AMPLITUDE) try: rope() except KeyboardInterrupt: print('Rope, by Al Sweigart al@inventwithpython.com')