encapsulation - Keep your privates...private - Hi-Lo game, random
Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 5(encapsulation - Keep your privates…private)、p.243(Exercise)の解答を求めてみる。
コード
Program.cs
Console.WriteLine("Welcome to HiLo.");
Console.WriteLine($"Guess numbers between 1 and {HiLoGame.MAXIMUM}");
HiLoGame.Hint();
while (HiLoGame.GetPot() > 0)
{
Console.WriteLine("Press h for higher, l for lower, ? to buy a hint,");
Console.WriteLine($"or any other key to quit with {HiLoGame.GetPot()}.");
char key = Console.ReadKey(true).KeyChar;
if (key == 'h')
{
HiLoGame.Guess(true);
}
else if (key == 'l')
{
HiLoGame.Guess(false);
}
else if (key == '?')
{
HiLoGame.Hint();
}
else
{
return;
}
}
Console.WriteLine("THe pot is empty. Bye!");
static class HiLoGame
{
public const int MAXIMUM = 10;
private static Random random = new Random();
private static int currentNumber = random.Next(1, MAXIMUM + 1);
private static int pot = 10;
internal static int GetPot()
{
return pot;
}
internal static void Guess(bool higher)
{
int nextNumber = random.Next(1, MAXIMUM + 1);
if ((higher && nextNumber >= currentNumber) ||
(!higher && nextNumber <= currentNumber))
{
Console.WriteLine("You guessed right!");
pot++;
}
else
{
Console.WriteLine("Bad luck, you guessed wrong.");
pot--;
}
currentNumber = nextNumber;
Console.WriteLine($"The current number is {currentNumber}");
}
internal static void Hint()
{
int half = MAXIMUM / 2;
if (currentNumber >= half)
{
Console.WriteLine($"The number is at least {half}");
}
else
{
Console.WriteLine($"The number is at most {half}");
}
pot--;
}
}
入出力結果(Terminal, Zsh)
% dotnet run
Welcome to HiLo.
Guess numbers between 1 and 10
The number is at least 5
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 9.
You guessed right!
The current number is 2
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 10.
You guessed right!
The current number is 7
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 11.
Bad luck, you guessed wrong.
The current number is 8
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 10.
Bad luck, you guessed wrong.
The current number is 9
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 9.
You guessed right!
The current number is 5
Press h for higher, l for lower, ? to buy a hint,
or any other key to quit with 10.
%