-1

Currently working on writing code for a Windows Forms version of the card game war. I needed a way to shuffle the list to randomize the deck. I have already defined the lists for deck and shuffledDeck as a list of strings.

When I run createDeck(), I had it output to a textbox in my windows form to ensure that it is infact creating the list properly. I also had it test to ensure that deck.Count() was equal to 52

private void shuffle()
        {
            createDeck();
            shuffledDeck = deck;
            Random r = new Random();
            int randomIndex = 0;
            while (deck.Count > 0)
            {
                randomIndex = r.Next(0, deck.Count);
                shuffledDeck.Add(deck[randomIndex]);
                deck.RemoveAt(randomIndex);
            }

This is my testing that the deck is in fact shuffled

            for (int a = 0; a <= 51; a++)
            {
                textBox1.Text += " " + shuffledDeck[a];
            }

I would expect that I would see a shuffled deck each time however whenever I run it, Visual Studio freezes and I am have to force quit the program to exit.

Scottb0898
  • 37
  • 1
  • 6
  • 4
    [Use your debugger](https://idownvotedbecau.se/nodebugging/). `shuffledDeck = deck`, so they are the same deck, not a copy. Every time you add a card to `shuffledDeck` and remove one from `deck` you are adding and removing a card from the same deck, so obviously you will never run out of cards. – Dour High Arch Apr 25 '19 at 21:59
  • 1
    deck.Count is always > 0 – Mate Apr 25 '19 at 21:59
  • 2
    shuffledDeck = deck => it is the same object – Michał Szkudlarek Apr 25 '19 at 22:00
  • 1
    **[Navigating through Code using the Step Debugger](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)** UI controls, like MessageBox, are feeble debugging aides. – Ňɏssa Pøngjǣrdenlarp Apr 25 '19 at 22:08

1 Answers1

2

The line shuffledDeck = deck; makes shuffledDeck and deck a reference to the same object. So inside your while loop, you are removing and adding "cards" to the same deck and the condition deck.Count > 0 will always be true.

Try using this object cloner: Deep cloning objects

And replace shuffledDeck = deck; with shuffledDeck = deck.Clone();

deleb
  • 569
  • 4
  • 6