• (2 Pages)
  • +
  • 1
  • 2

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

#1 s3thst4  Icon User is offline

  • a * a = (b * b) + (c * c) - 2(b)(c)cos(A)
  • member icon

Reputation: 10
  • View blog
  • Posts: 587
  • Joined: 20-November 08

Posted 10 December 2008 - 08:00 PM

*
POPULAR

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 property 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 its 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".

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

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

Random number = new Random(); // This is declaring number; our randomizer
int randomNumber; // Our randomized number
int guessedNumber; // Our guessed number



Now, in the Form1 Load event, type this in:

randomNumber = number.Next(1,10);



That code says that randomNumber 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:

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



if (textBox1.Text != "")



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

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



try/catch is an error catching control structure. In the try block 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 its Click event. I'm going to give you 1 majorly long code, but don't freak out. I'll explain it afterward.

guessedNumber = int.Parse(textBox1.Text);
bool win = false;
bool wrong = false; 
if (textBox1.Text == "")
{
    MessageBox.Show("Please enter an integer from 1-10!", "Error!");
    textBox1.Clear();
}
else
{
    if (guessedNumber >= 1 && guessedNumber <= 10)
    {
    	if (guessedNumber == randomNumber)
	{
	    win = true;
	    if (win == true)
	    {
		if (MessageBox.Show("You have won! Would you like to play again ?", "You win!", MessageBoxButtons.YesNo) == DialogResult.Yes)
		{
		    randomNumber = 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 " + randomNumber + ". Would you like to play again ?", "You lost!", MessageBoxButtons.YesNo) == DialogResult.Yes)
	{
	    randomNumber = number.Next(1, 10);
	    label3.Text = "3";
	    textBox1.Clear();
	}
	else
	{
	    this.Close();
	}
    }
    else
    {
	if (guessedNumber > randomNumber)
	{
	    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 guessedNumber 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(guessedNumber) is equal to our randomized number (randomNumber) 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 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 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 guessedNumber is not equal to randomNumber, then wrong is equal to true.
If guessedNumber 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 :)

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 and gives you an option to play again. If yes, it resets the randomized number, then makes the label equal 3 again; if no, then the application closes. So if the label's text is not equal to 0, then it detects whether guessedNumber was greater than or less than randomNumber.
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 :)
Tell me how I did; it was my first tutorial.

Is This A Good Question/Topic? 6
  • +

Replies To: C# Tutorial: Basic GUI Guessing Game

#2 Djanvk  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 80
  • Joined: 14-December 08

Posted 12 January 2009 - 04:15 AM

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

Random numer = new Random();


numer should be number.

Random number = new Random();


other than that it worked find.
Was This Post Helpful? 0
  • +
  • -

#3 s3thst4  Icon User is offline

  • a * a = (b * b) + (c * c) - 2(b)(c)cos(A)
  • member icon

Reputation: 10
  • View blog
  • Posts: 587
  • Joined: 20-November 08

Posted 31 January 2009 - 09:38 AM

View PostDjanvk, on 12 Jan, 2009 - 03:15 AM, said:

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

Random numer = new Random();


numer should be number.

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 January 2009 - 09:41 AM

Was This Post Helpful? 0
  • +
  • -

#4 Notorion  Icon User is offline

  • D.I.C Regular

Reputation: 35
  • View blog
  • Posts: 378
  • Joined: 17-February 09

Posted 21 May 2009 - 08:46 AM

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 - 08:49 AM

Was This Post Helpful? 0
  • +
  • -

#5 Guest_Kashif Intizam*


Reputation:

Posted 09 April 2010 - 01:26 AM

I m really impressed with your work. I m glad to have read this article. It was a great way of putting forward your ideas on this subject?? I m relieved to find such good work after going through such pains in searching for the appropriate matter for my project??. Congratulations.
Kashif Intizam

This post has been edited by tlhIn`toq: 13 November 2012 - 09:16 PM
Reason for edit:: No need to quote the entire post

Was This Post Helpful? 0

#6 jayxx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 06-May 10

Posted 11 May 2010 - 06:16 PM

Thanks for that, the main thing I learnt was that you can say:


int.Parse(textBox1.Text);


instead of what I always put:


Convert.ToInt32(textBox1.Text);


I assume you can also parse from and to many other value types, as I have heard of parsing before, but didnt have a clue what it was.

I do think this method can be shortened, but well done for a first tutorial.
Was This Post Helpful? 0
  • +
  • -

#7 Guest_Andre*


Reputation:

Posted 04 June 2010 - 08:43 AM

I keep getting "rn/gn does not exist in current context" and i made sure it was defined in the "Form1_Load", no idea what im doing wrong :/
Was This Post Helpful? 0

#8 phammond77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-June 10

Posted 22 June 2010 - 10:07 PM

View PostAndre, on 04 June 2010 - 07:43 AM, said:

I keep getting "rn/gn does not exist in current context" and i made sure it was defined in the "Form1_Load", no idea what im doing wrong :/



You have to make sure that you declare them before the "Form1_Load".
Was This Post Helpful? 0
  • +
  • -

#9 keisal  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 2
  • Joined: 05-December 10

Posted 05 December 2010 - 11:02 PM

I haven't done your tutorial yet so this really isn't about how it works but I read over it and personally variable names like rn and gn drive me insane. They say nothing about what the variable contains...I shouldn't have to look at the comments to see you mean random number and guessed number. Also it makes it really difficult to read my eyes just jump past them since its only two letters. I know I am probably being difficult but honestly if it wasn't for the praise this tutorial received I probably wouldn't bother reading it due to this. Just a suggestion that in the future you make more descriptive variable names.

MOD EDIT: Changed variable names; cleaned up the tutorial a bit.

This post has been edited by JackOfAllTrades: 06 December 2010 - 02:45 PM

Was This Post Helpful? 2
  • +
  • -

#10 Fallenrat  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 14-October 11

Posted 15 October 2011 - 06:30 AM

Awesome Tutorial! Thanks
Was This Post Helpful? 0
  • +
  • -

#11 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 181
  • View blog
  • Posts: 777
  • Joined: 27-October 11

Posted 28 October 2011 - 11:25 AM

View Postjayxx, on 12 May 2010 - 01:16 AM, said:

Thanks for that, the main thing I learnt was that you can say:


int.Parse(textBox1.Text);


instead of what I always put:


Convert.ToInt32(textBox1.Text);


I assume you can also parse from and to many other value types, as I have heard of parsing before, but didnt have a clue what it was.

I do think this method can be shortened, but well done for a first tutorial.


Sorry for realiving a dead thread but:

it's best to use
int.TryParse(textBox1.Text, out variable);

This way you can see if the conversion succeded since this method returns a bool indicating if it succeded or not...
What you could do is:
bool success = int.TryParse(textBox1.Text, out gn);


And then check the bool if it's true or not to see if the conversion succeded...
If you type like that you should put that in a try statement and catch the FormatException from the conversion if it fails. And in it change a variable indicating the success of the conversion...

This is all to make your code more robust.

All in all. Good tut. Should submit it to the tutorials section rather than just post it here... (advice)
Was This Post Helpful? 0
  • +
  • -

#12 Creative Ginger  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 11-July 12

Posted 22 August 2012 - 02:54 AM

Hi just wanted to say thanks for this tutorial.
This was my first time doing anything with c# and it was quite easy to follow, are there any more tutorials similar to this, or do you have any advice of where to go from here as I really want to learn more about c# and your tutorial has been the clearest one for me so far
Was This Post Helpful? 0
  • +
  • -

#13 farhan3d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 17-September 12

Posted 20 September 2012 - 01:58 AM

Thanks for this tutorial! I'm just getting started with C# .NET programming and have never had any experience with dialogs before. It's an interesting tutorial which covers a number of things.
Was This Post Helpful? 0
  • +
  • -

#14 Herks  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 23-August 12

Posted 21 September 2012 - 01:24 AM

Thanks, your tutorial is clear and easy to grasp for beginners.
Was This Post Helpful? 0
  • +
  • -

#15 Bipurna  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-September 12

Posted 24 September 2012 - 07:52 AM

i really tried it but shows the message the name guess number doesn't exist in the current form please help
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2