Как вы назначаете значение случайной позиции в массиве? - PullRequest
0 голосов
/ 14 мая 2019

Я пытаюсь сделать игру «Сапер», и я хочу расположить бомбы и множество кнопок случайным образом

Пока мой код для массива кнопок выглядит так:

Я хочу иметь массив кнопок и просто изменить текст из 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 Ответ

1 голос
/ 14 мая 2019

Это демонстрационный код с ложным 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; }
}
...