Skip to content

Instantly share code, notes, and snippets.

@nitori
Created July 3, 2024 18:29
Show Gist options
  • Save nitori/b69d9182690caff099f5a739f9ad3262 to your computer and use it in GitHub Desktop.
Save nitori/b69d9182690caff099f5a739f9ad3262 to your computer and use it in GitHub Desktop.
class Colors:
COLOR_NAMES = [
'black',
'red',
'green',
'yellow',
'blue',
'purple',
'cyan',
'white',
]
# RED, GREEN etc.
BG_COLOR_NAMES = [c.upper() for c in COLOR_NAMES]
def __format__(self, format_spec: str):
if format_spec == '':
return '\033[0m'
options = []
for part in format_spec.split(','):
if part in self.COLOR_NAMES:
options.append(f'3{self.COLOR_NAMES.index(part)}')
elif part in self.BG_COLOR_NAMES:
options.append(f'4{self.BG_COLOR_NAMES.index(part)}')
elif part in 'b+':
options.append('1')
elif part in 'i/':
options.append('3')
elif part in 'u_':
options.append('4')
elif part.startswith('#') and len(part) == 4:
options.append(f'38;2;{int(part[1:2] * 2, 16)};{int(part[2:3] * 2, 16)};{int(part[3:4] * 2, 16)}')
elif part.startswith('#') and len(part) == 7:
options.append(f'38;2;{int(part[1:3], 16)};{int(part[3:5], 16)};{int(part[5:7], 16)}')
elif part.startswith('##') and len(part) == 5:
options.append(f'48;2;{int(part[2:3] * 2, 16)};{int(part[3:4] * 2, 16)};{int(part[4:5] * 2, 16)}')
elif part.startswith('##') and len(part) == 8:
options.append(f'48;2;{int(part[2:4], 16)};{int(part[4:6], 16)};{int(part[6:8], 16)}')
else:
raise ValueError(f"Unknown format part: {part}")
return f'\033[{";".join(options)}m'
def main() -> None:
c = Colors()
print(f"To {c:red}fight{c:}, To {c:#f00}l{c:#f40}e{c:#f80}a{c:#fc0}r{c:#fff}n{c:}, "
f"To {c:b,u}become{c:} one with the {c:green}Matrix{c:}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment