对角和上下井字游戏算法C#Wpf

时间:2018-08-23 10:32:43

标签: c# visual-studio tic-tac-toe

所以我已经为Tic Tac Toe设定了横向胜利,但是我没有与其他人取得成功。

这是横向获胜的代码。

 private void CheckWinner(int row, int col)
    {
        if (aIntNaughtsCrosses[row, 0] == aIntNaughtsCrosses[row, 1])
        {
            if (aIntNaughtsCrosses[row, 0] == aIntNaughtsCrosses[row, 2])
            {
                MessageBox.Show("Yay");
            }

         }

aIntNaughtsCrosses是数组。

 else if(aIntNaughtsCrosses[col, 0] == aIntNaughtsCrosses[row, 0])
        {
            if(aIntNaughtsCrosses[col, 0] == aIntNaughtsCrosses[row, 0])
            {
                if(aIntNaughtsCrosses[col, 0] == aIntNaughtsCrosses[row, 1])
                {
                    if(aIntNaughtsCrosses[col, 0] == aIntNaughtsCrosses[row, 2])
                    {
                        MessageBox.Show("yay");
                    }
                }
            }


        }

这是我为垂直/向下获胜计划的代码。还将其应用于第1列和第2列。

1 个答案:

答案 0 :(得分:0)

水平方向正确,保持同一行并更改列。
现在,您必须保留同一列并更改行以检查垂直方向:

if (aIntNaughtsCrosses[row, 0] == aIntNaughtsCrosses[row, 1] && // horizontal
    aIntNaughtsCrosses[row, 0] == aIntNaughtsCrosses[row, 2] || // horizontal
    aIntNaughtsCrosses[0, col] == aIntNaughtsCrosses[1, col] && // vertical
    aIntNaughtsCrosses[0, col] == aIntNaughtsCrosses[2, col])   // vertical
{
    MessageBox.Show("Yay");
}

这意味着:

IF (row,0) equals (row,1) equals (row,2) OR   // horizontal
   (0,col) equals (1,col) equals (2,col) THEN // vertical
DISPLAY "Yay"

对于对角线,请注意只有2条对角线,您可以这样做(将aIntNaughtsCrosses缩短为arr):

if (col == row &&     // top-left to bottom-right
    arr[0, 0] == arr[1, 1] &&
    arr[0, 0] == arr[2, 2] ||
    col == 2 - row && // top-right to bottom-left
    arr[0, 2] == arr[1, 1] &&
    arr[0, 2] == arr[2, 0])
{
    MessageBox.Show("Yay");
}

这意味着:

IF (row,col) is in diag1 AND (0,0) equals (1,1) equals (2,2) OR   // diag1
   (row,col) is in diag2 AND (0,2) equals (1,1) equals (2,0) THEN // diag2
DISPLAY "Yay"

总而言之,以下应该起作用:

if (arr[row, 0] == arr[row, 1] && // horizontal
    arr[row, 0] == arr[row, 2] ||
    arr[0, col] == arr[1, col] && // vertical
    arr[0, col] == arr[2, col] ||
    col == row &&     // top-left to bottom-right
    arr[0, 0] == arr[1, 1] &&
    arr[0, 0] == arr[2, 2] ||
    col == 2 - row && // top-right to bottom-left
    arr[0, 2] == arr[1, 1] &&
    arr[0, 2] == arr[2, 0])
{
    MessageBox.Show("Yay");
}

这意味着:

IF (row,0) equals (row,1) equals (row,2) OR // horizontal 
   (0,col) equals (1,col) equals (2,col) OR // vertical
   (row,col) in diag1 AND (0,0) equals (1,1) equals (2,2) OR   // diag1
   (row,col) in diag2 AND (0,2) equals (1,1) equals (2,0) THEN // diag2
DISPLAY "Yay"