[英]How do you store the index position of a repeated keyword and store it in an array?
[英]How do you assign a value to a random position in an array?
我正在嘗試制作掃雷游戲,我想在炸彈上隨機放置炸彈並按一下按鈕
到目前為止,我的按鈕數組代碼如下所示:
我想要一個按鈕數組,只需更改其中的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]);
}
這是一個帶有錯誤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.