如何获得一定数量的随机颜色来填充网格-C#
本文关键字:颜色 填充 网格 -C# 随机 何获得 | 更新日期: 2023-09-27 18:22:16
我有一个7种颜色的列表:红色、蓝色、绿色、栗色、棕色、浅绿色和黑色。
在我的程序中,我有它,所以你点击一个框,然后这个框就会充满一种颜色。我希望每个盒子都是随机的颜色(从我的7种颜色列表中),我已经做到了以下几点:
Random random = new Random();
int randomColour = random.Next(0,6);
if (e.Button == MouseButtons.Left)
{
//got the y values of the grid
//got the x values of the grid
//Randomize The Colours
if (randomColour == 0)
{
Form.GetTile(x, y).FrontColour = Color.Red;
Score = Score + 1;
}
else if (randomColour == 1)
{
Form.GetTile(x, y).FrontColour = Color.Blue;
Score = Score + 2;
}
else if (randomColour == 2)
{
Form.GetTile(x, y).FrontColour = Color.Maroon;
Score = Score + 5;
}
else if (randomColour == 3)
{
Form.GetTile(x, y).FrontColour = Color.Aqua;
Score = Score + 10;
}
else if (randomColour == 4)
{
Form.GetTile(x, y).FrontColour = Color.Black;
Score = Score - 3;
}
else if (randomColour == 5)
{
Form.GetTile(x, y).FrontColour = Color.Brown;
Score = Score - 1;
}
else if (randomColour == 6)
{
Form.GetTile(x, y).FrontColour = Color.Green;
Score = Score + 3;
}
但是,我想设置我的代码,这样最多只能有20个红色框、20个蓝色框、5个绿色框、5个中棕色框、4个浅绿色框、五个栗色框和5个黑色框。
这应该是输出,除了更多的混洗。
Form.GetTile(x,y).FrontColor是我正在从另一个类访问的属性,它会更改方框的颜色
您可以预混洗要应用的数字列表
public class ShuffledChoices<T>{
private readonly List<T> Choices;
private Random rng = new Random();
public ShuffledChoices(IEnumerable<T> choices){
Choices = new List<T>(choices);
}
public T PickNext(){
var i = rng.Next(Choices.Count); // lock may not be a bad idea
var pick = Choices[i];
Choices.RemoveAt(i);
return i;
}
}
使用它:
var baseChoices = Enumerable.Repeat(Colors.Red, 20)
.Union(Enumerable.Repeat(Colors.Blue, 20))
.Union(Enumerable.Repeat(Colors.Green, 5))...;
var shuffledColors = new SuffledChoices<Color>(baseChoices);
...
if (e.Button == MouseButtons.Left){
Form.GetTile(x, y).FrontColour = shuffledColors.PickNext();
}
创建一个包含您自己颜色的字典,然后跟踪您选择颜色的次数
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("Red", 20);
dictionary.Add("Blue", 20);
dictionary.Add("Green", 5);
然后从字典中随机选择一个项目,并减去出现的
bool colourSelected = false;
do
{
var rnd = new Random();
var randomEntry = dictionary.ElementAt(rnd.Next(0, dictionary.Count));
String randomKey = randomEntry.Key;
String randomValue = randomEntry.Value;
if(randomvalue > 0)
{
// Take color
// could also add in logic to remove a color once it reaches 0,
// this way we don't select colors that are unavailable
dictionary[randomKey] = randomValue - 1;
colourSelected = true;
}
}
while(colourSelected == false);
代码可能需要一些工作,我根本没有运行它,所以可能有一些事情需要修复。