inheritance - Your object's family tree - switch statement
Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 6(inheritance - Your object’s family tree)、p.275(Exercise)の解答を求めてみる。
コード
Program.cs
using System;
namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
SwordDamage swordDamage = new SwordDamage(rollDice(3));
ArrowDamage arrowDamage = new ArrowDamage(rollDice(3));
while (true)
{
Console.Write("\nS for sword, A for Arrow, anything else to quit: ");
char weaponey = Char.ToUpper(Console.ReadKey().KeyChar);
switch (weaponey)
{
case 'S':
swordDamage.Roll = rollDice(3);
Console.Write(
"\n0 for no magic/flaming, 1 for magic, 2 for flaming, " +
"3 for both: ");
char input = Console.ReadKey().KeyChar;
swordDamage.Magic = input == '1' || input == '3';
swordDamage.Flaming = input == '2' || input == '3';
Console.WriteLine(
$"\nRolled {swordDamage.Roll} for {swordDamage.Damage} HP");
break;
case 'A':
arrowDamage.Roll = rollDice(3);
Console.Write(
"\n0 for no magic/flaming, 1 for magic, 2 for flaming, " +
"3 for both: ");
input = Console.ReadKey().KeyChar;
arrowDamage.Magic = input == '1' || input == '3';
arrowDamage.Flaming = input == '2' || input == '3';
Console.WriteLine(
$"\nRolled {arrowDamage.Roll} for {arrowDamage.Damage} HP");
break;
default:
return;
}
}
}
private static Random random = new Random();
private static int rollDice(int numberOfRolls)
{
int roll = 0;
for (int i = 0; i < numberOfRolls; i++)
{
roll += random.Next(1, 7);
}
return roll;
}
}
}
入出力結果(Terminal, Zsh)
S for sword, A for Arrow, anything else to quit: s
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 0
Rolled 9 for 12 HP
S for sword, A for Arrow, anything else to quit: s
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 1
Rolled 11 for 22 HP
S for sword, A for Arrow, anything else to quit: s
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 2
Rolled 13 for 18 HP
S for sword, A for Arrow, anything else to quit: s
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 3
Rolled 7 for 17 HP
S for sword, A for Arrow, anything else to quit: s
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 1
Rolled 9 for 18 HP
S for sword, A for Arrow, anything else to quit: S
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 2
Rolled 13 for 18 HP
S for sword, A for Arrow, anything else to quit: a
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 2
Rolled 10 for 5 HP
S for sword, A for Arrow, anything else to quit: