改组2个不同的牌组以相同的卡顺序结束

时间:2018-09-17 06:39:25

标签: c#

因此,我正在编写一个用于练习的小型战争纸牌游戏程序,而我在理解上有些麻烦的一件事是,为什么我的功能为人类和cpu返回相同的牌组。

public static void TheirDecks(Player hum , Player cpu)
    {
        hum.myDeck.GenerateDeck();
        cpu.myDeck.GenerateDeck();

        hum.myDeck.Shuffle();
        cpu.myDeck.Shuffle();
    }

因此在我的Create类中找到了themDecks()方法。

public void GenerateDeck() // Must use this to populate deck
    {
        CurrentlyInDeck = new List<Card>(52);
        int place = 0; // tracks which card number
        for (int i = 0; i < 4; i++)
        {
            for (int f = 0; f < 13; f++)
            {
                Card card = new Card();
                CurrentlyInDeck.Add(card);
                CurrentlyInDeck[place].suit = (Suit)i;
                CurrentlyInDeck[place].face = (Face)f;
                place++;
            }
        }
    }

    public void Shuffle() 
    {
        Random rand = new Random();
        Card holder = new Card();
        int random;

        for (int i = 0; i < 52; i++)
        {
            random = rand.Next(0, 51);
            holder = CurrentlyInDeck[i];
            CurrentlyInDeck[i] = CurrentlyInDeck[random];
            CurrentlyInDeck[random] = holder;
        }
    }

那些2在另一个叫做Deck的类中找到。当我运行以下命令时:

static void Main(string[] args)
    {
        Create.TheirDecks(human , cpu);
        human.myDeck.PrintDeck();
        Console.WriteLine();
        cpu.myDeck.PrintDeck();
    }

打印纸盘功能将打印出相同的纸盘。这是为什么?谢谢您的宝贵时间。

1 个答案:

答案 0 :(得分:1)

保留Random的单个实例,并对同一实例继续使用Next。 尝试以下解决方案:

private static readonly Random rand = new Random(); 

public void Shuffle() 
{
    Card holder = new Card();
    int random;

    for (int i = 0; i < 52; i++)
    {
        random = rand.Next(0, 51);
        holder = CurrentlyInDeck[i];
        CurrentlyInDeck[i] = CurrentlyInDeck[random];
        CurrentlyInDeck[random] = holder;
    }
}