You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现Wordle时单个字符背景色设置异常求助

解决Wordle游戏输入正确单词却全显红色的问题

问题根源

你的代码里有三个关键错误导致了这个现象:

  1. 答案数组索引错误
    你用answerChars2D[i, j]来对比当前字符,但i是当前的猜测轮次(对应面板的行),而目标答案应该是固定的某一行(比如数组的第0行)。用i去索引答案数组的行,相当于每次都在和当前猜测行的"空答案"对比,自然全是红色。

  2. 控制台颜色未重置
    设置背景色后没有恢复默认颜色,会导致后续所有输出都继承这个颜色,视觉上看起来整个面板都是红色。

  3. 单词验证逻辑位置错误
    把单词有效性检查放在内层循环(遍历每个字符)里,会导致每个字符都重复判断一次单词是否有效,不仅冗余,还会多次弹出错误提示。

修复后的代码

for (int i = 0; i < userGuessChars2D.GetLength(0); i++)
{
    Console.Clear();
    displayBoard();
    guessNum++;

    // 先处理用户输入,确保是有效单词
    string userGuesses;
    bool isValid;
    do
    {
        userGuesses = Console.ReadLine().ToLower();
        isValid = answers.Contains(userGuesses) || extras.Contains(userGuesses);
        if (!isValid)
        {
            Console.WriteLine("Please enter a valid word");
            Console.WriteLine("Press any key to retry...");
            Console.ReadKey();
            Console.Clear();
            displayBoard();
        }
    } while (!isValid);

    // 遍历每个字符处理颜色和存储
    for (int j = 0; j < userGuessChars2D.GetLength(1); j++)
    {
        userGuessChars2D[i, j] = userGuesses[j];
        
        // 先重置为默认颜色
        Console.ResetColor();

        // 对比正确答案(这里假设答案存在answerChars2D的第0行,根据你的实际结构调整)
        char targetChar = answerChars2D[0, j];
        if (userGuessChars2D[i, j] == targetChar)
        {
            Console.BackgroundColor = ConsoleColor.Green;
        }
        // 补充Wordle的黄色规则:字母存在但位置不对
        else if (answerChars2D.Cast<char>().Contains(userGuessChars2D[i, j]))
        {
            Console.BackgroundColor = ConsoleColor.Yellow;
        }
        else
        {
            Console.BackgroundColor = ConsoleColor.Red;
        }

        // 输出当前字符
        Console.Write(userGuessChars2D[i, j]);
    }

    // 重置颜色,避免影响后续输出
    Console.ResetColor();
    Console.WriteLine();
}

额外说明

  • 原代码缺少Wordle核心的黄色背景逻辑,修复时补充了这部分,让游戏更贴合原版规则。
  • 把单词验证移到外层,用do-while循环确保用户输入有效单词后再处理字符,避免无效输入干扰面板渲染。
  • 每次输出字符前重置控制台颜色,防止颜色污染后续的面板内容。

内容的提问来源于stack exchange,提问作者12345678i9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:55:01