Implement game

This commit is contained in:
Andrew Cooper
2022-08-20 08:26:33 +10:00
parent 9118236a6f
commit 769b277f63
4 changed files with 74 additions and 4 deletions

View File

@@ -13,6 +13,66 @@ internal class Game
public void Play()
{
while (true)
{
_io.Write(Streams.Introduction);
var limit = _io.ReadNumber(Prompts.Limit);
_io.WriteLine();
// There's a bug here that exists in the original code.
// If the limit entered is <= 0 then the program will crash.
var targetGuessCount = checked((int)Math.Log2(limit) + 1);
PlayGuessingRounds(limit, targetGuessCount);
_io.Write(Streams.BlankLines);
}
}
private void PlayGuessingRounds(float limit, int targetGuessCount)
{
while (true)
{
_io.WriteLine(Formats.Thinking, limit);
// There's a bug here that exists in the original code. If a non-integer is entered as the limit
// then it's possible for the secret number to be the next integer greater than the limit.
var secretNumber = (int)_random.NextFloat(limit) + 1;
var guessCount = 0;
while (true)
{
var guess = _io.ReadNumber("");
if (guess <= 0) { return; }
guessCount++;
if (IsGuessCorrect(guess, secretNumber)) { break; }
}
ReportResult(guessCount, targetGuessCount);
_io.Write(Streams.BlankLines);
}
}
private bool IsGuessCorrect(float guess, int secretNumber)
{
if (guess < secretNumber) { _io.Write(Streams.TooLow); }
if (guess > secretNumber) { _io.Write(Streams.TooHigh); }
return guess == secretNumber;
}
private void ReportResult(int guessCount, int targetGuessCount)
{
_io.WriteLine(Formats.ThatsIt, guessCount);
_io.WriteLine(
(guessCount - targetGuessCount) switch
{
< 0 => Strings.VeryGood,
0 => Strings.Good,
> 0 => string.Format(Formats.ShouldHave, targetGuessCount)
});
}
}

View File

@@ -0,0 +1,5 @@

View File

@@ -1,4 +1,4 @@
Guezs
Guess
Creative Computing Morristown, New Jersey

View File

@@ -10,8 +10,7 @@ internal static class Resource
public static Stream Introduction => GetStream();
public static Stream TooLow => GetStream();
public static Stream TooHigh => GetStream();
public static Stream Good => GetStream();
public static Stream VeryGood => GetStream();
public static Stream BlankLines => GetStream();
}
internal static class Formats
@@ -26,6 +25,12 @@ internal static class Resource
public static string Limit => GetString();
}
internal static class Strings
{
public static string Good => GetString();
public static string VeryGood => GetString();
}
private static string GetString([CallerMemberName] string? name = null)
{
using var stream = GetStream(name);