C 控制台Tictactoe:检查获胜条件

C++ console TicTacToe: Checking Win Conditions

本文关键字:获胜 条件 检查 控制台 Tictactoe      更新时间:2023-10-16

游戏板被存储为2D char数组。玩家使用NUMPAD将光标移动到板上,并在光标的Enter键位置中进行选择。

每次移动后,使用以下方法对板进行胜利。

void checkwin()
{
    //look along lines from current position
    int x = cursorPosX;
    int y = cursorPosY;
    int c = playerTurn ? 1 : 2; //which mark to look for
    for (int xAxis = 0; xAxis <= 2; xAxis++) //look along x axis
    {
        x = WrapValue(0, sizeof(squares[0]), x + 1);
        if (CheckPos(x, y) != c) //if we don't find the same mark, must not be a horizontal line, otherwise, break out.
        {
            x = cursorPosX; //reset x
            for (int yAxis = 0; yAxis <= 2; yAxis++) //look along y axis
            {
                y = WrapValue(0, sizeof(squares[0]), y + 1);
                if (CheckPos(x, y) != c) 
                {
                    y = cursorPosY;
                    //look for diagonal
                    for (int i = 0; i <= 2; i++ )
                    {
                        x = WrapValue(0, sizeof(squares[0]), x + 1);
                        y = WrapValue(0, sizeof(squares[0]), y + 1);
                        if (CheckPos(x, y) != c)
                        {
                            //failed everything, return
                            winConditions = -1;
                            return;
                        }
                    }
                    break;
                }
            }
            break;
        }
    }
    //if we make it out of the loops, we have a winner.
    winConditions = playerTurn ? 0 : 1;
}

我弄错了结果 - 在不合适的情况下返回抽奖或获胜。我几乎可以肯定的是x和y在某个时候会得到错误的值,然后开始检查错误的斑点。

Visual Studio进入Yaxis循环后停止更新X和Y的手表 - 我不确定为什么,但它阻止了我跟踪这些值。我是否打破了有关在某个地方进行范围的规则?这是我使用x和y作为变量名称的唯一位置。

以下相关的包装方法。我的目的是始终能够通过添加来检查其他两个空间,无论我在董事会上的位置

int WrapValue(int min, int max, int value)
{
    auto range = max - min;
    while (value >= max)
    {
        value -= range;
    }
    while (value < min)
    {
        value += range;
    }
    return value;
}

我很高兴受过训练的眼睛告诉我我在这里做错了什么。非常感谢您的时间。

嵌套是一个可怕的想法。我通过将代码重构为多个单独的循环来解决问题,这些循环做了1件事,而不是彼此陷入更深层次的地狱级别。

for (int xAxis = 0; xAxis <= 2; xAxis++) //look along x axis
{
    x = WrapValue(0, sizeof(squares[0]), x + 1);
    if (CheckPos(x, y) != c) //if we don't find the same mark, must not be a horizontal line, otherwise, break out.
    {
        x = cursorPosX; //reset x
        break;
    }
    else if (xAxis == 2)
    {
        winConditions = playerTurn ? 0 : 1;
        return;
    }
}
for (int yAxis = 0; yAxis <= 2; yAxis++) //look along y axis
{
    y = WrapValue(0, sizeof(squares[0]), y + 1);
    if (CheckPos(x, y) != c)
    {
        y = cursorPosY;
        break;
    }
    else if (yAxis == 2)
    {
        winConditions = playerTurn ? 0 : 1;
        return;
    }
}
...ect

这违反了干燥,但它确实按照应该的方式工作,我相信我以后可以简化。

虽然我不完全确定为什么以前的方法不起作用,但我确实意识到这只是糟糕的设计。