Number Guessing Game With C#

A simple number guessing game in C#

Let's design a number guessing game in the style shown with the pictures below. The computer will hold a number between 0 and 1000. The user has 10 right to know the number. Check button is initially inactive. 

Program Codes:

namespace WindowsFormsApplication17
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int heldNumber, counter;
          

        private void Startgame_Click(object sender, EventArgs e)
        {
            Random random = new Random();
            heldNumber = random.Next(0, 1000);

            counter = 10;
            test.Text = counter.ToString();
            status.Text = "";
            textBox1.Text = "";

            controlButton.Enabled = true;

        }

        private void controlButton_Click(object sender, EventArgs e)
        {

            if (textBox1.Text == "")
            {
                status.Text = "Enter a number.";
            }
            else
            {
                int enteredNumber = int.Parse(textBox1.Text);

                if (enteredNumber  <heldNumber)
                {
                    status.Text = "Up";
                    counter--;
                }
                else if (enteredNumber  > heldNumber)
                {
                    status.Text = "Down";
                    counter--;
                }
                else
                {
                    status.Text = "CONGRATULATIONS. YOU WIN!!!";
                    controlButton.Enabled = false;
                }
            }
            test.Text = counter.ToString();

            if (counter == 0)
            {
                controlButton.Enabled = false;
                status.Text = "GAME OVER. YOU LOSE...\n Number was " + heldNumber;
            }
        }
    }
}

 

Number Guessing Game with C#, c# random number generation, random number, randomise

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 1175 times.

Online Users: 151



guessing-number-game