In the deck class in article 1, a deck of cards is represented by a card array method, which is less flexible and often uses a set of cards in a card game, where it is necessary to create a Solitaire collection class cards
1. Implementing by inheriting the collection class
First introduce the System.Collection space in the Arrylist class bar, this class inherits the IList interface, you can dynamically add or remove elements, very useful. Just a few changes to the previous code. Specific changes are as follows:
(1) Where you need to modify the fields of the deck class
// private card[] _cards=new card[52]; Private New ArrayList ();
(2), you need to modify the deck class constructor
Public Deck () { for (int.04; i++) { for ( int 1; J + +) { // _cards[i * + j-1] = new Card ((Cardsuit) I, (Cardrank) j); _cardslist.add (new Card ((Cardsuit) I, (Cardrank) j);} }}
(3), need to change the Shuffle Method shuffle ()
Public voidShuffle () {//card[] cards=new card[52];ArrayList cardslist =NewArrayList (); BOOL[] isfind=New BOOL[ the]; Random Rand=NewRandom (); intindex; for(inti =0; I < the; i++) { Do{Index=rand. Next ( the); } while(Isfind[index]); //Cards[i]=_cards[index];Cardslist.add (_cardslist[index]); Isfind[index]=true; } //cards. CopyTo (_cards, 0);_cardslist=(ArrayList) Cardslist.clone (); }
(4) The Getcard () method needs to be modified
Public Card getcard (int cardindex) { if(cardindex<0 | | cardindex>= The new Exception (" exceeds the index range [0,51]" )); // return _cards[cardindex]; return (Card) _cardslist[cardindex]; }
In this case, the modifications are all done and the results are the same. But this class has a fatal disadvantage, please next decomposition.
Lamy Card Game Development Road Study 2