"""Earthquake, a scrolling terminal animation by Al Sweigart.""" import math import random import shutil import sys import time # The number of character columns. None uses the terminal width. WIDTH = None # Calm rows before the first quake can begin. FIRST_QUAKE_MIN = 15 FIRST_QUAKE_MAX = 40 # Calm rows before later quakes can begin. NEXT_QUAKE_MIN = 30 NEXT_QUAKE_MAX = 80 # The proportion of quake intensity retained after each row. QUAKE_DECAY = 0.96 LAYERS = [(' ', 'sky'), ('~', 'grass'), ('.', 'soil'), (':', 'clay'), ('#', 'rock'), ('%', 'bedrock')] BASE_BOUNDARIES = [0.08, 0.15, 0.30, 0.50, 0.70, 1.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 earthquake(width=WIDTH): quake_intensity = 0.0 time_since_quake = 0 next_quake_in = random.randint(FIRST_QUAKE_MIN, FIRST_QUAKE_MAX) row_count = 0 while True: current_width = get_width(width) row = [] for x in range(current_width): noise = quake_intensity * random.uniform(-0.1, 0.1) wave = 0.02 * math.sin(x * 0.1 + row_count * 0.3) * (1 + quake_intensity * 5) fraction = x / current_width + noise + wave layer_char = LAYERS[-1][0] for index, boundary in enumerate(BASE_BOUNDARIES): if fraction < boundary: layer_char = LAYERS[index][0] break if quake_intensity > 0.3 and random.random() < quake_intensity * 0.1: layer_char = random.choice('*xX/\\') row.append(layer_char) if quake_intensity > 0.1: shift = int(quake_intensity * random.uniform(-4, 4)) if shift > 0: row = [' '] * shift + row[:current_width - shift] elif shift < 0: row = row[-shift:] + [' '] * (-shift) print(''.join(row[:current_width])) if quake_intensity > 0.5: delay = 0.01 elif quake_intensity > 0.1: delay = 0.03 else: delay = random.uniform(0.08, 0.15) time.sleep(delay) time_since_quake += 1 if time_since_quake >= next_quake_in and quake_intensity < 0.05: quake_intensity = random.uniform(0.6, 1.0) time_since_quake = 0 next_quake_in = random.randint(NEXT_QUAKE_MIN, NEXT_QUAKE_MAX) else: quake_intensity *= QUAKE_DECAY row_count += 1 try: earthquake() except KeyboardInterrupt: print('Earthquake, by Al Sweigart al@inventwithpython.com')