Skip to content

Instantly share code, notes, and snippets.

@seyed-dev
Created December 26, 2023 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seyed-dev/25fe81e3a93bbccc3f28d878bc35b5e3 to your computer and use it in GitHub Desktop.
Save seyed-dev/25fe81e3a93bbccc3f28d878bc35b5e3 to your computer and use it in GitHub Desktop.
Snowfall using Python code
import os
import sys
import time
import random
from math import sin
def get_terminal_size():
rows, columns = os.popen('stty size', 'r').read().split()
return int(rows), int(columns)
def snow():
h, w = get_terminal_size()
air = [[1] * h for _ in range(w)]
# Define the flakes with ANSI color escape codes
flakes = [
" ", # No color for empty space
" ", # No color for empty space
" ", # No color for empty space
" ", # No color for empty space
"\033[37m❆\033[0m", # White for *
"\033[34m❄\033[0m", # Blue for ❄
"\033[36m❅\033[0m", # Cyan for ❅
]
scsin = lambda t: (sin(t) / 2 + 0.5) * (0.1 / 3)
likelihood = lambda t: scsin(t) + scsin(t * 1.00001) + scsin(t * 0.9999)
try:
while True:
for x in range(w):
for y in range(h - 1, -1, -1):
if y == 0: # new flakes
air[x][y] = random.randint(2, len(flakes) - 1) if random.random() < likelihood(time.time()) else 1
elif y == h - 1: # accumulate bottom
air[x][y] = 2 if ((random.random() < 0.95 and air[x][y] > 1) or (air[x][y - 1] > 1 and random.random() < 0.2)) else 1
elif all(value == 1 for value in air[x][y:]): # melt pile sometimes
air[x][y] = 2 if random.random() < 0.95 else 1
elif air[x][y - 1] > 1 and all(value == 1 for value in air[x][y + 1:]): # if flake coming and piled up below
air[x][y] = 2 if random.random() < 0.1 else 1
else: # fall downwards otherwise
air[x][y] = air[x][y - 1]
# Clear the screen and print the snow
os.system('clear')
for y in range(h):
for x in range(w):
flake_index = min(air[x][y], len(flakes) - 1)
sys.stdout.write(flakes[flake_index])
sys.stdout.write('\n')
sys.stdout.flush()
time.sleep(1/8)
except KeyboardInterrupt:
pass
snow()
@seyed-dev
Copy link
Author

image

@rm-onata
Copy link

cute 😍

@antil0l
Copy link

antil0l commented Dec 26, 2023

def get_terminal_size():
    columns, rows = os.get_terminal_size()
    return int(rows), int(columns)

making it os agnostic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment