This repository has been archived on 2025-09-28. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
terminal-rain/rain.py

59 lines
1.4 KiB
Python
Raw Normal View History

2021-06-11 20:57:37 +02:00
#!/usr/bin/env python3
'''
terminal-rain - rain.py
Copyright (c) 2021 Julian Müller (W13R)
License: MIT
'''
import os, random, sys, time
class Raindrop():
def __init__(self, posX):
self.posX = posX
self.posY = 0
self.symbol = "|"
# array for the raindrops
raindrops = []
def generate_new_raindrops(n):
# generate n new raindrops per frame
for _ in range(n):
raindrops.append(Raindrop(random.randint(1, 1000) % (width + 1)))
def remove_old_raindrops(x, n):
# when there are more than x raindrops, delete the last n
if len(raindrops) > x:
for _ in range(n):
raindrops.pop(0)
def calculate_raindrop_locations():
# calculate the new position for every raindrop
for elem_ in raindrops:
if elem_.posY <= height - 1:
elem_.posY += 1
else:
elem_.symbol = "_"
def write():
# clear the screen
sys.stdout.write("\u001b[2J")
# write the raindrops to the terminal
for elem_ in raindrops:
sys.stdout.write(f"\u001b[{elem_.posY};{elem_.posX}f")
sys.stdout.write(elem_.symbol)
sys.stdout.write(f"\u001b[H")
# flush the changes to the terminal
sys.stdout.flush()
while True:
width, height = os.get_terminal_size()
generate_new_raindrops(3)
remove_old_raindrops(230, 3)
calculate_raindrop_locations()
write()
time.sleep(0.032)