"""Sandstorm, 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.02 # The number of character columns. None uses the terminal width. WIDTH = None # The number of individual grains moving through the storm. NUM_PARTICLES = 60 # Characters used to draw grains, ordered from slower to faster. SAND_CHARS = '.,:;\'`' # The constant rightward wind added to the changing gusts. BASE_WIND = 1.5 def get_width(width=None): """Return the requested width or the current terminal width.""" result = shutil.get_terminal_size()[0] if width is None else width if sys.platform == 'win32': result -= 1 return result def sandstorm(delay=DELAY, width=WIDTH, num_particles=NUM_PARTICLES): """Display sand grains blowing across the screen in gusting wind.""" current_width = get_width(width) particles = [ {'x': random.randint(0, current_width - 1), 'speed': random.uniform(0.5, 3.0)} for _ in range(num_particles) ] t = 0.0 while True: current_width = get_width(width) row = [' '] * current_width gust = 3.0 * math.sin(t * 0.05) + 1.5 * math.sin(t * 0.13) effective_wind = BASE_WIND + gust for particle in particles: particle['x'] += ( particle['speed'] * effective_wind * 0.3 + random.uniform(-0.5, 0.5) ) if particle['x'] >= current_width: particle['x'] = 0 particle['speed'] = random.uniform(0.5, 3.0) elif particle['x'] < 0: particle['x'] = current_width - 1 particle['speed'] = random.uniform(0.5, 3.0) x = int(particle['x']) % current_width if row[x] == ' ': char_index = int(particle['speed'] / 3.0 * (len(SAND_CHARS) - 1)) char_index = max(0, min(len(SAND_CHARS) - 1, char_index)) row[x] = SAND_CHARS[char_index] # Strong gusts create occasional dense patches. if abs(gust) > 2.5: cluster_x = random.randint(0, current_width - 1) for offset in range(random.randint(2, 6)): x = (cluster_x + offset) % current_width if row[x] == ' ': row[x] = random.choice('.,') print(''.join(row)) t += 1 time.sleep(delay) try: sandstorm() except KeyboardInterrupt: print('Sandstorm, by Al Sweigart al@inventwithpython.com')