I am trying to make a tic tac toe game where the user inputs the dimensions and then a board is created with buttons. When a button is clicked, it is disabled and the text inside changes to "X" or "O" accordingly. The user plays against a very basic "AI" which picks the buttons at random.I'm trying to check for empty (enabled) buttons on the board but I get the error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
heres the code:
public partial class Form1 : Form{
   int num; 
   Button[,] buttonspinak;
   private void button2_Click(object sender, EventArgs e)
        {
            int start = 180, end = 30;
            num = Convert.ToInt32(textBox1.Text);
            buttonspinak = new Button[num, num];
                for (int i = 0; i < num; i++)
                {
                    end += 80;
                    start = 180;
                    for (int j = 0; j < num; j++)
                    {
                        Button b = new Button();
                        b.Size = new Size(60, 60);
                        b.Location = new Point(start, end);
                        this.Controls.Add(b);
                        start += 80;
                        b.BackColor = Color.White;
                        buttonspinak[i, j] = b;
                        b.Click += new EventHandler(Computer2);
                        Computer(sender, e);
                    }
                }
            }
   int countercomputer;
        Random randcompu = new Random();
        private void Computer(object sender, EventArgs e)
        {
            int randomi = 0;
            int randomj = 0;
            Button b = (Button)sender;
            b.Enabled = false;
            randomi = randcompu.Next(0, num);
            randomj = randcompu.Next(0, num);
            **while (buttonspinak[randomi, randomj].Text == "O" || buttonspinak[randomi, randomj].Text == "X")** // this is the line where i get the error
            {
                randomi = randcompu.Next(0, num);
                randomj = randcompu.Next(0, num);
                //buttonspinak[randomi, randomj].Text = "C";
            }
            buttonspinak[randomi, randomj].Text = "O";
            b_Elegxos();
        }
private void Computer2(object sender, EventArgs e)
    {
        countercomputer++;
        Button b = (Button)sender;
        b.Enabled = false;
        if (countercomputer % 2 != 0)
        {
            b.Text = "X";
            b.ForeColor = Color.DarkRed;
        }
        b_Elegxos();
    }
}
 
    