Added colors to shell and gameshell

This commit is contained in:
Patrick Marsee 2019-01-19 19:23:04 -05:00
parent 565b6ba903
commit ab5d01908e
4 changed files with 198 additions and 53 deletions

View file

@ -20,11 +20,14 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# Ver. 0.1.0017
# Ver. 0.1.0026
import types as _types
import traceback as _tb
import math as _math
_CONV24TO8 = 6 / 256
class Shell(object):
@ -33,8 +36,86 @@ class Shell(object):
self.__aliases = {}
self.ps1 = '> '
self.ps2 = '> '
self.colorMode = 0 # bits of color depth. Supports: 0, 3, 4, 8, 24
self.__exit = False
def __color24(self, r, g, b, fg = True):
if fg:
return '\x1b[38;2;{0};{1};{2}m'.format(r, g, b)
else:
return '\x1b[48;2;{0};{1};{2}m'.format(r, g, b)
def __color8(self, r, g, b, fg = True):
r = _math.floor(r * _CONV24TO8)
g = _math.floor(g * _CONV24TO8)
b = _math.floor(b * _CONV24TO8)
ret = 16 + b + 6 * g + 36 * r
if fg:
return '\x1b[38;5;{0}m'.format(ret)
else:
return '\x1b[48;5;{0}m'.format(ret)
def __color4(self, r, g, b, fg = True):
color = _math.floor(r / 128) + 2 * _math.floor(g / 128) + 4 * _math.floor(b / 128)
r2, g2, b2 = r % 128, g % 128, b % 128
if r2 + g2 + b2 >= 192:
color += 60
if fg:
color += 30
else:
color += 40
return '\x1b[{0}m'.format(color)
def __color3(self, r, g, b, fg = True):
color = _math.floor(r / 128) + 2 * _math.floor(g / 128) + 4 * _math.floor(b / 128)
if fg:
color += 30
else:
color += 40
return '\x1b[{0}m'.format(color)
def colorFromHex(self, color):
"""expects string formmatted like 3377DD"""
return int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16)
def color(self, r, g = 0, b = 0, fg = True):
if isinstance(r, str):
r, g, b = self.colorFromHex(r)
if self.colorMode == 0: # no color
return ''
elif self.colorMode == 3:
return self.__color3(r, g, b, fg)
elif self.colorMode == 4:
return self.__color4(r, g, b, fg)
elif self.colorMode == 8:
return self.__color8(r, g, b, fg)
elif self.colorMode == 24:
return self.__color24(r, g, b, fg)
else:
return ''
def setColor(self, r, g = 0, b = 0, fg = True):
"""Set the text color."""
if isinstance(r, str):
r, g, b = self.colorFromHex(r)
if self.colorMode == 0: # no color
return
elif self.colorMode == 3:
print(self.__color3(r, g, b, fg), end = '')
elif self.colorMode == 4:
print(self.__color4(r, g, b, fg), end = '')
elif self.colorMode == 8:
print(self.__color8(r, g, b, fg), end = '')
elif self.colorMode == 24:
print(self.__color24(r, g, b, fg), end = '')
else:
return
return
def clearColor(self):
print('\x1b[0m', end = '')
return
def run(self):
"""The main game/shell loop"""
while not self.__exit: