简体   繁体   中英

How do you assign a value to a random position in an array?

I am trying to make a Minesweeper game and I want to randomly place bombs across and array of buttons

So far my code for the array of buttons looks like this:

I want to have an array of buttons and just change the text of 10 of them, selected at random to display a B or a background image of a bomb.

int horizontal = 270;
int vertical = 150;
Button[] buttonArray = new Button[81];
for (int i = 0; i < buttonArray.Length; i++)
{
    buttonArray[i] = new Button();
    buttonArray[i].Size = new Size(20, 20);
    buttonArray[i].Location = new Point(horizontal, vertical);

    if ((i == 8) || (i == 17) || (i == 26) || (i == 35) || (i == 53) || (i == 62) || (i == 71))
    {
        vertical = 150;
        horizontal = horizontal + 20;
    }
    else
        vertical = vertical + 20;

    this.Controls.Add(buttonArray[i]);
}

This is a demonstrative code with a false Button class, now you have to apply it to your code:

class Program
{
    private static Random Random = new Random();
    static void Main(string[] args)
    {
        Button[] buttons = new Button[81];

        //Code to initialize Buttons

        int[] indexes = GetNRandomIndexesBetweenInts(0, buttons.Length, 10);

        foreach (int index in indexes)
        {
            buttons[index].Text = "B";
        }
    }

    private static int[] GetNRandomIndexesBetweenInts(int min, int maxPlusOne, int nRandom)
    {
        List<int> indexes = Enumerable.Range(min, maxPlusOne).ToList();
        List<int> pickedIndexes = new List<int>();

        for (int i = 0; i < nRandom; i++)
        {
            int index = indexes[Random.Next(0, indexes.Count)];
            pickedIndexes.Add(index);
            indexes.Remove(index);
        }

        return pickedIndexes.ToArray();
    }
}

public class Button
{
    public string Text { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM