首页 > 解决方案 > 随机播放独特的图像并调用形成按钮-C#

问题描述

我正在用类构建一个扑克游戏。我有一个类图像,我想从字符串中加载图像,随机播放并返回唯一图像。之后我想将图像调用到 main 中的 5 个图片框。

这是在我的课上:

String[] img = Directory.GetFiles(@"...\...\cards");
List<int> deck = new List<int>();

public List<int> pachet1()
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    var lista = new List<int>();

    for (int i = 0; i < 52; i++)
    {
        deck.Add(i);
    }
    foreach (int a in deck)
    {
        int c = a;
        lista.Add(c);
    }
    return lista;
}

这主要是:

private void pictureBox_Click(object sender, EventArgs e)
{
    //here i want to call fucntion
}   

标签: c#

解决方案


如果我没有正确理解您,您希望随机播放,然后从列表中返回 5 个项目。

为此,您可以使用通用List shuffle扩展方法。

public static class MyExtensions
{
    public static void Shuffle<T>(this IList<T> list)
    {
        using (var provider = new RNGCryptoServiceProvider())
        {
            int n = list.Count;
            while (n > 1)
            {
                byte[] box = new byte[1];
                do provider.GetBytes(box);
                while (!(box[0] < n * (byte.MaxValue / n)));
                int k = (box[0] % n);
                n--;
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }
}

然后使用它来随机化列表并从列表中获取第一个n

public List<int> GetRandomItemsFromList(List<int>list, int amount)
{
    list.shuffle();
    return list.GetRange(0, amount);
}

它的用法是

List<int>items = GetRandomItemsFromList(list, 5);

推荐阅读