来自文件的随机图像,无需复制任何内容

时间:2016-10-11 18:29:36

标签: c#

你好扑克游戏吗?我从一个文件中随机调用我的卡,但我希望没有重复。例如,在同一只手中没有2个五个球杆,或者2个黑桃杰克。这基本上就是我一直在尝试做的事情,一旦完成,我的游戏应该完成 这是一些代码

string[] CardDisplay = new string[5];

    for (int i = 0; i < 5; i++)
    {
        CardDisplay[i] = getRandomImage();
    }

   PokerCard[0] = PokerCard1.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[0]);
   PokerCard[1] = PokerCard2.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[1]);
   PokerCard[2] = PokerCard3.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[2]);
   PokerCard[3] = PokerCard4.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[3]);
   PokerCard[4] = PokerCard5.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[4]);


public string getRandomImage()
{

    string[] fileNames = Directory.GetFiles(MapPath("~/GameStyles/VideoPoker/Images/Poker/"));
    int CurrentPick;

    CurrentPick = rand.Next(fileNames.Length);

    string CardToShow = fileNames[CurrentPick];
    return Path.GetFileName(CardToShow);
}

以下是我所拥有的屏幕截图

enter image description here

1 个答案:

答案 0 :(得分:1)

我建议使用LINQ来完成此任务:

string[] fileNames = Directory.GetFiles(MapPath("~/GameStyles/VideoPoker/Images/Poker/"));

var randomCards = fileNames
    .OrderBy(i => Guid.NewGuid())
    .Take(5)
    .Select(filePath => Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", Path.GetFileName(filePath)))
    .ToArray();

PokerCard[0] = PokerCard1.ImageUrl = randomCards[0];
PokerCard[1] = PokerCard2.ImageUrl = randomCards[1];
PokerCard[2] = PokerCard3.ImageUrl = randomCards[2];
PokerCard[3] = PokerCard4.ImageUrl = randomCards[3];
PokerCard[4] = PokerCard5.ImageUrl = randomCards[4];

这将简单地重新排序fileNames数组,按随机Guid排序(这将基本上随机化数组),然后取前5个元素。

这是一个.NET小提琴,展示它将如何运作:https://dotnetfiddle.net/c1996q