"""A rotating, colorful ASCII Christmas
All rights reserved · mono
"""A rotating, colorful ASCII Christmas tree for the terminal."""
import argparse
import math
import random
import shutil
import sys
import time
from dataclasses import dataclass
RESET = "\033[0m"
TREE_HEIGHT = 6
COLORS = {
"green": "\033[32m",
"bright_green": "\033[92m",
"yellow": "\033[93m",
"red": "\033[91m",
"cyan": "\033[96m",
"magenta": "\033[95m",
"brown": "\033[33m",
"dim": "\033[2m",
"white": "\033[97m",
}
def make_tree():
points = []
for level in range(1, TREE_HEIGHT + 1):
radius = (TREE_HEIGHT + 1 - level) * 1.05
for sample in range(72):
angle = 2 * math.pi * sample / 72
branch_shape = 1 + 0.06 * math.cos(6 * angle + level * 0.5)
distance = radius * branch_shape
shade = "bright_green" if sample % 4 == 0 else "green"
points.append(
(
distance * math.cos(angle),
float(level),
distance * math.sin(angle),
"*" if sample % 13 == 0 else "^",
shade,
)
)
bulb_colors = ("red", "cyan", "yellow", "magenta")
bulbs = []
for level, y in enumerate((2, 3, 4, 5, 6)):
radius = (TREE_HEIGHT + 1 - y) * 1.05 * 0.88
for n in range(2):
angle = level * 1.7 + n * math.pi
bulbs.append(
(
radius * math.cos(angle),
y,
radius * math.sin(angle),
"o",
bulb_colors[(level + n) % len(bulb_colors)],
)
)
return points, bulbs
TREE, BULBS = make_tree()
@dataclass
class Snowflake:
x: float
y: float
speed: float
drift: float
phase: float
glyph: str
def make_snow(width, height, count=36):
glyphs = (".", "*", "+")
return [
Snowflake(
x=random.uniform(0, width - 1),
y=random.uniform(0, height - 2),
speed=random.uniform(2.0, 5.0),
drift=random.uniform(-0.4, 0.4),
phase=random.uniform(0, 2 * math.pi),
glyph=random.choice(glyphs),
)
for _ in range(count)
]
def update_snow(snowflakes, elapsed, width, bottom):
for flake in snowflakes:
flake.y += flake.speed * elapsed
flake.x += (
flake.drift + 0.45 * math.sin(flake.y * 0.7 + flake.phase)
) * elapsed
if flake.y >= bottom:
flake.x = random.uniform(0, width - 1)
flake.y = random.uniform(-4, -1)
flake.x %= width
def render_frame(angle, width=61, height=24, color=True, snowflakes=()):
grid = [[" "] * width for _ in range(height)]
depth = [[-math.inf] * width for _ in range(height)]
center_x = width // 2
ground = height - 7
horizontal_scale = min(1.7, max(0.7, (width - 4) / 16))
cos_angle = math.cos(angle)
sin_angle = math.sin(angle)
def put_screen(row, col, char, shade):
if 0 <= row < height - 1 and 0 <= col < width:
grid[row][col] = (char, shade)
def put(x, y, z, char, shade, force=False):
rotated_x = x * cos_angle + z * sin_angle
rotated_z = -x * sin_angle + z * cos_angle
col = center_x + round(rotated_x * horizontal_scale)
row = ground - round(y)
if 0 <= row < height - 1 and 0 <= col < width:
if force or rotated_z >= depth[row][col]:
grid[row][col] = (char, shade)
depth[row][col] = rotated_z
for x, y, z, char, shade in TREE:
put(x, y, z, char, shade)
for x, y, z, char, shade in BULBS:
put(x, y, z, char, shade, force=True)
star_row = max(0, ground - TREE_HEIGHT - 1)
if center_x < width:
grid[star_row][center_x] = ("*", "yellow")
for row in (ground, ground + 1):
if row < height - 1:
for col in range(max(0, center_x - 1), min(width, center_x + 2)):
grid[row][col] = ("|", "brown")
gifts = (
(-15, "red"),
(-4, "cyan"),
(7, "magenta"),
)
for offset, wrap_color in gifts:
left = center_x + offset
bow_row = ground + 2
for col, char in ((left + 3, "\\"), (left + 4, "*"), (left + 5, "/")):
put_screen(bow_row, col, char, "yellow")
for col, char in enumerate("+=======+"):
put_screen(bow_row + 1, left + col, char, wrap_color)
for col, char in enumerate("| | |"):
shade = "yellow" if char == "|" and col == 4 else wrap_color
put_screen(bow_row + 2, left + col, char, shade)
for col, char in enumerate("+---+---+"):
shade = "yellow" if char == "+" and col == 4 else wrap_color
put_screen(bow_row + 3, left + col, char, shade)
for flake in snowflakes:
put_screen(round(flake.y), round(flake.x), flake.glyph, "white")
lines = []
for row in grid:
line = []
for cell in row:
if isinstance(cell, tuple):
char, shade = cell
line.append(f"{COLORS[shade]}{char}{RESET}" if color else char)
else:
line.append(cell)
lines.append("".join(line).rstrip())
status = "Ctrl-C to stop | rotating ASCII Christmas tree"[:width]
if color:
status = f"{COLORS['dim']}{status}{RESET}"
lines[-1] = status
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--speed", type=float, default=1.0, help="rotation speed (default: 1.0)")
parser.add_argument("--fps", type=float, default=18.0, help="frames per second (default: 18)")
color_options = parser.add_mutually_exclusive_group()
color_options.add_argument("--color", action="store_true", help="force ANSI colors")
color_options.add_argument("--no-color", action="store_true", help="disable ANSI colors")
args = parser.parse_args()
if args.fps <= 0:
parser.error("--fps must be greater than zero")
terminal = shutil.get_terminal_size((61, 24))
width = max(20, terminal.columns)
height = max(20, terminal.lines)
use_color = args.color or (sys.stdout.isatty() and not args.no_color)
angle = 0.0
snowflakes = make_snow(width, height)
previous = time.monotonic()
sys.stdout.write("\033[2J\033[?25l")
try:
while True:
started = time.monotonic()
elapsed = min(started - previous, 0.1)
previous = started
angle += args.speed * elapsed
update_snow(snowflakes, elapsed, width, height - 1)
sys.stdout.write(
"\033[H" + render_frame(angle, width, height, use_color, snowflakes)
)
sys.stdout.flush()
time.sleep(max(0, 1 / args.fps - (time.monotonic() - started)))
except KeyboardInterrupt:
pass
finally:
sys.stdout.write("\033[0m\033[?25h\n")
sys.stdout.flush()
if __name__ == "__main__":
main()