For something completely unrelated, I decided to check into my older Delphi code and noticed the ‘remnants’ of the code that actually started as a framework for a (basic) Spades1 card game. So hey: the code was actually so readable that most of it was easily turned into a C# version (that is minus the bidding code).
The fun part of it all was the ease of sorting in C#. Actually, you still need to write code to get that going, but compared to the things I needed to get a hand sorted in Delphi, that can be a different story (it’s actually not too bad either if you use regular TLists and that):
First of all make your base object descend from the IComparable class. This means, you’ll have to add a CompareTo method to your base object
public class TCard : IComparable
{
private TFaceValue ffacevalue;
private bool ffaceup = false;
private TSuit fsuit;
// Code removed for brevity reasons...
public int CalcValue
{
get { return NumericValue(); }
}
public int CompareTo(TCard acard)
{
return this.CalcValue.CompareTo(acard.CalcValue);
}
}
Then create a class based on IComparer:
public class THandComparer : IComparer
{
private TSortOptions fsort = TSortOptions.Ascending;
public TSortOptions SortOption
{
get { return fsort; }
set { fsort = value; }
}
public int Compare(TCard x, TCard y)
{
if (fsort == TSortOptions.Ascending)
{
return x.CompareTo(y);
}
else
{
return y.CompareTo(x);
}
}
}
I decided to give the player an option to sort the cards descending or ascending based on the combination of suit and card value: Notice that for descending order, you literally just switch the objects (the base CompareTo method returns -1, 0 or 1!)
And then in the THand Class:
// [....]
public void Sort()
{
THandComparer fcomparer = new THandComparer();
fcomparer.SortOption = forder;
fhand.Sort(fcomparer);
}
What rest are the drawing procedures, the card faces (I should have a couple of sets somewhere on my source backup disks) and the bidding engine.