c# - 随机播放独特的图像并调用形成按钮-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
}
解决方案
如果我没有正确理解您,您希望随机播放,然后从列表中返回 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);
推荐阅读
- swagger - swagger端点的排序算法
- ruby-on-rails - 如何使用 Ruby on Rails 在 Paperclip 中制作具有 PNG 最大尺寸的版本
- java - 如何从片段中使用 Android Image Cropper
- java - JpaRepository getOne() 获取并更新整个对象
- amazon-web-services - 在基于 ARM 的实例上虚拟化多个 SBC
- sql - 如何在这个存储过程中插入 WHERE 语句?
- python - 被这个错误难住了:ValueError: min() arg is an empty sequence
- python - Tensorflow 未在 Python 3.6.9 上检测 GPU,但在 Python 2.7 上工作
- sql - 将具有逗号分隔值的列与其他列连接起来
- node.js - 在 updateOne 选项中传递会话与在 mongoose nodejs 中的 bulkWrite 选项中传递会话有什么区别