如何为数组中的随机位置分配值?

时间:2019-05-14 08:07:52

标签: c# arrays random insert assign

我正在尝试做一个扫雷游戏,我想在炸弹和按钮阵列中随机放置炸弹

到目前为止,我的按钮数组代码如下:

我想要一个按钮阵列,只需更改其中的10个按钮的文本,即可随机选择以显示B或炸弹的背景图像。

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]);
}

1 个答案:

答案 0 :(得分:1)

这是一个带有错误Button类的说明性代码,现在您必须将其应用于代码:

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; }
}