namespace HorseRace;
public sealed class HorseRace
{
public const int MaxSteps = 20;
private const int DelayMilliseconds = 100;
private readonly Horse[] _horses;
public HorseRace(Horse[] horses)
{
_horses = horses;
}
private bool IsFinished { get; set; }
///
/// Prints the starting list for all horses in this race.
///
public void PrintStartList()
{
string nl = Environment.NewLine;
var s = "Starting List";
s += $"{nl}{new string('=', s.Length)}{nl}"
;
foreach (var horse in _horses)
{
s += string.Format($"{horse.StartNumber,3} {horse.Name,-10} {horse.Age,2}{nl}");
}
Console.WriteLine(s);
}
///
/// Starts and performs the race by moving and drawing the horses, until at least one
/// horse has reached the finish line.
///
public void PerformRace()
{
IsFinished = false;
while (!IsFinished)
{
MoveHorses();
DrawHorses();
Thread.Sleep(DelayMilliseconds);
}
AssignRanks();
}
///
/// Prints the race results to the terminal; only if the race is finished.
///
public void PrintResults()
{
foreach (var horse in _horses)
{
Console.WriteLine($"{horse.Rank,3}. {horse.Name,-10} (SN {horse.StartNumber} Position {horse.Position}");
}
}
///
/// Moves all horses and checks, if any of the horses has reached the finish line.
///
private void MoveHorses()
{
if(IsFinished)
{
return;
}
foreach (var horse in _horses)
{
horse.Move();
if (horse.Position >= MaxSteps)
{
IsFinished = true;
return;
}
}
}
///
/// Draws each horse with label, current position and finish line.
///
private void DrawHorses()
{
Console.Clear();
foreach (var horse in _horses)
{
horse.Draw();
}
}
///
/// Assigns ranks to the horses, according to their individual position in the race.
///
private void AssignRanks()
{
SortByPosition();
for (int i = 0; i < _horses.Length; i++)
{
if (i > 0 && _horses[i].Position == _horses[i - 1].Position)
{
_horses[i].Rank = _horses[i - 1].Rank;
}
else
{
_horses[i].Rank = i + 1;
}
}
}
///
/// Sorts the array of horses by position and then by starting number.
///
private void SortByPosition()
{
for (int i = 0; i < _horses.Length - 1; i++)
{
for (int j = 0; j < _horses.Length - i - 1; j++)
{
if (_horses[j].CompareTo(_horses[j + 1]) > 0)
{
(_horses[j], _horses[j + 1]) = (_horses[j + 1], _horses[j]);
}
}
}
}
}