public void Shuffle() { //Card[] newDeck = new Card[52]; Cards newDeck = new Cards(); bool[] assigned = new bool[52]; Random sourceGen = new Random(); for (int i = 0; i < 52; i++) { //int destCard = 0; int sourceCard = 0; bool foundCard = false; // 找到下一张还未被洗牌的牌 while (foundCard == false) { //destCard = sourceGen.Next(52); sourceCard = sourceGen.Next(52); if (assigned[sourceCard] == false) { foundCard = true; } } assigned[sourceCard] = true; //newDeck[sourceCard] = cards[i]; newDeck.Add(cards[sourceCard]); } 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); }
/// <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); }