Article Description
This article gives enough idea about how to use collections and properties in C#. In this article, author develops a card game using collections and properties.
Code Description
Attached is the sample Cards game. It contains 5 classes in total.
Class1.cs - is the main entry point of the game. It creates number of instances of Player object depending on the number of players. After done with Player, main method of Class1 instantiates Deck object which has an array of 52 Card objects. It then calls Shuffle method of Deck which randomly rearranges cards in an array.It then calls InitializeCardsInHand method which adds Cards to each player's collection of cards. Each player is given a chance to take a Card on the table or draw new Card from the Deck. This continues until all cards in one of the players collection have the same suit.
Player.cs - Player constructor creates an instance of Cards object which is collection of cards in each player's hand.
Card.cs - It has 2 enums representing suit and rank of the cards. Constructor assigns Rank and Suit for the Card.
Cards.cs - Cards is derived from the CollectionBase class. It has Index property which uses List property of CollectionBase class which returns System.Collection.IList containing the list of elements in the CollectionBase instance. It also has Add and Remove methods to add and remove the card from the collection.
Deck.cs- It represents an array of 52 cards. It has 1 method and 2 properties. Shuffle method is for randomly shuffling Card objects in an array. NextCard property is for getting the next Card in the Deck. CardIndex is for setting the current top card in the Deck.
To win the game player must have all cards of the same suit in hand.
This game has one bug. I've left it up to you to find it and fix it.