Introduction
This is an article that briefly explains the use of a group of classes I created that represent a typical set of playing cards. I wanted to create a game of cribbage, and began by looking for Open Source code that would have the basic playing card classes built for me. Surprisingly, I didn't find any that suited my needs. So, I decided the first thing I would need to create for my game of cribbage were the playing cards. These included a card class, a card array (a collection of cards), a card comparer (for sorting the card array in different ways), a standard 52 card deck, and shoe classes. I originally wrote these classes in C#, but translated them to VB using the free online tool. I hope you find this useful.
Using the code
The project file actually has the solution file as well as three projects in it. There is one project for the C# card classes, one for VB.NET card classes, and the third is a simple C# console app that is designed to show you the uses of the classes. The C# and VB.NET classes are identical in functionality, and only differ in the language they were written in.
One of the most common mistakes I saw when looking at how others approached the card classes is to not use enumeration when representing the card properties. By using strongly typed data, the code will be easier to read and less prone to usage errors.
Another shortcoming I saw in other similar projects is the lack of methods for sorting the cards. There are many different ways to order a set of cards, such as face, value, suit, ascending, descending, etc. I decided to create a static class that uses the IComparable
interface to make sorting easier. The actual implementation of the sort algorithm is hidden in a private nested class as seen below:
public static class CardComparer
{
public static IComparer SortFaceAscending()
{
return (IComparer)new SortFaceAscendingHelper();
}
....
private class SortFaceAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
if (a is Card && b is Card)
{
Card cardA = (Card)a;
Card cardB = (Card)b;
if (cardA.Face > cardB.Face) { return 1; }
else if (cardA.Face < cardB.Face) { return -1; }
else { return 0; }
}
else { throw new ArgumentException("Object is not of type Card."); }
}
}
Ways to improve/build upon this code
I built this code as a foundation for a cribbage game that I am currently working on. It could be used or easily modified to play with any card game that you want. The biggest difference that the various card games have is the actual value of the card, which is why I made the face and suit properties separate from the actual value of the card. This could be improved by the value of the card based on the current game being played, perhaps through a static class passed to the card's constructor.