Improve a conditional if

0

I would like to improve this code, I am creating a game three in a row and this is an example to determine the winner in the first row.

I would like to reduce it but it works the same.

This is the code:

if (((tablero[0] == tablero[3])&& (tablero[0] == tablero[6])&& (tablero[0] != 0))
                    || ((tablero[0] == tablero[6]) && (tablero[0] == tablero[3]) && (tablero[0] != 0))
                    || ((tablero[6] == tablero[3])&&(tablero[6]== tablero[0])&&(tablero[6]!=0))
                    || ((tablero[6] == tablero[0]) && (tablero[6] == tablero[3]) && (tablero[6] != 0))
                    || ((tablero[3] == tablero[0]) && (tablero[3] == tablero[6]) && (tablero[3] != 0))
                    || ((tablero[3] == tablero[6]) && (tablero[3] == tablero[0]) && (tablero[3] != 0)))
                    hay3enRaya = true;

The locations are like this: 0 3 6 - that represents the first row of the 3x3 matrix.

    
asked by Edwin Javier González Quintero 06.08.2018 в 17:59
source

1 answer

2

Taking into account a board with these positions and assuming that each box can take the value of 0 for empty , 1 for x and 2 for o (deducted from your code):

[0][1][2]      [x][ ][o]      [1][0][2]
[3][4][5]  ->  [o][x][ ]  ->  [2][1][0]
[6][7][8]      [x][ ][o]      [1][0][2]

As you know, a tic-tac-toe board has 8 possible solutions to win:

  • 3 vertical solutions
  • 3 horizontals and
  • 2 diagonals

You could implement this algorithm, nothing complex and easy to understand:

//soluciones horizontales
validar(0,1,2);
validar(3,4,5);
validar(6,7,8);

//soluciones verticales
validar(0,3,6);
validar(1,4,7);
validar(2,5,8);

//soluciones diagonales
validar(0,4,8);
validar(2,4,6);

public void validar(int a, int b, int c){
    //validas si no están vacíos
    if(tablero[a] != 0 && tablero[b] != 0 && tablero[c] != 0)
        // validas si son iguales
        if(tablero[a] == tablero[b] && tablero[b] == tablero[c])
                hay3enRaya = true;
}

Console.WriteLine(hay3enRaya);

There are more optimal ways to implement the validation algorithm for a tic-tac-toe, above all using recursion, but that is more applicable if you are interested in speed and performance in your solution.

    
answered by 06.08.2018 в 18:31