Skip to content

Instantly share code, notes, and snippets.

@ashafq
Last active March 27, 2022 01:12
Show Gist options
  • Save ashafq/297abbc3894ef8ca7450f1bc7e067a7c to your computer and use it in GitHub Desktop.
Save ashafq/297abbc3894ef8ca7450f1bc7e067a7c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
"""Display a rainbow color gradiant"""
from __future__ import print_function
from collections import namedtuple
__activity_ctx = 0.0
Color = namedtuple("Color", ["red", "green", "blue"])
def rainbow(seed=0, frequency=0.01):
"""Return a color"""
from math import sin, fmod, pi
qsin = lambda x: int((sin(x) * 127) + 128)
tau = 2.0 * pi
p0 = 0
p1 = (2.0 / 3.0) * pi
p2 = (4.0 / 3.0) * pi
phase = fmod(seed, tau)
dphase = tau * frequency
red = qsin(phase + p0)
green = qsin(phase + p1)
blue = qsin(phase + p2)
phase = fmod(phase + dphase, tau)
return Color(red, green, blue), phase
def rainbow_line(seed=0, width=80):
"""Draw a rainbow line"""
line = ""
for _ in xrange(width):
color, seed = rainbow(seed)
r, g, b = color
line += "\x1b[48;2;{};{};{}m ".format(r, g, b)
line += "\x1b[0m"
return line, seed
def show_activity(rows=4, cols=80):
"""Show some activity in console"""
from sys import stdout
global __activity_ctx
seed = __activity_ctx
if stdout.isatty():
line, seed = rainbow_line(seed, width=cols)
pline = "{}\n".format(line) * rows
print("{}\x1b[{}A".format(pline, rows), end="")
stdout.flush()
__activity_ctx = seed
else:
# Do nothing
pass
if __name__ == "__main__":
from time import sleep
try:
while True:
#show_activity(rows=8, cols=100)
show_activity(rows=26, cols=125)
sleep(0.1)
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment