I'm working on a little text-based adventure in Python 3.2 as I learn it in order to practise and become more familiar with the language. Anyway, I want to make it so that when certain actions happen, the color of the print text changes. How do I do this.
For example, the first text I want this to occur for is:
if 'strength' in uniqueskill.lower():
time.sleep(3)
print('As you are a Warrior, I shall supply you with the most basic tools every Warrior needs.')
time.sleep(3)
print('A sword and shield.')
time.sleep(1)
print('You have gained A SWORD AND SHIELD!')
Colorama is a great fully cross platform module for printing to the terminal/command line in different colours.
Example:
import colorama
from colorama import Fore, Back, Style
colorama.init()
text = "The quick brown fox jumps over the lazy dog"
print(Fore.RED + text)
print(Back.GREEN + text + Style.RESET_ALL)
print(text)
Gives you:
You didn't specify your platform, which is quite important here, since most methods for outputting color text to console are platform specific. The curses library which comes with Python, for instance, is UNIX-only, and ANSI codes, don't work on new versions of Windows anymore. The most cross platform solution I can think of, is to install the Windows version of curses on Windows machines and use it.
Here's an example for using color with curses:
import curses
# initialize curses
stdscr = curses.initscr()
curses.start_color()
# initialize color #1 to Blue with Cyan background
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_CYAN)
stdscr.addstr('A sword and a shield.', curses.color_pair(1))
stdscr.refresh()
# finalize curses
curses.endwin()
Please note that curses is more complex than just having colors. You can use it to define several windows on the console screen, position text using absolute or relative coordinates, manipulate keyboard input and so on. You can find a tutorial here: http://docs.python.org/dev/howto/curses.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With