2013-04-16 37 views
1

我正在嘗試爲我製作的簡單數字猜測遊戲添加代碼。一旦用戶猜到了正確的號碼,就會彈出消息對話框,告訴他他是勝利者。當我點擊它時,該消息對話框中有一個名爲「ok」的按鈕,我將回到表單。當用戶點擊消息對話框「ok」按鈕時重新啓動代碼

相反,我希望它重新啓動代碼,以便生成一個新的隨機數。這是可能的還是我需要手動將代碼恢復到優勝者代碼區域內的默認狀態?

這裏是我現在的代碼:

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(); 
     } 

回答

1

簡單地使功能驗證碼。

選擇所有的代碼,然後用鼠標右鍵單擊它,選擇第二個選項:Refactor

選擇子選項:Extract a method

您可以爲此公開方法命名。

然後你可以從任何地方調用這個方法,(正如你所說的重啓代碼)。

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,然後關閉該窗體。外層循環會自動重新打開一個新的空遊戲窗體。

相關問題