• (2 Pages)
  • +
  • 1
  • 2

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

#16 nnti11  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 29-March 11

Posted 26 September 2012 - 01:47 AM

Hi s3thst4,
Thanks for this tutorial, i used it and i practiced.
It's clear but i believe that you use two variables(win & Wrong) which are unnecessary.
I use this code when i click the button "Guess!":
            if (GuessNumber >= 1 && GuessNumber <= 10)
            {              
                if (RandomNumber == GuessNumber)
                {
                    DialogResult result1 = new DialogResult();
                    result1 = MessageBox.Show("You have won! Would you like to play again ?", "You win!", MessageBoxButtons.YesNo);
                    if (result1 == DialogResult.Yes)
                    {
                        RandomNumber = Number.Next(1, 10);
                        label3.Text = "3";
                        textBox1.Clear();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {
                    if (RandomNumber < GuessNumber)
                    {
                        MessageBox.Show("Lower!", "Wrong");                        
                    }
                    else
                    {
                        MessageBox.Show("Higer!", "Wrong");
                    }
                    textBox1.Clear();
                    label3.Text = (int.Parse(label3.Text) - 1).ToString();
                    if (label3.Text == "0")
                    {
                        MessageBox.Show("You have lose! The number is " + RandomNumber);
                        DialogResult result1 = new DialogResult();
                        result1 = MessageBox.Show("Do you want to play again!", "You Lose", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result1 == DialogResult.Yes)
                        {
                            RandomNumber = Number.Next(1, 10);
                            label3.Text = "3";
                            textBox1.Clear();
                        }
                        else
                        {
                            this.Close();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter an integer Number Between 1-10!", "Error!");
                textBox1.Clear();
            }


Please tell if this right or wrong. I am new in c# prongramming and i don't have experience.
Thanks
Was This Post Helpful? 0
  • +
  • -

#17 Knightmarejk  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 12-November 12

Posted 12 November 2012 - 06:22 PM

Thanks for this great tutorial. I managed to improve upon it (I'm still learning) by separating method code from handlers, and adding an ENTER keypress trigger

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace guessingGame
{
    public partial class Form1 : Form
    {
        public Form1()
        {
           InitializeComponent(); //makes all the buttons and form stuff appear
        }

        Random number = new Random();
        int randomNumber;
        int guessedNumber;
        bool newGuess = true;

        private void Form1_Load(object sender, EventArgs e)
        {
            randomNumber = number.Next(1, 10);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                try
                {
                    guessedNumber = int.Parse(textBox1.Text);
                }
                catch
                {
                    MessageBox.Show("Please enter an integer from 1-10","Error! Non-numerical character detected!");
                    textBox1.Clear();
                }
            }
            this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys); //whenever textbox changes it check if there was an enter, even when closing dialogue boxes.
        }

        private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) // enter key (either)
            {
                if (newGuess)
                {
                    newGuess = false;
                    checkGuess();
                }
            }
            else
            {
                newGuess = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            checkGuess();
        }

        private void checkGuess()
        {
            try
            {
                guessedNumber = int.Parse(textBox1.Text);
            }
            catch
            {
                MessageBox.Show("Something dun goofed");
                textBox1.Clear();
                return;
            }


            if ( (textBox1.Text == "") || !(guessedNumber >= 1 && guessedNumber <= 10) ) //nothing entered or out of range, exit condition
            {
                MessageBox.Show("Please enter an integer from 1-10!", "Error!");
                textBox1.Clear();
                return;
            }

            if (guessedNumber == randomNumber)
            {
                win();
            }
            else
            {
                failure();
            }
        }

        private void resetGame()
        {
            randomNumber = number.Next(1, 10);
            label3.Text = "3";
            textBox1.Clear();
        }

        private void win()
        {
            if (MessageBox.Show("You have won! Would you like to play again ?", "You win!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                resetGame();
            }
            else
            {
                this.Close();
            }
        }

        private void failure()
        {
            label3.Text = (int.Parse(label3.Text) - 1).ToString(); //decrement guesses
            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)
                {
                    resetGame();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                if (guessedNumber > randomNumber)
                {
                    MessageBox.Show("Lower!", "Wrong!");
                    textBox1.Clear();
                }
                else
                {
                    MessageBox.Show("Higher!", "Wrong!");
                    textBox1.Clear();
                }
            }
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                checkGuess();
            }
        }
    }
}



Was This Post Helpful? 0
  • +
  • -

#18 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5674
  • View blog
  • Posts: 12,186
  • Joined: 02-June 10

Posted 13 November 2012 - 09:37 PM

Quote

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

Or later - Its not required to use a version 7 years old. VS2012 would be good too.



01 int.Parse(textBox1.Text);
47     label3.Text



Naming like this is something we fight against every day. We try hard to get rookies into better habits and to use meaningful names for their controls, thus creating meaningful names for the handler methods they are based on.

We also strongly try to get away from this tight integration with the GUI. That's why we keep pounding on rookies to use properties and NOT reference the GUI controls throughout their code.


It feels a lot like this tutorial was built around your own homework from the first month of C# 101. While the help is appreciated I'm worried that rookies leading rookies is going to compound the bad habits we are trying so hard to overcome. When other rookies reading your tutorial are able to fix and improve on it so quickly it becomes less of a tutorial and more of a class group project.

Some of the issues I have with this are covered in my common tips post:


Some of my common tips (some may apply more than others to your specific style):
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.

  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)

  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like index, timeOut, row, column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
    You might want to look at some of the naming guidelines. Its a lot easier to start with good habits than to break bad habits later and re-learn.



  • Try to avoid having work actually take place in GUI control event handlers. It is better to have the GUI handler call other methods so those methods can be reused and make the code more readable. This is also how you can send parameters rather than use excessive global variables. Get in this habit even if you are using WinForms because WPF works a lot under the idea of "commands" and this will get you working towards that. Think of each gester, control click, menu option etc. as a command to do something such as a command to SAVE. It doesn't matter where the command comes from, all sources should point at the same target to do the actual saving.

    // All of this different triggering mechinisms call the same single [il]SavePreferences()[/il] method
    
    btnSave(object sender, eventargs e)
    {
        SavePreferences(preferencesPath);
    }
    
    <KeyboardShortcut control+s bound to save>
    <Touchscreen guesture swiping from lowerleft to upperright bound to save>
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences(@"C:\prefs\test.txt");
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();// No parameter method overload
    }
    
    FormMain_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    


  • Don't replace lines of code that don't work. Instead comment them out and put your new attempts below that. This will keep you from re-trying the same ideas over and over. Also, when you come back to us saying "I've tried this 100 different ways and still can't get it", we can actually see what you tried. So often a failed attempt is very very close and just needs a little nudge in the right direction. So if we can say "See what you did in attempt 3... blah blah" it helps a lot

    // Try #1 - May 1, 0900hrs
    //    code
    //    code  
    //    code
    // Try #2 - May 2, 1700hrs   Okay, plan B.  What if I do it *this* way
    //    code
    //    code  
    //    code
    // Try #14 - May 3, 0500hrs after 5 cans of RedBull.  Maybe I should get some sleep. I can't think of anything else but this last idea
        code
        code  
        code
    
    

    If you are using Visual Studio you can select a block of lines and hit control+k control+c (Kode Comment) to comment it out. control+k control+u (Kode Uncomment) to uncomment a selected block.

Was This Post Helpful? 0
  • +
  • -

#19 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9567
  • View blog
  • Posts: 36,213
  • Joined: 12-June 08

Posted 14 November 2012 - 12:35 AM

View PosttlhIn`toq, on 13 November 2012 - 10:37 PM, said:

Quote

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

Or later - Its not required to use a version 7 years old. VS2012 would be good too.

Be mindful the tutorial was written 10 December 2008.
Was This Post Helpful? 0
  • +
  • -

#20 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5674
  • View blog
  • Posts: 12,186
  • Joined: 02-June 10

Posted 14 November 2012 - 08:52 AM

When Herks posted to the thread it jumped to the top of the index page, and I thought it was new. And farhan3d posted just the day before. I have to be better about looking at the date of the question and not just the most recent post(s).
Was This Post Helpful? 0
  • +
  • -

#21 prototype4  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 44
  • Joined: 22-October 12

Posted 15 November 2012 - 06:50 AM

not a bad tutorial man. i am starting C# all by my onesy so this will definitely help me out since i practically know my way around the Visual Studios 2010 program. (i explore things when i get bored lol.) :rockon: :genius:
Was This Post Helpful? 0
  • +
  • -

#22 themanofsteel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-July 13

Posted 22 July 2013 - 07:36 AM

View PostDjanvk, on 12 January 2009 - 04: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.


I wanted to know how he got the text from text box on windows form application shown on http://www.youtube.c...h?v=RXBwRIlxfew

so for the calculator should i set the screen to be a text box or a label?

[/label.setText(Result)] ??

Designing a C# calculator
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2