encapsulation - Keep your privates...private - Create a console app to calculate damage
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.229(Exercise)の解答を求めてみる。
コード
Program.cs
using ConsoleApp1;
SwordDamage swordDamage = new SwordDamage();
while (true)
{
Console.Write("0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: ");
char key = Console.ReadKey(false).KeyChar;
if (key < '0' || '3' < key)
{
break;
}
swordDamage.Roll = 0;
for (int i = 0; i < 3; i++)
{
swordDamage.Roll += Random.Shared.Next(1, 7);
}
swordDamage.SetMagig(key == '1' || key == '3');
swordDamage.SetFlaming(key == '2' || key == '3');
Console.WriteLine($"\nRolled {swordDamage.Roll} for {swordDamage.Damage} HP\n");
}
入出力結果(Terminal, Zsh)
% dotnet run
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 0
Rolled 10 for 15 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 0
Rolled 6 for 11 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 1
Rolled 7 for 17 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 1
Rolled 10 for 22 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 2
Rolled 10 for 17 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 2
Rolled 7 for 14 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: 3
Rolled 8 for 21 HP
0 fur no magic/flaming, 1 for magic, 2 for flaming, 3 for both, anything else to quit: q%