oryam
oryam

Reputation: 17

Check if won in Tic Tac Toe 2D array c#

Console App C#

I made a 2D array to represent a grid for the game. I cant find a way to check if the player has won. I tried many things and searched online and I cant find it I tried to loop thru the grid and check each one of the elements inside that row/column I would love to get the explanation of why its not working and how to do it instead of the code answer.

public static void Win_check()
{
    for (int i = 0; i < 3; i++)
    {
        if (grid[1, i] == 'x' && grid[1, i] == 'x' && grid[1, i] == 'x')
        {
            gameStatus = 'x';
        }

        if (grid[2, i] == 'o' && grid[2, i] == 'o' && grid[2, i] == 'o')
        {
            gameStatus = 'o';
        }

        if (grid[3, i] == 'o' && grid[3, i] == 'o' && grid[3, i] == 'o')
        {
            gameStatus = 'o';
        }

        if (grid[i, 1] == 'x' && grid[i, 1] == 'x' && grid[i, 1] == 'x')
        {
            gameStatus = 'x';
        }

        if (grid[i, 2] == 'o' && grid[i, 2] == 'o' && grid[i, 2] == 'o')
        {
            gameStatus = 'o';
        }

        if (grid[i, 3] == 'o' && grid[i, 3] == 'o' && grid[i, 3] == 'o')
        {
            gameStatus = 'o';
        }
            
    }
}

Upvotes: 0

Views: 583

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I suggest enumerating all the lines which bring win: 3 horizontal, 3 vertical and finally 2 diagonals.

private static IEnumerable<char[]> Lines(char[,] field) {
  char[] result;

  int size = Math.Min(field.GetLength(0), field.GetLength(1));

  for (int r = 0; r < size; ++r) {
    result = new char[size];

    for (int c = 0; c < size; ++c)
      result[c] = field[r, c];

    yield return result;
  }

  for (int c = 0; c < size; ++c) {
    result = new char[size];

    for (int r = 0; r < size; ++r)
      result[r] = field[r, c];

    yield return result;
  }

  result = new char[size];

  for (int d = 0; d < size; ++d)
    result[d] = field[d, d];

  yield return result;

  result = new char[size];

  for (int d = 0; d < size; ++d)
    result[d] = field[d, size - d - 1];

  yield return result;
}

Then you can easily query these lines with a help of Linq:

using System.Linq;

...

private static bool IsWon(char[,] field, char who) {
  return Lines(field).Any(line => line.All(item => item == who));
}

For instance:

  char[,] field = new char[,] {
    { 'x', 'o', 'o'},
    { 'x', 'o', ' '},
    { 'o', 'x', 'x'},
  };

  // Is field won by x?
  Console.WriteLine(IsWon(field, 'x') ? "Y" : "N");
  // Is field won by o?
  Console.WriteLine(IsWon(field, 'o') ? "Y" : "N");

Upvotes: 3

Related Questions