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

如何在数组中使用termcolor使用Python打印不同的颜色?,python,colors,terminal,Python,Colors,Terminal,我是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

我是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:"))
#/usr/bin/env python
从随机导入randint
从termcolor导入彩色
导入操作系统
导入系统
导入时间
clear=lambda:os.system('tput reset')
清除()
董事会=[]
电路板尺寸=5
对于范围内的x(电路板尺寸):
board.append([“[W]”]*板大小)
def打印板(板):
对于板中的行:
打印彩色(“.join(行),“青色”)
#打印“让我们玩战舰吧!”
印刷电路板
def随机_行(板):
返回randint(0,len(板)-1)
def随机_柱(板):
返回randint(0,len(板[0])-1)
船行=随机船行(板)+1
船列=随机船列(板)+1
#打印船放置的位置
#做正确的事,不要作弊!
#打印发货行
#打印船型
印刷彩色(\n未爆炸:,“黄色”)+彩色([W],“青色”)
印刷彩色(“已被轰炸:”,“黄色”)+彩色(“[”,“青色”)+彩色(“X”,“红色”)+彩色(“]\n”,“青色”)
猜测行=int(原始输入(“猜测行:”)
guess\u col=int(原始输入(“guess col:”)
计数器=0
状态=真
而布尔(州):
计数器=int(计数器)+1
如果guess\u row==ship\u row和guess\u col==ship\u col:
清除()
打印“\n\n祝贺你!你击沉了我的战舰!\n\n”
在“+str(计数器)+”猜测后打印“你得到了它。”
状态=假
时间。睡眠(2)
清除()
sys.exit()
其他:
如果(猜测行-1<0或猜测行>线路板大小)或(猜测列-1<0或猜测列>线路板大小):
打印“哦,那甚至不在海里。”
计数器=int(计数器)-1
时间。睡眠(1)
清除()
elif(董事会[guess\u row-1][guess\u col-1]==“[X]”):
打印“你已经猜到了。”
计数器=int(计数器)-1
时间。睡眠(1)
清除()
其他:
打印“你错过了我的战舰!”
清除()
电路板[GUSE\U row-1][GUSE\U col-1]=“[X]”
#计数器=int(计数器)+1
印刷电路板
印刷彩色(\n未爆炸:,“黄色”)+彩色([W],“青色”)
印刷彩色(“已被轰炸:”,“黄色”)+彩色(“[”,“青色”)+彩色(“X”,“红色”)+彩色(“]\n”,“青色”)
猜测行=int(原始输入(“猜测行:”)
guess\u col=int(原始输入(“guess col:”)
我想,当用户猜到我只想让字母X变成红色时,正如键所示

电流输出:

#!/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”是红色的,方括号是青色的,这基本上就是我想在游戏中实现的

理想输出:

#!/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:"))

问题:

#!/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:"))

如何使其按上述方式打印?

您需要更新打印板方法

def print_board(board):
    for row in board:
        print colored(" ".join(row),"cyan")
如果不编写您需要编写的确切代码,您需要将其更改为:

def print_board(board):
    for row in board:
        for each cell in the row:
            if it is a W:
                print it cyan
            if it is an X:
                print it in red
        move to a new line now
通常,当您打印时,它会换行,因此您需要签出 问题代码是:

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)

你能把这个问题归结到本质上来吗?查看如何询问如何增加条件的数量,例如“[H]”应为洋红色?我尝试了类似于
print.join(着色(元素,“青色”)if元素!=“[S]”else colored(元素,“绿色”)if元素!=“[X]”else colored(元素,“红色”)if元素!=“[H]”else colored(元素,“洋红色”)if元素行中的元素)
但它不起作用它不起作用的一个原因是
元素
是单个字符,而
'[S]'
是三个字符,因此永远不会匹配。