public Deck() { //// Book solution //for (int suitVal = 0; suitVal < 4; suitVal++) //{ // for (int rankVal = 1; rankVal < 14; rankVal++) // { // cards.Add(new Card((Suit)suitVal, (Rank)rankVal)); // } //} // Loop through all the Suit and Rank enum values foreach (Suit suit in Enum.GetValues(typeof(Suit))) { foreach (Rank rank in Enum.GetValues(typeof(Rank))) { cards.Add(new Card(suit, rank)); } } }
/// <summary> /// Shuffles all the cards in this deck. /// </summary> public void Shuffle() { // Create a temporary collection to shuffle the cards into. Cards newDeck = new Cards(); // Create an array to track which elements of the temporary array already have // a card assigned to them. bool[] assigned = new bool[52]; // Use a Random class to select the positions to shuffle the cards into. Random sourceGen = new Random(); // Shuffle each card in the cards field into the temporary collection. for (int i = 0; i < 52; i++) { int sourceCard = 0; bool foundCard = false; while (foundCard == false) { // Generate random numbers from 0 - 51 until we find a position in the // temporary array that doesn't have a card assigned to it. sourceCard = sourceGen.Next(52); if (assigned[sourceCard] == false) { foundCard = true; } } //Set the flag that an empty position was found, and assign the current card // to it. assigned[sourceCard] = true; newDeck.Add(cards[sourceCard]); } // Copy the shuffled deck back into the same instance of the cards field. // Note that cards = newDeck would create a new instance in cards, which could // cause problems if some other code was holding a reference to the original // instance of cards. newDeck.CopyTo(cards); }
public void Shuffle() { Cards newDeck = new Cards(); bool[] assigned = new bool[52]; Random sourceGen = new Random(); for (int i = 0; i < 52; i++) { int sourceCard = 0; bool foundCard = false; while (foundCard == false) { sourceCard = sourceGen.Next(52); if (assigned[sourceCard] == false) { foundCard = true; } } assigned[sourceCard] = true; newDeck.Add(cards[sourceCard]); } newDeck.CopyTo(cards); }