foreach-if-语句w/ Linq条件给出意外结果

本文关键字:意外 结果 条件 Linq 语句 foreach-if- | 更新日期: 2023-09-27 17:53:20

这是井字游戏的一部分。checkmate方法返回一个字符串,该字符串将被另一个函数(此处未显示)用于执行井字棋。

这是棋盘,玩家有两个棋子排列在最上面一行:

public static char[] board = { '+', '+', 'E',
                               'A', 'S', 'D',
                               'Z', 'X', 'C' };

下面是决定下一步操作的代码:

private static string checkmate()
{      
    List<char[]> dalist = new List<char[]> 
    {
        new char[3] { board[3], board[4], board[5] },
        new char[3] { board[0], board[4], board[8] },
        new char[3] { board[2], board[4], board[6] },
        new char[3] { board[1], board[4], board[7] },
        new char[3] { board[0], board[1], board[2] },
        new char[3] { board[6], board[7], board[8] },
        new char[3] { board[0], board[3], board[6] },
        new char[3] { board[2], board[5], board[8] }
    };
    foreach (var item in dalist)
    {
        if (item.Where(x => x == '+').Count() == 2)
            return new string(item.Where(x => x != '+').ToArray());
        else if (item.Where(x => x == '-').Count() == 2)
            return new string(item.Where(x => x != '-').ToArray());
        else if (item.Where(x => x == '+').Count() == 1)
            return item.Where(x => x != '+').First().ToString();
        else
        {
            Random random = new Random();
            int rList = random.Next(0, 3);
            int rPosition = random.Next(0, 2);
            return dalist.ElementAt(rList).GetValue(rPosition).ToString();
        }
    }
    return "AA";
}

方法返回一个单独的字母作为字符串,对应于棋盘上的移动。

该方法通过创建一字棋中8种可能获胜的模式列表来分析棋盘,并将它们与棋盘上已有的模式进行测试

在foreach循环中按顺序作为ifelse条件工作的逻辑四个组件。对于当前,该方法应该在第一个if语句时返回'E'并中断循环。相反,程序通过整个循环并返回最后的else语句?为什么不识别第一个if条件的匹配?

循环应该遍历列表中的8个元素,直到找到匹配项。

1) checkmate,如果有一个可用的移动,它将返回获胜的移动

2)如果没有将死,这一步棋将检查对手是否有将死并阻塞路径

3) link two如果没有将死来赢得或阻止,这将放置第二个棋子连接到获胜路径

4) 将首字母随机放置在前两轮的四个角或中间之一

foreach-if-语句w/ Linq条件给出意外结果

您需要对所有可能的获胜步法执行每个单独的测试。并不是每次测试第一步获胜,然后每次测试第二步获胜,等等。因此,在每个测试周围包装一个for循环,如果没有任何循环找到匹配,则让随机块运行。

如果我理解正确,你认为第一个If语句应该是真的,因此函数应该返回。我猜你认为第一个item{'+' ,'+', 'E'}

但这是不正确的。第一个item{'A', 'S', 'D'},因为当您创建dalist时,第一个字符数组是{ board[3], board[4], board[5] }

编辑!

我现在看到你的函数保证在for-each循环的第一次迭代时返回,因为每个执行路径都有一个返回语句。所以它永远不会到达{'+' ,'+', 'E'}的行