bcf48edc82d549c4438c6b752d2c7babf84c66dc
[rainbowstream.git] / rainbowstream / colors.py
1 import random
2 import itertools
3 from functools import wraps
4 from pyfiglet import figlet_format
5 from .config import *
6
7
8 def basic_color(code):
9 """
10 16 colors supported
11 """
12 def inner(text, bold=True):
13 c = code
14 if bold:
15 c = "1;%s" % c
16 return "\033[%sm%s\033[0m" % (c, text)
17 return inner
18
19
20 def RGB(code):
21 """
22 256 colors supported
23 """
24 def inner(text):
25 c = code
26 return "\033[38;5;%sm%s\033[0m" % (c, text)
27 return inner
28
29
30 default = basic_color('39')
31 black = basic_color('30')
32 red = basic_color('31')
33 green = basic_color('32')
34 yellow = basic_color('33')
35 blue = basic_color('34')
36 magenta = basic_color('35')
37 cyan = basic_color('36')
38 grey = basic_color('90')
39 light_red = basic_color('91')
40 light_green = basic_color('92')
41 light_yellow = basic_color('93')
42 light_blue = basic_color('94')
43 light_magenta = basic_color('95')
44 light_cyan = basic_color('96')
45 white = basic_color('97')
46
47 on_default = basic_color('49')
48 on_black = basic_color('40')
49 on_red = basic_color('41')
50 on_green = basic_color('42')
51 on_yellow = basic_color('43')
52 on_blue = basic_color('44')
53 on_magenta = basic_color('45')
54 on_cyan = basic_color('46')
55 on_grey = basic_color('100')
56 on_light_red = basic_color('101')
57 on_light_green = basic_color('102')
58 on_light_yellow = basic_color('103')
59 on_light_blue = basic_color('104')
60 on_light_magenta = basic_color('105')
61 on_light_cyan = basic_color('106')
62 on_white = basic_color('107')
63
64 colors_shuffle = [locals()[i.encode('utf8')] if not i.startswith('RGB_') else RGB(int(i[4:])) for i in c['CYCLE_COLOR']]
65
66 background_shuffle = [
67 on_grey,
68 on_light_red,
69 on_light_green,
70 on_light_yellow,
71 on_light_blue,
72 on_light_magenta,
73 on_light_cyan]
74 cyc = itertools.cycle(colors_shuffle[1:])
75
76
77 def order_rainbow(s):
78 """
79 Print a string with ordered color with each character
80 """
81 c = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
82 return reduce(lambda x, y: x + y, c)
83
84
85 def random_rainbow(s):
86 """
87 Print a string with random color with each character
88 """
89 c = [random.choice(colors_shuffle)(i) for i in s]
90 return reduce(lambda x, y: x + y, c)
91
92
93 def Memoize(func):
94 """
95 Memoize decorator
96 """
97 cache = {}
98
99 @wraps(func)
100 def wrapper(*args):
101 if args not in cache:
102 cache[args] = func(*args)
103 return cache[args]
104 return wrapper
105
106
107 @Memoize
108 def cycle_color(s):
109 """
110 Cycle the colors_shuffle
111 """
112 return next(cyc)(s)
113
114
115 def ascii_art(text):
116 """
117 Draw the Ascii Art
118 """
119 fi = figlet_format(text, font='doom')
120 print('\n'.join(
121 [next(cyc)(i) for i in fi.split('\n')]
122 )
123 )