Reader Level:
ARTICLE

Yahtzee Program Using C#: Part II

Posted by Mike Gold Articles | Windows Forms C# January 31, 2002
This is an update of the Yahtzee program for VS 2005. Included in this version is a Game Reset and a High Score Tracker. The Top Ten High Scores are tracked using an Array with sortable components. In this article we will talk about the IComparable interface used to make an object stored in an array sortable.
  • 0
  • 0
  • 24851

yahtzee1.jpg

 

Introduction


This is an update of the Yahtzee program. Included in this version is a Game Reset and a High Score Tracker. The Top Ten High Scores are tracked using an Array with sortable components. In this article we will talk about the IComparable interface used to make an object stored in an array sortable.

The ScorePair class is a class containing two members Player and Score. In order to make this class comparable, we simply add the interface IComparable and add a CompareTo Method as shown below:

public class ScorePair : IComparable
{
public int CompareTo(object a)
{
if (Score.ToInt32() > ((ScorePair)a).Score.ToInt32())
{
return -1;
}
if (Score.ToInt32() < ((ScorePair)a).Score.ToInt32())
{
return 1;
}
return 0;
}
public ScorePair()
{
Name = "";
Score = "0";
}
public ScorePair(string aName, string aScore)
{
Name = aName;
Score = aScore;
}
public string Name;
public string Score;
}

The CompareTo Function returns 1, 0, or -1 based on the comparison of the ScorePair objects whether the object compared is less than, equal to, or greater than the instance. In this case we return -1 if the Score is greater than the object to be compared to, because we want to sort in descending order when we call the sort function, the highest score being first. Below is the initial array of ScorePairs. 

public ScorePair[] ScoreArray = new ScorePair[11]
{
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair(),
new ScorePair()
};

The call to sort is made below using the static Array function Sort:

public void AddHighScore(string name, int score)
{
// put it as the last one, then sort it
ScoreArray[10] = new ScorePair(ThePlayerName, score.ToString());
Array.Sort(ScoreArray);
// sort the array
WriteScoreArray(); // make the scores persist in a text file
}

Elements of an array using the IComparable interface can also use the ArrayList.BinarySearch routine, and other algorithms requiring comparisons within the array.

COMMENT USING

Trending up