我正在尝试在 C# 中创建 wordle。下面是我的代码,用于将用户输入转换为字符数组,以根据字母的位置更改每个字符的颜色
for (int i = 0; i < userGuessChars2D.GetLength(0); i++)
{
// Clear and re-display the board and increase guess number by 1
Console.Clear();
displayBoard();
guessNum++;
// Store user guess
userGuesses = Console.ReadLine().ToLower();
for (int j = 0; j < userGuessChars2D.GetLength(1); j++)
{
// Check if user input is included in answer and extra word list
if (answers.Contains(userGuesses) || extras.Contains(userGuesses))
{
userGuessChars2D[i, j] = userGuesses[j];
// Check the positioning of the letters and change the colour accordingly
if (userGuessChars2D[i, j] == answerChars2D[i, j])
{
Console.BackgroundColor = ConsoleColor.Green;
}
else if (userGuessChars2D[i, j] != answerChars2D[i, j])
{
Console.BackgroundColor = ConsoleColor.Red;
}
}
else
{
Console.WriteLine("Please enter a valid word");
}
}
}
无论我做什么,即使我输入了正确的单词,整个面板都返回红色。
有人知道我能做些什么来解决这个问题吗?
从提供的代码来看,看起来你在画板然后设置颜色。设置控制台颜色后需要写入控制台
// Check the positioning of the letters and change the colour accordingly
if (userGuessChars2D[i, j] == answerChars2D[i, j])
{
Console.BackgroundColor = ConsoleColor.Green;
// Write to the console now
Console.WriteLine(answerChars2D[i, j]);
// Optionally reset the console colour for future printing
Console.ResetColor();
}
else if (userGuessChars2D[i, j] != answerChars2D[i, j])
{
Console.BackgroundColor = ConsoleColor.Red;
// Write to the console now
Console.WriteLine(answerChars2D[i, j]);
// Optionally reset the console colour for future printing
Console.ResetColor();
}
你可能想进一步重构它以防止重复逻辑
public void Print(string answer, ConsoleColor color)
{
Console.BackgroundColor = color;
Console.WriteLine(answer);
Console.ResetColor();
}
// Use
Print(userGuessChars2d[i, j], ConsoleColor.Green);
您可以使用 ANSI 转义码。
最新版本的 OS Windows 支持它们。 控制台虚拟终端序列.
他们的用法是这样的:
const string RED = "\x1b[31m";
const string GREEN = "\x1b[32m";
const string UNDERLINE = "\x1B[4m";
const string RESET = "\x1B[0m";
Console.WriteLine(GREEN + "Success!" + RESET);
Console.WriteLine(RED + "Error!" + RESET);
Console.WriteLine("Some " + UNDERLINE + "underlined" + RESET + " text");
Console.WriteLine(RED + "Hello " + GREEN + "World!" + RESET);