我試圖在Visual C#中創建一個Hang子手遊戲,但我遇到了按鈕單擊事件的信函問題。Visual C#Hang子手按鈕單擊事件
這是它應該如何工作的:玩家點擊一個字母按鈕(A-Z)。如果該按鈕的文本位於他應該猜測的單詞(guessWord)中,則該字母被顯示並且正確的猜測計數器遞增。如果這封信不在猜測中,他留下的機會就會減少,而一名hang子手也會被吸引。當guessGuess> = guessWord的長度時,玩家贏得比賽,當他沒有機會時(他以8開始),他將失去比賽。
我不知道我現在的代碼有什麼問題。有時當我運行它時,在點擊一個字母按鈕後,我會看到「你丟失了」框。有時,當一個正確的字母被猜出時,程序會顯示該字母,但會顯示「You lost」框。
void LetterBtn_Click(object sender, EventArgs e)
{
//Event hook-up
Button b = (Button)sender;
char letterClicked = b.Text.ToCharArray()[0];
//Disable button after it's been clicked
b.Enabled = false;
string gameOverTitle1 = "Congrats!";
string gameOverTitle2 = "Sorry!";
string gameOverMsg1 = "You won!";
string gameOverMsg2 = "You lost!";
char[] guessWordChars = guessWord.ToCharArray();
//If the character is in the word
if ((guessWord = guessWord.ToUpper()).Contains(letterClicked))
{
for (int i = 0; i < guessWord.Length; i++)
{
if (guessWordChars[i] == letterClicked)
{
//Reveal the character
lblguessWord[i].Font = new Font("Bauhaus 93", 28, FontStyle.Regular);
lblguessWord[i].Text = letterClicked.ToString();
lblguessWord[i].ForeColor = Color.Fuchsia;
//Increment counter
correctGuess += 1;
}
}
//Winning condition
if (correctGuess >= guessWordChars.Length)
{
return;
}
//Tell the player he won the game
frmGameOverBox frmGameOverBoxInstance = new frmGameOverBox(gameOverTitle2, gameOverMsg2);
frmGameOverBoxInstance.ShowDialog();
}
else
{
//Incorrect guess
if (chances > 0)
{
chances -= 1;
}
//Player lost the game
else
{
//Reveal the word
for (int k = 0; k < guessWordChars.Length; k++)
{
lblguessWord[k].Text = guessWordChars[k].ToString();
}
//Tell the player he lost the game
frmGameOverBox frmGameOverBoxInstance = new frmGameOverBox(gameOverTitle1, gameOverMsg1);
frmGameOverBoxInstance.ShowDialog();
}
}
}
除了這一切,如果有人猜測已經被猜出並已被揭示的信件,沒有什麼可以阻止他們再次猜測同一封信。更糟糕的是,那個人可以不斷猜測同一封信,每次都會被視爲一個正確的猜測,從而最終滿足'如果'條件並最終贏得每場比賽。但不是真的。 – Icemanind 2014-12-10 23:19:01
@icemanind - 是的,@ mdegges還應該保留一個布爾型'猜測'標誌數組,以防止這種情況。 – dbc 2014-12-10 23:23:44
b.Enabled = false;阻止用戶多次點擊一個字母按鈕。 – mdegges 2014-12-10 23:27:14