如何在数组中使用termcolor使用Python打印不同的颜色?

我对python相当陌生,并且写了第二本书,因为我认为这是学习新语言的最佳方法.我的代码如下:

编码:

#!/usr/bin/env python

from random import randint
from termcolor import colored
import os
import sys
import time
clear = lambda : os.system('tput reset')

clear()

board = []

board_size=5

for x in range(board_size):
    board.append(["[W]"] * board_size)

def print_board(board):
    for row in board:
        print colored(" ".join(row),"cyan")

#print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board) +1
ship_col = random_col(board) +1

# Prints  where the ship is placed
# Do the right and don't cheat! 
# print ship_row
# print ship_col


print colored("\nNot bombed:      ","yellow") + colored("[W]","cyan")
print colored("Has been bombed: ","yellow") + colored("[","cyan") + colored("X","red") + colored("]\n","cyan")

guess_row = int(raw_input("Guess Row:")) 
guess_col = int(raw_input("Guess Col:"))

counter=0

state=True

while bool(state):

    counter=int(counter)+1

    if guess_row == ship_row and guess_col == ship_col:
        clear()
        print "\n\n  Congratulations! You sunk my battleship!\n\n"
        print "You got it right after " + str(counter) + " guesses."
        state=False
        time.sleep(2)
        clear()
        sys.exit()

    else:
        if (guess_row -1 < 0 or guess_row > board_size) or (guess_col -1 < 0 or guess_col > board_size):
            print "Oops, that's not even in the ocean."
            counter=int(counter)-1
            time.sleep(1)
            clear()

        elif(board[guess_row-1][guess_col-1] == "[X]"):
            print "You guessed that one already."
            counter=int(counter)-1
            time.sleep(1)
            clear()

        else:
            print "You missed my battleship!"
            clear()
            board[guess_row-1][guess_col-1] = "[X]"
            #counter=int(counter)+1


    print_board(board)

    print colored("\nNot bombed:      ","yellow") + colored("[W]","cyan")
    print colored("Has been bombed: ","yellow") + colored("[","cyan") + colored("X","red") + colored("]\n","cyan")

    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

我想,当用户猜到我只希望字母X为红色时(如键所暗示).

电流输出:

如何在数组中使用termcolor使用Python打印不同的颜色?

请注意,只有红色的“ X”和方括号是青色,这基本上是我想要在游戏中实现的目标.

理想输出:

如何在数组中使用termcolor使用Python打印不同的颜色?

题:

我怎样才能像上面那样打印?

解决方法:

问题代码为:

print colored(" ".join(row),"cyan")

你需要:

print ' '.join(colored(element, 'cyan') if element != 'X'
               else colored(element, 'red')
               for element in row)

编辑

通常,您可以根据字符查找颜色.一个通用的工具是使用Python的dict,它提供键和值之间的映射.

>>> color_key = {
...     'X': 'red',
...     'H': 'magenta'}
>>> color_key['X']
'red'

如果使用get,则可以为缺少的密钥提供默认值:

>>> color_key.get('[', 'cyan')
'cyan'

否则会引发异常:

>>> color_key['[']
...KeyError...

用法:

print ' '.join(colored(element, color_key.get(element, 'cyan')
           for element in row)
上一篇:Android发布错误:预期颜色资源ID(R.color.),但收到RGB整数


下一篇:python-在networkx中为步行边缘着色