C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 300,428 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,481 people online right now. Registration is fast and FREE... Join Now!




C# Tutorial: Basic GUI Guessing Game

 
Reply to this topicStart new topic

> C# Tutorial: Basic GUI Guessing Game, How to write a simple Guessing Game with C#

s3thst4
Group Icon



post 10 Dec, 2008 - 07:00 PM
Post #1


Hello, I'm going to show you how to create a simple guessing game program.

First, you'll need Microsoft Visual C# 2005 or 2008 Express Edition, or Microsoft Visual Studio 2005 or 2008.

Now, create a new project. To do so, go to file, new project, Windows Application Form. Name is Guessing Game.

Change Form1's text propery to 'Guessing Game'.

Add a label to your form, and make its text property 'Guess a Number 1-10!'
You can make it from whatever number you want to whatever, it doesn't matter. I'm going to use 10, but it can easily be changed.

Now, add a textbox to go under it. Nothing to change in it's properties.

Then add a button that says "Guess!", or whatever you want.

Then add 2 labels; one that says "Tries Left:" then put the other right next to it and make it say "3".

This is what your GUI Form should look like, or at least something similar.

IPB Image

Alright, now it's time to add some code to this project.

First, we need to make our global variables. So, 2x click the form, and it should lead you to Form1's load event. Above where it says
Form1_Load, type in.

CODE

Random numer = new Random(); // This is declaring number; our randomizer
int rn; // This is declaring rn; our randomized number
int gn; // This is declaring gn; our guessed number


Now, in the form1 load event, type this in:

CODE

rn = number.Next(1,10);


That code says that gn is a randomized number with the minimum being 1 and the maximum being 10.

Then, go to the textBox's textChanged event by double-clicking it on the GUI form.

When you're there, type this in.

CODE

if (textBox1.Text != "")
{
   try
   {
      gn = int.Parse(textBox1.Text);
   }
   catch
   {
      MessageBox.Show("Please enter an integer from 1-10", "Error!");
      textBox1.Clear();
   }
}


CODE

if (textBox1.Text != "")


This says 'if textbox1's text is not equal to being empty, do this:'

CODE

try
{
  gn = int.Parse(textBox1.Text);
}
catch
{
  MessageBox.Show("Please enter an integer from 1-10!", "Error!");
  textBox1.Clear();
}


Try/Catch is an error catching. In try, you type in what you want to error-check, in this case, textBox1 parsed to an int. Parsing is transferring it from a string into an int in this case. Catch is what is displayed if the user enters an invalid character. textBox1.Clear();, obviously, clears the textbox of any text within it. And..if you don't know what MessageBox is..why are you reading this ? J/k, MessageBox.Show(); is a method that displays a MessageBox. The text before the comma is what's in it, and after the comma is the title.

Now, it's time to move on to the big code; the button1's click event. Double click the button to access it's click event. I'm going to give you 1 majorly long code; but don't freak out. I'll explain it afterwards.

CODE

            gn = int.Parse(textBox1.Text);
            bool win = false;
            bool wrong = false;
            if (textBox1.Text == "")
            {
                MessageBox.Show("Please enter an interger from 1-10!", "Error!");
                textBox1.Clear();
            }
            else
            {
                if (gn >= 1 && gn <= 10)
                {
                    if (gn == rn)
                    {
                        win = true;
                        if (win == true)
                        {
                            if (MessageBox.Show("You have won! Would you like to play again ?", "You win!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                rn = number.Next(1, 10);
                                label3.Text = "3";
                                textBox1.Clear();
                            }
                            else
                            {
                                this.Close();
                            }
                        }
                        else
                        {
                            // Do nothing
                        }
                    }
                    else
                    {
                        wrong = true;
                    }



                }
                else
                {
                    MessageBox.Show("Please enter an integer from 1-10!", "Error!");
                    textBox1.Clear();
                }
            }
            if (wrong == true)
            {
                label3.Text = (int.Parse(label3.Text) - 1).ToString();
                if (label3.Text == "0")
                {
                    if (MessageBox.Show("You have lost! The randomized number was " + rn + ". Would you like to play again ?", "You lost!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        rn = number.Next(1, 10);
                        label3.Text = "3";
                        textBox1.Clear();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {
                    if (gn > rn)
                    {
                        MessageBox.Show("Lower!", "Wrong!");
                        textBox1.Clear();
                    }
                    else
                    {
                        MessageBox.Show("Higher!", "Wrong!");
                        textBox1.Clear();
                    }
                }
            }
            else
            {
                // Do nothing
            }


We are parsing the textbox at the beginning.
Then, we are declaring 2 bool (boolean) variables, which answer the true/false question; 'win' and 'wrong', both by default set to 'false'.
So first, we check if the textbox is empty when they hit the enter button. If it is, an error message appears, if not, the rest of the code is executed.
if gn is greater than or equal to 1 or less than or equal to 10, it allows the rest of the code to be executed.
if our guessed number(gn) is equal to our randomized number (rn) then our bool variable 'win' is set to true.
if win is true, then it makes a messagebox appear asking if you want to play again, using an if to execute it. If the dialogresult is yes, then it re-randomizes the number, sets the label back to 3 (we haven't gotten to the part where the label changes yet) and clears the textbox. If the dialogresult is no, then it closes the program.
And if win is not equal to true, then do nothing. The comment is not required, it just helps me remember.
if gn is not equal to rn, then wrong is equal to true.
if gn is not greater than or equal to 1 or less than or equal to 10, it gives you the error that we've used throughout the program.
Then, finally, we're out of those ifs.
Now time for more ifs, yay! <3 smile.gif

if wrong is true, then label3.text is parsed into an int then subtracted by one then converted back to a string so that the form will accept it as text.
if label3's text is 0, then it tells you what the randomized number was, gives you an option to play again. If yes, it resets the randomized number, then makes the label equal 3 again. if no, then it closes. so if the label's text is not equal to 0, then it detects whether gn was greater than or less than rn.
if greater than, then a messagebox appears and tells you to go lower, then clears the textbox.
if less than, a messagebox appears and tells you to go higher, then clears the textbox.
And finally, if wrong is not true, then it does nothing.

Thanks for reading my tutorial smile.gif
Tell me how I did; it was my first tutorial.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Djanvk
**



post 12 Jan, 2009 - 03:15 AM
Post #2
Fun little tutorial, does a good job a basic GUI program. The only problem I found was in this line of code:

CODE
Random numer = new Random();


numer should be number.

CODE
Random number = new Random();


other than that it worked find.
Go to the top of the page
+Quote Post

s3thst4
Group Icon



post 31 Jan, 2009 - 08:38 AM
Post #3
QUOTE(Djanvk @ 12 Jan, 2009 - 03:15 AM) *

Fun little tutorial, does a good job a basic GUI program. The only problem I found was in this line of code:

CODE
Random numer = new Random();


numer should be number.

CODE
Random number = new Random();


other than that it worked find.


Haha, sorry about that. Just a typo.
Thanks, I'll go fix it immediatly.

Edit: I can't edit the Tutorial. But yeah, it was intended to be number.

This post has been edited by s3thst4: 31 Jan, 2009 - 08:41 AM
Go to the top of the page
+Quote Post

Notorion
***



post 21 May, 2009 - 07:46 AM
Post #4
Thanks for this, I am trying to get into C# after my all of my c++, and this was a good introduction for me, really helped me understand the forms, and basic member calls.

This post has been edited by Notorion: 21 May, 2009 - 07:49 AM
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/8/09 12:26AM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month