C#C
C#2y ago
427 replies
pikau

Defining and checking a 2D string array

Hey.

I am creating a tic tac toe board game with 3 rows and 3 columns (a 2D array). When I input, for example far more than 3 characters for a row into the console, it always returns that the board is valid. My isValid method is not working evidently. Im not sure if it is becuase of improper intiialisation of the board class, game class, or the method itself. Please let me know!

Board.cs relevant code:

    class Board
    {
        private char[,] board;

        /// <summary>
        /// Get whether the board is valid, i.e. the board is a 3x3 board with only 'X', 'O' and '.' characters
        /// and the number of 'X' is equal to or one more than the number of 'O'
        /// </summary>
        /// <returns>True if the board is valid, false otherwise</returns>
        /// 

        // Need to also make sure that the number of o is not 1 less than x as x goes first.
        public bool IsValid()
        {
            // CHeck if both the rows and column of the board are in 3x3
            if (board.GetLength(0) != 3)
                return false;
            else if (board.GetLength(1) != 3)
                return false;

            else return true;
        }

        /// <summary>
        /// Constructor of the Board class. Fill the 2D board of characters using the lines array of strings.
        /// </summary>
        /// <param name="lines">The array of strings to fill the 2D board of characters</param>
        public Board(string[] lines)
        {
            // Constructor that creates a 3x3 array of characters (char)
            board = new char[3, 3];

        }



Game.cs relevant code:
public class Game
{
    // Board field
    internal Board Board;

    // Constructor that takes in 3 strings that represents the board (this string is defined in program)
    public Game(string[] lines)
    {
        Board = new Board(lines);
    }



Relevant program.cs code: (cannot change this)
 Game game = new Game(lines);
if (game.Board.IsValid())
{
    Console.WriteLine($"Valid as hell");
    Console.WriteLine(game.HasWinner() ? $"The winner is: {game.GetWinner()}!" : "There is no winner!");
}
else
{
    Console.WriteLine("The board is invalid!");
}
Console.WriteLine("===========================");


Just looking for a bit of guidance!
Was this page helpful?