From 5fbf0dc37f9c4ac120df56e454d177ca55c4820b Mon Sep 17 00:00:00 2001 From: Andrew Cooper Date: Sat, 16 Apr 2022 17:00:06 +1000 Subject: [PATCH] Encapsulate formulae --- 25_Chief/csharp/Game.cs | 27 ++++++++++--------------- 25_Chief/csharp/IReadWriteExtensions.cs | 9 +++++++++ 25_Chief/csharp/Math.cs | 18 +++++++++++++++++ 3 files changed, 38 insertions(+), 16 deletions(-) create mode 100644 25_Chief/csharp/Math.cs diff --git a/25_Chief/csharp/Game.cs b/25_Chief/csharp/Game.cs index 95839cb5..4612140b 100644 --- a/25_Chief/csharp/Game.cs +++ b/25_Chief/csharp/Game.cs @@ -14,17 +14,11 @@ internal class Game internal void Play() { - _io.Write(Streams.Title); - if (!_io.ReadYes(Prompts.Ready)) - { - _io.Write(Streams.ShutUp); - } - - _io.Write(Streams.Instructions); + DoIntroduction(); var result = _io.ReadNumber(Prompts.Answer); - if (_io.ReadYes(Formats.Bet, (result + 1 - 5) * 5 / 8 * 5 - 3)) + if (_io.ReadYes(Formats.Bet, Math.CalculateOriginal(result))) { _io.Write(Streams.Bye); return; @@ -32,7 +26,7 @@ internal class Game var original = _io.ReadNumber(Prompts.Original); - _io.WriteLine(Formats.Working, GetStepValues(original).ToArray()); + _io.WriteLine(Math.ShowWorking(original)); if (_io.ReadYes(Prompts.Believe)) { @@ -43,13 +37,14 @@ internal class Game _io.Write(Streams.Lightning); } - private static IEnumerable GetStepValues(float value) + private void DoIntroduction() { - yield return value; - yield return value += 3; - yield return value /= 5; - yield return value *= 8; - yield return value = value / 5 + 5; - yield return value - 1; + _io.Write(Streams.Title); + if (!_io.ReadYes(Prompts.Ready)) + { + _io.Write(Streams.ShutUp); + } + + _io.Write(Streams.Instructions); } } diff --git a/25_Chief/csharp/IReadWriteExtensions.cs b/25_Chief/csharp/IReadWriteExtensions.cs index e69de29b..c74256ec 100644 --- a/25_Chief/csharp/IReadWriteExtensions.cs +++ b/25_Chief/csharp/IReadWriteExtensions.cs @@ -0,0 +1,9 @@ +namespace Chief; + +internal static class IReadWriteExtensions +{ + internal static bool ReadYes(this IReadWrite io, string format, float value) => + io.ReadYes(string.Format(format, value)); + internal static bool ReadYes(this IReadWrite io, string prompt) => + io.ReadString(prompt).Equals("Yes", StringComparison.InvariantCultureIgnoreCase); +} \ No newline at end of file diff --git a/25_Chief/csharp/Math.cs b/25_Chief/csharp/Math.cs new file mode 100644 index 00000000..ba28d1f3 --- /dev/null +++ b/25_Chief/csharp/Math.cs @@ -0,0 +1,18 @@ +using static Chief.Resources.Resource; + +namespace Chief; + +public static class Math +{ + public static float CalculateOriginal(float result) => (result + 1 - 5) * 5 / 8 * 5 - 3; + + public static string ShowWorking(float value) => + string.Format( + Formats.Working, + value, + value += 3, + value /= 5, + value *= 8, + value = value / 5 + 5, + value - 1); +} \ No newline at end of file