Skip to content

Instantly share code, notes, and snippets.

@zevtyardt
Created April 24, 2019 09:42
Show Gist options
  • Save zevtyardt/42d242f2568be62ab81337e7c49be100 to your computer and use it in GitHub Desktop.
Save zevtyardt/42d242f2568be62ab81337e7c49be100 to your computer and use it in GitHub Desktop.
ascii art with module curses
import random, string
import curses
import time
import re
import urllib
SLEEP = 0.05
def _ascii():
content = urllib.urlopen('http://www.asciiartfarts.com/random.cgi').read()
return '{}'.format(re.sub(r'&.*?;', '', re.findall(r'pre>(.*?)</pre>', content, re.S)[1]))
def _max_len_banner():
return max([len(line) for line in BANNER_TEXT.splitlines()]) + 4
def _lmx(win):
lebar_max_banner = _max_len_banner() / 2
tinggi_max_banner = len(BANNER_TEXT.splitlines()) / 2
tinggi_layar, lebar_layar = _getmax(win)
tinggi = tinggi_layar / 2 - tinggi_max_banner
lebar = lebar_layar / 2 - lebar_max_banner
return lebar_max_banner, tinggi_max_banner, lebar, tinggi
def _print_banner(win):
lebar_max_banner, tinggi_max_banner, lebar, tinggi = _lmx(win)
F = ' {0:<%s}' % (lebar_max_banner * 2 - 2)
for next, line in enumerate(BANNER_TEXT.splitlines(), start=1):
win.addstr(tinggi + next, lebar, F.format(line), curses.color_pair(3))
win.addstr(tinggi + next + 1, lebar, F.format(''), curses.color_pair(3))
win.refresh()
def _gentext(lebar):
chars = list(string.printable[:94])
return ''.join([random.choice(chars) for _ in range(lebar - 2)])
def _getmax(win):
return win.getmaxyx()
def _print(win, kwargs):
lebar_max_banner, tinggi_max_banner, lebar, tinggi = _lmx(win)
for (line, pos, color), text in kwargs.items():
if line in range(tinggi, tinggi + tinggi_max_banner):
win.addstr(line, pos, text[:lebar], curses.color_pair(color))
win.addstr(' ' * (lebar_max_banner * 2 - 2), curses.color_pair(0))
win.addstr(text[lebar + (lebar_max_banner * 2 - 2):], curses.color_pair(color))
else:
win.addstr(line, pos, text, curses.color_pair(color))
win.refresh()
def _move(kwargs):
rev = {}
for (line, pos, color), text in kwargs.items():
if line > 2:
rev[(line - 1, pos, color)] = text
return rev
def main(win):
_ = {}
tinggi = _getmax(win)[0] - 2
lebar = _getmax(win)[1] - 2
while True:
win.nodelay(1)
_[(len(_) + 2, 2, random.randrange(0, 256))] = _gentext(lebar)
if len(_) >= tinggi:
_ = _move(_)
_print(win, _)
_print_banner(win)
time.sleep(SLEEP)
win.refresh()
if __name__ == '__main__':
win = curses.initscr()
curses.curs_set(0)
curses.noecho()
curses.start_color()
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, i, -1)
while True:
BANNER_TEXT = _ascii()
if _max_len_banner() <= _getmax(win)[1] - 10:
break
try: main(win)
except Exception as e:
curses.endwin()
print '[critical] %s' % str(e)
except KeyboardInterrupt:
curses.endwin()
print '[error] user interrupt'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment