1

私が作成している単純な数字推測ゲームのコードにスパイスを加えようとしています。ユーザーが適切な数字を推測すると、メッセージ ダイアログ ボックスが表示され、勝者であることを伝えます。そのメッセージ ダイアログ ボックスには、「OK」という名前のボタンが 1 つあり、クリックするとフォームに戻ります。

代わりに、新しい乱数が生成されるようにコードを再起動したいと思います。これは可能ですか、または勝者のコード領域内でコードをデフォルトの状態に手動で戻す必要がありますか?

ここに私のコードがあります:

    private void btnEval_Click (object sender, EventArgs e)
    {
        // increment the counter to be displayed later
        howManyClicks++;



        // main decision conditions, ensures something is entered
        if (txtNum.Text != "")
        {
            // user input number
            double num = double.Parse (txtNum.Text);

            if (randomNumber > num)
            {
                // if too low
                this.BackColor = Color.Yellow;
                lblMain.Text = "TOO LOW!";
                lblReq.Text = "please try again";
                txtNum.Clear ();
                txtNum.Focus ();

            }
            else if (randomNumber < num)
            {
                // if too high
                this.BackColor = Color.Red;
                lblMain.Text = "TOO HIGH!";
                lblReq.Text = "please try again";
                txtNum.Clear ();
                txtNum.Focus ();
            }
            else
            {
                // correct
                this.BackColor = Color.Green;
                lblMain.Text = "CORRECT!";
                lblReq.Text = "well done";
                MessageBox.Show ("You are right!! It took you " + howManyClicks + " guesses", "You are a WINNER!!",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                txtNum.Clear ();
                txtNum.Focus ();
            }
        }
        else
        {
            MessageBox.Show ("You must enter a vaild number! Please try again.", "ERROR",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            txtNum.Clear ();
            txtNum.Focus ();
        }
4

2 に答える 2

2

どうやら、「ゲームの状態」( howManyClicksrandomNumber、...) はフォームのインスタンス変数に格納されているようです。したがって、次のオプションがあります。


ゲームの状態を独自のクラスに抽出し、このクラスのインスタンスへの参照のみをフォームに保持します。

GameState state;

ゲームを開始または再開するときは、フォームのユーザー インターフェイス要素に を割り当ててリセットするnew GameState()だけです。state


または、フォームを閉じて再度開くこともできます。メイン ループは次のようになります。

while (true) {
    var form = new GameForm();
    var result = form.ShowDialog(); // waits until the form as been closed

    if (result == DialogResult.Cancel) {
        break;  // The user wants to stop playing
    }
}

ゲーム フォームでは、OKボタンがクリックされると、フォームを設定Me.DialogResultDialogResult.OKてから閉じます。外側のループは、新しい空のゲーム フォームを自動的に再開します。

于 2013-04-16T05:29:59.793 に答える