"""Hourglass, a scrolling terminal animation by Al Sweigart.""" import random, shutil, sys, time DELAY = 0.04 # Pause between rows in seconds. WIDTH = None # None uses the terminal width. GLASS_WIDTH, HALF_HEIGHT, DRAIN_RATE = 20, 10, 0.005 def get_width(width=None): result = shutil.get_terminal_size()[0] if width is None else width return result - 1 if sys.platform == 'win32' else result def hourglass(delay=DELAY, width=WIDTH): sand_level, cycle_phase = 1.0, 0 while True: current_width = get_width(width); center = current_width // 2 glass_width = min(GLASS_WIDTH, current_width // 3); cycle_length = 2 * HALF_HEIGHT + 3 position, row = cycle_phase % cycle_length, [' '] * current_width if position >= 2 * HALF_HEIGHT + 1: for dx in range(-glass_width, glass_width + 1): row[center + dx] = '=' elif position == HALF_HEIGHT: row[center] = '·' if sand_level > 0.01 else ' '; row[center - 1] = row[center + 1] = '|' elif position < HALF_HEIGHT: bulb_width = int(glass_width * (1 - position / HALF_HEIGHT * 0.85)) for dx in range(-bulb_width, bulb_width + 1): row[center + dx] = '|' if abs(dx) >= bulb_width - 1 else '▒' if position >= int((1 - sand_level) * HALF_HEIGHT) else ' ' else: bottom_row = position - HALF_HEIGHT - 1; bulb_width = int(glass_width * (bottom_row / HALF_HEIGHT * 0.85 + 0.15)); fill_line = int(sand_level * HALF_HEIGHT) for dx in range(-bulb_width, bulb_width + 1): row[center + dx] = '|' if abs(dx) >= bulb_width - 1 else '▒' if bottom_row >= fill_line else ':' if bottom_row == fill_line - 1 and random.random() < 0.3 else ' ' print(''.join(row)); time.sleep(delay); cycle_phase += 1 if cycle_phase >= cycle_length: cycle_phase = 0; sand_level -= DRAIN_RATE * cycle_length if sand_level <= 0: sand_level = 1.0 try: hourglass() except KeyboardInterrupt: print('Hourglass, by Al Sweigart al@inventwithpython.com')