encapsulation - Keep your privates… private - if/else if/else, Console, ReadKeyメソッド, Random
Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 5(encapsulation - Keep your privates… private)、p.721(Exercise)の解答を求めてみる。
コード
Program.cs
using System;
namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
SwordDamage swordDamage = new SwordDamage();
Random random = new Random();
while (true)
{
Console.Write(
"0 for no magic/flaming, 1 for magic, 2 for flaming, " +
"3 for both, anything else to quit: ");
char input = Console.ReadKey().KeyChar;
if (input != '0' && input != '1' && input != '2' && input != '3')
{
return;
}
swordDamage.Roll = 0;
for (int i = 0; i < 3; i++)
{
swordDamage.Roll += random.Next(1, 7);
}
swordDamage.SetMagic(input == '1' || input == '3');
swordDamage.SetFlaming(input == '2' || input == '3');
Console.WriteLine($"\nRolled {swordDamage.Roll} for {swordDamage.Damage} HP");
}
}
}
}
入出力結果(Terminal, Zsh)
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 0
Rolled 9 for 12 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 0
Rolled 5 for 8 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 1
Rolled 14 for 27 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 1
Rolled 9 for 18 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 2
Rolled 13 for 18 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 3
Rolled 7 for 17 HP
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: q