我试图让我的“开始”按钮在图片顶部标记的所有4个框中生成一个颜色。颜色不应该相同。它应该像Lotto一样工作但是用Colors而不是数字。谁能告诉我我的代码有什么问题?
这就是我的代码;
}
private void buttonStart_Click(object sender, EventArgs e)
{
buttontest.BackColor = GetRandomColor();
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
Color RandomColor = GetRandomColor();
buttontest.BackColor = GetRandomColor();
buttontest.Refresh();
}
private Random random;
private void MainForm_Load(object sender, EventArgs e)
{
//Create a new instance of the random class
random = new Random();
}
private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
private void buttontest_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
buttontest.BackColor = Color.Red;
}
}
}
答案 0 :(得分:1)
你问题的答案是这样的:
Random random = new Random();
private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
private void btnStart_Click(object sender, EventArgs e)
{
button1.BackColor = GetRandomColor();
button2.BackColor = GetRandomColor();
button3.BackColor = GetRandomColor();
button4.BackColor = GetRandomColor();
}
但是我知道游戏MasterMind你想拥有一组特定的颜色。然后代码应该是这样的:
List<Color> possibleColors = new List<Color>()
{
Color.Red,
Color.Green,
Color.Gold,
Color.Blue
};
private Color GetRandomColorOfList()
{
return possibleColors[random.Next(0, possibleColors.Count)];
}
private void button5_Click(object sender, EventArgs e)
{
button1.BackColor = GetRandomColorOfList();
button2.BackColor = GetRandomColorOfList();
button3.BackColor = GetRandomColorOfList();
button4.BackColor = GetRandomColorOfList();
}
答案 1 :(得分:0)
您可以使用上面Michael Seidel建议的列表,并在点击Start
按钮时将其随机播放,例如,使用Fisher-Yates算法here。
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
List<Color> possibleColors = new List<Color>()
{
Color.Red,
Color.Green,
Color.Gold,
Color.Blue
};
private void button5_Click(object sender, EventArgs e)
{
possibleColors.Shuffle();
button1.BackColor = possibleColors[0];
button2.BackColor = possibleColors[1];
button3.BackColor = possibleColors[2];
button4.BackColor = possibleColors[3];
}