Help with windows forms tool

2

What happens is that I must do a minesweeper of 300 squares, but I do not know with which tool to create the frame, could someone please tell me which tool will be useful to put the random code and that the game works for me? ? Thanks

    
asked by Marcela Real 14.04.2017 в 18:33
source

1 answer

1

One option is through the button control, here I leave the code as I would do it.

First I would make a method that allows me to generate the positions where the mines will be found

private int[] getMinas()
{
    int[] minas = new int[20]; //aquí pones cuantas minas quieres que hayan
    Random rand = new Random();
    for (int i = 0; i < 20; i++)
    {
        int pos = rand.Next(1, 301); //serían del 1 al 300
        if (!(minas.Contains(pos)))
            minas[i] = pos;
        else
            i--; //para repetir nuevamente que se ejecute un random para la posición actual, en caso de que haya salido una mina que ya existía.
    }
    return minas;
}

Then you have to make a method that will be triggered when you press the button to check if a mine is found or not

private void dynamicbutton_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            btn.Enabled = false; //desactivas el botón para que no lo vuelvan a presionar
            if (btn.Name.Contains("Mina")) //verificas sí el botón es de mina o no por su nombre, que fue asignado en el método que genera la matriz de minas.
            {
                //Salió una mina
                btn.Text = "X";
            }
            else
            {
                //No salió mina
            }
        }

Finally you make an array of dynamically generated buttons (here you can put a panel to add the matrix)

    private void GenerarMatrizBoton()
    {
        int[] minas = getMinas();
        int indice = 1;
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 30; j++)
            {
                Button btn = new Button();
                btn.Click += new System.EventHandler(dynamicbutton_Click);
                btn.Width = 20;
                btn.Height = 20;
                btn.Location = new Point((j * 20 + 10), (i * 20 + 30));
                if (minas.Contains(indice))
                    btn.Name = "Minas" + indice.ToString();
                else
                    btn.Name = "Libre" + indice.ToString();
                panel1.Controls.Add(btn);
                indice++;
            }
        }
    }
    
answered by 20.04.2017 в 17:33