CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2011
    Posts
    1

    Making a number guessing game object-oriented

    I am trying to learn object oriented concepts. I have code for a simple number guessing game using windows forms. I am trying to make object oriented. I have had some success with console applications, but with windows forms I am increasingly confused. I realize I methods like initializegame(), gameWon(), GameLost(), FinishGame() but I'm having a hard time creating objects, and calling them, etc... Anybody have any suggestions? Also, is there a code formatting tool for this forum?

    Code:
    Namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            Random number = new Random(); // This is declaring number; our randomizer
            int randomNumber; // Our randomized number
            int guessedNumber; // Our guessed number
    
    
            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!");
                        textBox1.Clear();
                    }
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                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 = "4";
                                    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 = "4";
                            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
                }
     }
    
            private void progressBar1_Click(object sender, EventArgs e)
            {
    
            }
        }
     }
    Last edited by GremlinSA; December 7th, 2012 at 02:06 PM.

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    956

    Re: Making a number guessing game object-oriented

    So, objects are not too complicated, they're just a group of related variables, possibly with some subroutines ("methods") that are somehow related.

    So you might have something like this:

    Code:
    //Declare a class, which describes what types of data an object stores and the methods you might call
    class NumberGuessingGame
    {
        public bool gameIsOver;      //Public means I can read this variable from a subroutine outside the class
        private int randomNumber;  //Private means I can only read this variable from inside the class
    
        //A random number generator
        Random rng;
    
        //A constructor, which we will call to create a new NumberGuessingGame
        public NumberGuessingGame()
        {
            gameIsOver = false; //We haven't guessed the number yet, so the game still goes on
    
            rng = new Random();                  //Get a random number generator for this instance
            randomNumber = rng.Next(0, 10); //Get a random number between 0 and 9, inclusive
        }
    
        //Then we'll create a method that returns TRUE if a guess is correct
        public bool makeGuess(int guessedNumber)
        {
            //If the number we guessed is equal to the randomNumber stored in this object (this is a reserved keyword)
            if( guessedNumber == this.randomNumber)
            {
                this.gameIsOver = true;
                return true;
            }
    
            //Otherwise, the game continues and the guess was wrong
            return false;
        }
        
        //Or maybe we want to be able to give a string as a guess and have it interpret it as a number
        public bool makeGuess(string guessedNumber)
        {
            //Call the makeGuess subroutine associated with THIS object
            return this.makeGuess(Int32.parse(guessedNumber));
        }
    }
    So then you could call this like:

    Code:
    public static void main(string[] args)
    {
        //Make a new guessing game instance
        //An instance is a SPECIFIC collection of information
        //For example, you might have written a "class" representing book with variables like title, year of publication, etc
        //But an INSTANCE of that class is data representing some specific book (e.g. Moby Dick) using the "Book" class
    
        NumberGuessingGame myGame = new NumberGuessingGame();
    
        //Then loop until you win
        while( ! myGame.isGameOver )
        {
            Console.Write("Guess a number: ");
            string myGuess = Console.ReadLine();
    
            //Then check your guess
            myGame.makeGuess(myGuess);
    
        }  //Loop until the game is over
    
        //When they finally guess the number, display a congratulatory message and exit
        Console.WriteLine("You win!");
        
    }
    Does that make it a little more clear? You could, in principle, have several games going at the same time by declaring several instances (objects) of the NumberGuessingGame class:

    Code:
    NumberGuessingGame game1 = new NumberGuessingGame();
    NumberGuessingGame game2 = new NumberGuessingGame();
    
    //Code to play the game, separately, goes here...
    game1.guess("1") //Guess that game1's secret variable is 1...
    
    //...etc...
    Hope that helps! Try making modifications until you understand.

    Hopefully there are no syntax errors, but I pretty much just typed code into the window, so it's possible there might be some typos... (hopefully not though).
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts



HTML5 Development Center

Click Here to Expand Forum to Full Width