简体   繁体   English

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

[英]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. 我想要一个按钮数组,只需更改其中的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]);
}

This is a demonstrative code with a false Button class, now you have to apply it to your code: 这是一个带有错误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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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