tl; dr在井字游戏中全部输出为蓝色,只希望x为蓝色,o为红色
在课堂上,我们正在尝试制作井字游戏,目前,我们正在尝试以仅X为蓝色而O为红色的方式修改代码,但是当我们导入colorama时,它会为所有输出着色。我知道所有文本都将以蓝色打印。因此从本质上来说,它应该看起来像: 我还提供了游戏代码。
import random
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
def print_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
print_board()
if (random.randint(1,2) == 1):
player_1_pick = input(player_1_pick + ", choose X or O: ").upper()
if (player_1_pick == "X"):
player_2_pick = "O"
while True:
x = input('Pick a number from 0-8')
x = int(x)
board[x] = 'X'
print_board()
然后,我们决定打开python的另一个选项卡(我们正在使用repl.it)来尝试在孤立的环境中解决此问题,我们在其中提出了以下建议:
import random
import colorama
from colorama import Fore, Style
def getPieceLabel(piece):
if (piece == 1):
return "|" + color.PURPLE + color.BOLD + "X" + color.END + "|"
elif (piece == 2 ):
return "|" + color.BLUE + color.BOLD + "O"
+ "|"
else:
return color.BOLD + "|_|" + color.END
board = ["_"] * 9
def print_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
print(Style.RESET_ALL)
while True:
x = input('Pick a number from 0-8')
x = int(x)
board[x] = 'X'
print_board()
我们需要一些帮助来解决这个问题/问题所在。
答案 0 :(得分:1)
这是一个代码,可为不同的项目打印不同的颜色(也在repl.it上测试!)。
import random
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Tic Tac Toe")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.BLUE + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.RED + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print() # new line
print_board()
if (random.randint(1,2) == 1):
player_1_pick = input(player_1_pick + ", choose X or O: ").upper()
if (player_1_pick == "X"):
player_2_pick = "O"
while True:
x = input('Pick a number from 0-8: ')
x = int(x)
board[x] = 'X'
print_board()
为什么??当您使用Back.RED
或Fore.RED
时,它只会更改全局输出颜色(而不仅仅是特定的print()
语句)。这意味着,如果您希望每个打印项目使用不同的颜色,则必须更改它们的颜色。这就是我在print_board()
下所做的。
由于您要打印3x3矩阵(或2D数组)以及元素或项目之间的边界,因此我不得不利用两个循环将它们分别打印为不同的颜色(根据需要)。
注意:该程序有效,但我认为缺少一些逻辑,因为该游戏仅适用于第一个玩家。没有第二个播放器(甚至系统播放器)。这超出了此答案的范围。