130 lines
3.2 KiB
C#
130 lines
3.2 KiB
C#
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; }
|
|
|
|
/// <summary>
|
|
/// Prints the starting list for all horses in this race.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts and performs the race by moving and drawing the horses, until at least one
|
|
/// horse has reached the finish line.
|
|
/// </summary>
|
|
public void PerformRace()
|
|
{
|
|
IsFinished = false;
|
|
while (!IsFinished)
|
|
{
|
|
MoveHorses();
|
|
DrawHorses();
|
|
Thread.Sleep(DelayMilliseconds);
|
|
}
|
|
|
|
AssignRanks();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Prints the race results to the terminal; only if the race is finished.
|
|
/// </summary>
|
|
public void PrintResults()
|
|
{
|
|
foreach (var horse in _horses)
|
|
{
|
|
Console.WriteLine($"{horse.Rank,3}. {horse.Name,-10} (SN {horse.StartNumber} Position {horse.Position}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Moves all horses and checks, if any of the horses has reached the finish line.
|
|
/// </summary>
|
|
private void MoveHorses()
|
|
{
|
|
if(IsFinished)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var horse in _horses)
|
|
{
|
|
horse.Move();
|
|
if (horse.Position >= MaxSteps)
|
|
{
|
|
IsFinished = true;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Draws each horse with label, current position and finish line.
|
|
/// </summary>
|
|
private void DrawHorses()
|
|
{
|
|
Console.Clear();
|
|
foreach (var horse in _horses)
|
|
{
|
|
horse.Draw();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Assigns ranks to the horses, according to their individual position in the race.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sorts the array of horses by position and then by starting number.
|
|
/// </summary>
|
|
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]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|