鶴亀算
問題
鶴亀算を出題するプログラムを作ってください。
鶴、亀
・鶴の数、亀の数はランダムに与えられ、それぞれ1以上10未満とする(1≦ n < 10)
・鶴の足は2本、亀の足は4本とする
入力
・鶴の数、亀の数を入力する
・整数値以外が入力された場合は、再び数を受け付けるようにする
・鶴と亀の数の入力が終われば答え合わせをおこなう
コンティニュー
・コンティニューはyかn(Yes or No)で判定する
・yを入力すると再び問題を表示し、nを入力すると終了する
例
頭の数は10、足の数は26。 鶴は何羽? >a 鶴は何羽? >5 亀は何匹? >5 不正解 正解は、鶴が7羽、亀が3匹でした。 もう一度しますか?(y/n) >y 頭の数は8、足の数は24。 鶴は何羽? >4 亀は何匹? >4 正解! もう一度しますか?(y/n) >n
解答例
using System; namespace TsuruKame { class Program { static void Main(string[] args) { TKZan tk = new TKZan(); tk.Start(); } } public class TKZan { //鶴亀最大最小数 private const int min = 1; private const int max = 10; private Random r; //鶴亀の数 private int tsuru; private int kame; //コンストラクタ public TKZan() { r = new Random(); } //ゲームループ public void Start() { do { this.Init(); this.GameMain(); } while (this.AskContinue()); } //出題から答え合わせまで private void GameMain() { int ansTsuru; int ansKame; Boolean check; this.OpenProblem(); ansTsuru = this.GetAnswer("鶴", "羽"); ansKame = this.GetAnswer("亀", "匹"); check = this.CheckAnswers(ansTsuru, ansKame); this.OpenAnswer(check); } //問題の初期化 private void Init() { this.tsuru = this.r.Next(min, max); this.kame = this.r.Next(min, max); } //出題 private void OpenProblem() { int headsNum = this.tsuru + this.kame; ; int legsNum = this.tsuru * 2 + this.kame * 4; Console.WriteLine("頭の数は{0}、足の数は{1}。", headsNum, legsNum); } //解答の入力 private int GetAnswer(String animalName, String numerative) { int n; String str; do { Console.WriteLine("{0}は何{1}?", animalName, numerative); str = Console.ReadLine(); } while (!int.TryParse(str, out n)); return n; } //答え合わせ private Boolean CheckAnswers(int t, int k) { if((t == this.tsuru) & (k == this.kame)) { return true; } else { return false; } } //解答の表示 private void OpenAnswer(Boolean c) { if(c == true) { Console.WriteLine("正解!"); } else { Console.WriteLine("不正解"); Console.WriteLine("正解は、鶴が{0}羽、亀が{1}匹でした。", this.tsuru, this.kame); } } //コンティニュー? private Boolean AskContinue() { Boolean f = true; String str; do { Console.WriteLine("もう一度しますか?(y/n)"); str = Console.ReadLine(); if ((str == "y") | (str == "n")) { f = false; } } while (f); return str == "y" ? true : false; } } }