在C#中洗牌

时间:2009-07-19 19:20:28

标签: c# .net shuffle playing-cards

我正在尝试为一个列出一副卡片内容的项目编写一个代码,询问该人想要洗牌的次数,然后将它们洗牌。它必须使用一个方法来使用System.Random类创建两个随机整数。

这些是我的课程:

的Program.cs:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Deck mydeck = new Deck();
            foreach (Card c in mydeck.Cards)
            {
                Console.WriteLine(c);
            }
            Console.WriteLine("How Many Times Do You Want To Shuffle?");

        }
    }
}

Deck.cs:

namespace ConsoleApplication1
{
    class Deck
    {    
        Card[] cards = new Card[52];
        string[] numbers = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K" };
        public Deck()
        {
            int i = 0;
            foreach(string s in numbers)
            {
                cards[i] = new Card(Suits.Clubs, s);
                i++;

            }
            foreach (string s in numbers)
            {
                cards[i] = new Card(Suits.Spades, s);
                i++;

            }
            foreach (string s in numbers)
            {
                cards[i] = new Card(Suits.Hearts, s);
                i++;

            }
            foreach (string s in numbers)
            {
                cards[i] = new Card(Suits.Diamonds, s);
                i++;

            }
        }

        public Card[] Cards
        {
            get
            {
                return cards;


            }
        }
    }  
}

Enums.cs:

namespace ConsoleApplication1
{        
    enum Suits 
    {
        Hearts,
        Diamonds,
        Spades,
        Clubs
    }
}

Card.cs:

namespace ConsoleApplication1
{
    class Card
    {
        protected Suits suit;
        protected string cardvalue;
        public Card()
        {
        }
        public Card(Suits suit2, string cardvalue2)
        {
            suit = suit2;
            cardvalue = cardvalue2;
        }
        public override string ToString()
        {
            return string.Format("{0} of {1}", cardvalue, suit);
        }
    }
 }

请告诉我如何使卡片随意移动,然后列出随机播放的卡片。

9 个答案:

答案 0 :(得分:46)

使用Fisher-Yates shuffle

您的C#代码应如下所示:

static public class FisherYates
{
    static Random r = new Random();
    //  Based on Java code from wikipedia:
    //  http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
    static public void Shuffle(int[] deck)
    {
        for (int n = deck.Length - 1; n > 0; --n)
        {
            int k = r.Next(n+1);
            int temp = deck[n];
            deck[n] = deck[k];
            deck[k] = temp;
        }
    }
}

答案 1 :(得分:17)

一开始洗牌似乎是微不足道的,但通常大多数人想出的算法都是不正确的。

杰夫阿特伍德(Coding Horror)写了一些关于这个主题的非常好的文章:

http://www.codinghorror.com/blog/archives/001008.html

http://www.codinghorror.com/blog/archives/001015.html

(特别是第二个是必读的)

答案 2 :(得分:5)

我认为这是一个你可能只是陷入抽象的情况。

在软件中混洗一副牌是一个以随机顺序向用户提供牌组的问题。这实际上并不需要你提前洗牌。

初始你的套牌。 (我通常使用1到52之间的数字来表示卡片并以数学方式计算哪张卡片。)

  1. 使用随机数生成器从卡片中挑出一张卡片。
  2. 将卡片与卡片末端的卡片交换。
  3. 减少指向甲板末端的柜台,从甲板上取下该卡。
  4. 转到第1步,直至完成绘图卡。
  5. 编辑:一般来说,如果你有一个好的随机数生成器,就可以多次“改组”它。

    这应该可以使用您显示的数据结构。您只需要添加一个“Draw”方法和成员变量来跟踪卡组的结尾。如果你真的想要提前实际进行“洗牌”,那么A你的教授是个混蛋,B你随时抽出52张牌就会被洗牌。一旦你绘制了所有卡片,你需要提供一个“DeckEmpty”方法,以及重置甲板结束以再次包含所有卡片的方法。

答案 3 :(得分:3)

要正确地洗牌,你不应该只使用Random类,种子只有2 ^ 32,这意味着你的Random对象只能给你2 ^ 32(假设)不同的顺序,其中有52! (因子52)生成真实生活套牌的方式。

我正在使用2 guid来创建32字节的随机数据 - > 4个4字节的种子和我洗牌 卡片上有8种不同的种子

然后通过种子获得一定数量的牌[5,5,6,6,6,7,8,9]

这是我使用的代码

    public void Shuffle(Guid guid1, Guid guid2)
    {
        int[] cardsToGet = new int[] { 5, 5, 6, 6, 6, 7, 8, 9 };
        byte[] b1 = guid1.ToByteArray();
        byte[] b2 = guid2.ToByteArray();

        byte[] all = new byte[b1.Length + b2.Length];
        Array.Copy(b1, all, b1.Length);
        Array.Copy(b2, 0, all, b1.Length, b2.Length);

        List<Card> cards = new List<Card>(this);
        Clear();

        for (int c = 0; c < cardsToGet.Length; c++)
        {
            int seed = BitConverter.ToInt32(all, c * 4);
            Random random = new Random(seed);
            for (int d = 0; d < cardsToGet[c]; d++)
            {
                int index = random.Next(cards.Count);
                Add(cards[index]);
                cards.RemoveAt(index);
            }
        }
    }

答案 4 :(得分:2)

你的Shuffle可能会起作用,但它并不是真正有效而且不是栩栩如生。你应该这样试试:

//The shuffle goes like this: you take a portion of the deck, then put them in random places
private void Shuffle()
{
 int length = DeckofCards.Count;
 int level = 20; //number of shuffle iterations

 List<Card> Shuffleing; //the part of the deck were putting back
 Random rnd = new Random();
 int PickedCount, BackPortion; //the last used random number

 for (int _i = 0; _i < level; _i++)
 {
  PickedCount = rnd.Next(10, 30); //number of cards we pick out
  Shuffleing = DeckofCards.GetRange(0, PickedCount);
  DeckofCards.RemoveRange(0, PickedCount);

  while (Shuffleing.Count != 0)
  {
   PickedCount = rnd.Next(10, DeckofCards.Count - 1); //where we place a range of cards
   BackPortion = rnd.Next(1, Shuffleing.Count / 3 + 1); //the number of cards we but back in one step
   DeckofCards.InsertRange(PickedCount, Shuffleing.GetRange(0, BackPortion)); //instering a range of cards
   Shuffleing.RemoveRange(0, BackPortion); //we remove what we just placed back
  }
 }
}

通过这种方式,您可以通过更少的迭代获得更逼真的随机播放

答案 5 :(得分:-1)

洗牌应该以这种方式运作:

你在牌组中随机取两张牌(牌组中牌的索引是随机数) 并交换两张牌的位置。 例如,在索引2处获取卡片,在索引9处获取卡片并将它们更改为位置。

这可以重复一定次数。

算法看起来像这样:

int firstNum = rnd.Next(52);
int secondNum = rnd.Next(52);

Card tempCard = MyCards[firstNum];
MyCards[firstNum] = MyCards[secondNum];
MyCards[secondNum] = tempCard;

答案 6 :(得分:-1)

总的来说,我将每个套牌看作一个包含Card对象数组的对象,每个Card对象都包含一个值和套件int属性,可以应用于Enum值和套件根据您正在使用的Deck类型收集指定版本。 (这将允许这一点代码更通用,并允许更容易的价值比较3&lt; 11(杰克)!〜)你的风格将适用于学校项目,我只是用它来获得强迫症!

class Card
{
    public int value
    { get; set; }

    public int suite
    { get; set; }
}


abstract class Deck
{
    public Card[] cards
    { get; set; }

    public void ShuffleCards(int timesToShuffle)
    {
        Card temp;
        Random random = new Random();
         // int timesToShuffle = random.Next(300, 600); #Had it setup for random shuffle
        int cardToShuffle1, cardToShuffle2; 

        for (int x = 0; x < timesToShuffle; x++)
        {
            cardToShuffle1 = random.Next(this.cards.Length);
            cardToShuffle2 = random.Next(this.cards.Length);
            temp = this.cards[cardToShuffle1];

            this.cards[cardToShuffle1] = this.cards[cardToShuffle2];
            this.cards[cardToShuffle2] = temp;
        }
    }
}

假设您使用了基础Deck类,然后将其继承到您想要的套牌类型(使其成为可以将相同的代码应用于Uno套牌或者其他任何东西。)正常类型的套牌类的代码。

class NormalDeck : Deck
{
    // This would go in the NormalGame class to apply the enumerators to the values as a cipher.
    // Need int values for logic reasons (easier to work with numbers than J or K !!!
    // Also allows for most other methods to work with other deck<Type> (ex: Uno, Go Fish, Normal cards)
    public enum Suites
    {
        Hearts,
        Diamonds,
        Spades,
        Clover
    };

    // Same comment as above. 
    public enum Values
    { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };

    public void NewNormalDeck()
    {
        // Clear the deck of cards
        if (this.cards != null)
        {
            Array.Clear(this.cards, 0, this.cards.Length);
        }

        //Set Value to length of Normal deck of Cards without Jokers 
        cards = new Card[52];

        // to keep count of which card we are.  
        int curNumofCards = 0;

        // Cycle through all of the suites listed in "suites" then all the values of     that suite
        for (int x = 0; x < Enum.GetValues(typeof(Suites)).GetLength(0); x++)
        {
            for (int y = 0; y < Enum.GetValues(typeof(Values)).GetLength(0); y++)
            {
                Card newCard = new Card();
                newCard.suite = x;
                newCard.value = y;
                this.cards[curNumofCards] = newCard;
                curNumofCards++;
            }
        }
    }
}

答案 7 :(得分:-1)

我制作了一个包含7张牌的程序,然后随机播放,我希望能够帮助他们。

课程计划 {

static void Main(string[] args)
{
    Random random = new Random(); 
    var cards = new List<string>();
    //CARDS VECRTOR
    String[] listas = new String[] { "Card 1", "Card 2", "Card 3", "Card 4", "Card 5", "Card 6", "Card 7"};


    for (int i = 0; i<= cards.Count; i++)
    {

        int number = random.Next(0, 7); //Random number 0--->7


        for (int j = 0; j <=6; j++)
        {
            if (cards.Contains(listas[number])) // NO REPEAT SHUFFLE
            {

                number = random.Next(0, 7); //AGAIN RANDOM

            }
            else
            {
                cards.Add(listas[number]); //ADD CARD
            }
        }

    }

    Console.WriteLine(" LIST CARDS");

    foreach (var card in cards)
    {
        Console.Write(card + " ,");


    }

    Console.WriteLine("Total Cards: "+cards.Count);

    //REMOVE

    for (int k = 0; k <=6; k++)
    {
       // salmons.RemoveAt(k);
        Console.WriteLine("I take the card: "+cards.ElementAt(k));
        cards.RemoveAt(k); //REMOVE CARD
        cards.Insert(k,"Card Taken"); //REPLACE INDEX
        foreach (var card in cards)
        {
            Console.Write(card + " " + "\n");

        }


    }


    Console.Read(); //just pause

}

}

答案 8 :(得分:-1)

static void Shuffle(List<int> cards)
    {
        Console.WriteLine("");
        Console.WriteLine("Shuffling");
        Console.WriteLine("---------");

        cards = cards.OrderBy(x => Guid.NewGuid()).ToList();

        foreach (var card in cards)
        {
            Console.WriteLine(card.ToString());
        }
    }