"""Tides, 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 # The rate at which the overall tide changes. TIDE_SPEED = 0.008 # The rate at which individual waves advance and recede. WAVE_SPEED = 0.12 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 tides(width=WIDTH): tide_phase = 0.0 wave_phase = 0.0 while True: current_width = get_width(width) row = [' '] * current_width tide = (math.sin(tide_phase) + 1) / 2 tide_reach = int(tide * current_width * 0.5) wave = (math.sin(wave_phase) + 1) / 2 wave_reach = tide_reach + int(wave * current_width * 0.15) for x in range(current_width): if x < tide_reach - 10: row[x] = '~' elif x < tide_reach: row[x] = '-' elif x < wave_reach: if x == wave_reach - 1: row[x] = '#' elif x == wave_reach - 2 and random.random() < 0.7: row[x] = '#' else: row[x] = '.' elif x < wave_reach + 3: row[x] = ':' if random.random() < 0.6 else '.' else: row[x] = ':' if random.random() < 0.15 else ' ' if random.random() < 0.02: gull_x = random.randint(0, current_width - 3) for index, char in enumerate('^v^'): row[gull_x + index] = char print(''.join(row)) wave_derivative = math.cos(wave_phase) if wave_derivative > 0.5: delay = 0.08 elif wave_derivative > -0.2: delay = 0.02 else: delay = 0.12 if abs(math.cos(tide_phase)) < 0.2: delay += 0.05 time.sleep(delay) wave_phase += WAVE_SPEED tide_phase += TIDE_SPEED try: tides() except KeyboardInterrupt: print('Tides, by Al Sweigart al@inventwithpython.com')