Home > C#, Programming > Tutorial #2 – Basic Guess Game in C#

Tutorial #2 – Basic Guess Game in C#

Here is my new tutorial for you about C#. In this tutorial i am going to make a little game about guessing result of some number summation, multiplation, division and addition. And i am going to focus on handling the enter keypress event for textfield.

Here as you see from the screenshot of the main window a user should guess the result of this operation. Textbox1 equals the random number “96″, textbox2 equals the random number “73″ and there is an randomly operator which is “-” . User should guess this result and should write down the guess into the textbox3 field. When user press enter button textbox3 handles this event.

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) //Char 13 handles the enter key
{
Console.WriteLine(total);  //Here i can check the result from console for testing purposes
if (total.ToString() == textBox3.Text)
{
StringBuilder dogru_str = new StringBuilder();
dogru_str.Append(textBox1.Text);
dogru_str.Append(" " + label1.Text + " ");
dogru_str.Append(textBox2.Text + " = ");
dogru_str.Append(total + "\n");
dogru_str.Append("Your answer was correct...");
MessageBox.Show(dogru_str.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

Here dogru_str keeps the new string. Then  i am able to send this paramater to MessageBox.Show

wins += 1; //Here i can show that how many times user wins
label4.Text = wins.ToString();
textBox3.ReadOnly = true;
}
else
{
StringBuilder yanlis_str = new StringBuilder();
yanlis_str.Append(textBox1.Text);
yanlis_str.Append(" " + label1.Text + " ");
yanlis_str.Append(textBox2.Text + " = ");
yanlis_str.Append(total + "\n");
yanlis_str.Append("Your answer was wrong.!!");
MessageBox.Show(yanlis_str.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
loses += 1;
label5.Text = loses.ToString();
textBox3.ReadOnly = true;
}
}
}  

After pressing enter button it determines if it is wrong answer or not. Then user should press replay button the replay the game.

VN:F [1.9.22_1171]
Rating: 9.8/10 (4 votes cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)
Tutorial #2 - Basic Guess Game in C#, 9.8 out of 10 based on 4 ratings
  1. No comments yet.
  1. No trackbacks yet.