-1

I'm trying to make a tic tac toe game in c# and i'm having problems at checking for the game over subprogram.

    int i, j;
        for (i = 0; i < 3; i++)
            for (j = 0; j < 3; j++)
            {
                b[i, j] = new Button();
                b[i, j].ForeColor = Color.Gray;
                b[i, j].Location = new Point((i * 100) + 25 - i * 10, (j * 100) + 25 - j * 10);
                b[i, j].Size = new Size(60, 60);
                b[i, j].Click += new EventHandler(b_Click);
                b[i, j].Font = new Font("Goudy Old Style", 25);
                this.Controls.Add(b[i, j]);
            }

Is it possible to send i, j through the b_click subprogram, for each button?(my game over subprogram work with the parameters i,j)

    private void b_Click(object sender, EventArgs e)
    {
        Button b =  (Button)sender ;
        if (tura)
            b.Text = Convert.ToString('X');
        else
            b.Text = Convert.ToString('O');
        tura = !tura;
        b.Enabled = false;
        nr_tura++;
        castigator(i,j);
    }
    private void castigator(int i,int j)
    {
        if (game_over(i, j) && tura)
            MessageBox.Show("A castigat X", "Game Over");
        else MessageBox.Show("A castigat O", "Game Over");
        if (nr_tura == 9)
            MessageBox.Show("Remiza", "Game Over");
    }

1 Answers1

1

You can use the Tag property of the button to keep a Point object with the specified i and j values of that button.
add this to the loop that creates the button: b[i, j].Tag = new Point(i, j);.
And inside the event handler just read them from there like this:

Point coordinates = (Point)((Button)sender).Tag;
i = coordinates.X;
j = coordinates.Y;
// ... the rest of your code
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121