Skip to content

Instantly share code, notes, and snippets.

@jsheedy
Last active March 30, 2022 19:47
Show Gist options
  • Save jsheedy/597a860948b09627bcf15ebe2f5a8727 to your computer and use it in GitHub Desktop.
Save jsheedy/597a860948b09627bcf15ebe2f5a8727 to your computer and use it in GitHub Desktop.
ansi grafx demo
import io
import itertools
import shutil
import sys
BLOCK = chr(9608)
ESC = "\x1b["
RST = ESC + "0m"
class IterFile:
"""given an iterator which yields strings,
return a file like object for reading those strings"""
def __init__(self, it):
self._it = it
self._f = io.StringIO()
def read(self, length=sys.maxsize):
try:
while self._f.tell() < length:
self._f.write(next(self._it))
finally:
self._f.seek(0)
data = self._f.read(length)
# save the remainder for next read
remainder = self._f.read()
self._f.seek(0)
self._f.truncate(0)
self._f.write(remainder)
return data
def move(i, j):
return ESC + f"{i};{j}H"
def color(i):
return ESC + f"38;5;{i}m"
def terminal_size():
return shutil.get_terminal_size()
pixels = [color(i) + BLOCK for i in range(256)]
columns, rows = terminal_size()
def draw(phase):
sys.stdout.write(move(0, 0))
pixel_gen = (pixels[(i + phase) % 256] for i in range(rows * columns))
f = IterFile(pixel_gen)
shutil.copyfileobj(f, sys.stdout)
if __name__ == "__main__":
for i in itertools.count():
draw(i)
@jsheedy
Copy link
Author

jsheedy commented Mar 30, 2022

ansi demo

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