Sign in to follow this  
Dhadson

Guess your number game... assistance required

Recommended Posts

Hi everyone, I am loathe to do this, as I hoped I could solve this myself, yet despite my efforts I am in need of some assistance. As you may guess, I am new to programming and still learning. I have made some very basic programs, and I am slowly advancing with my work. I have now struck a problem where I am unable to get this game to do what I wish. The game is for the computer to guess your number (a variation on the old "guess your number" game... I basically modified a old version of mine to create this) yet I obviously don't have the skill to implement this properly and I am unsure where to look. With the game, I have the player think of a number, and the computer to guess a number between 1 and 100. The player tells the computer if the guess is correct, higher, or lower. The main problem is that if the game doesn't like the player saying lower... and that the computer doesn't recognise any limits on the range. I am sure that there are many more problems... yet these are the ones I am struggling with presently. Ultimately, I wish to get the game to a stage that a player will choose from a menu if he wants to guess, or for the computer to guess, creating a scoring system in the process where you compete against the computer. I also want to have the option that should a player obviously cheat against the computer (by giving conflicting advise when the computer guesses a number) the computer will quit the game on the player... yet that is something I will work on in the future. So, in short, I would very much appreciate any advise on the below source concerning the major problems mentioned above...

#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#include <ctime>

using namespace std;

char playAgain();

int main(int argc, char *argv[])
{
  int guess;
  char correct;
  int lrange=0;
  int hrange=100;
  char answer;
  
  cout << "\t***Guess the number***\n\n" << endl;
  cout << "I will try try to guess the correct number in the least tries." << endl;  
  cout << "When I make a guess please enter h for higher, l for lower, or y for a correct answer.\n" << endl;

  char again;
  
  while (again != 'n')
  {
    int tries = 0;
    
    
    do
      {	
      while (guess > lrange || guess < hrange)

      {
	   srand(time(0)); //this is to seed the rand
  
	   int randomNumber = rand();  //generate rand
  	
	   int number = (randomNumber % 100) + 1; // number between 1 - range 
	  
         cout << "My guess is " << number << "\nIs this correct?\n" << endl;

         cin >> correct;
         ++ tries;
         
         
         if (correct == 'y')
         {break;}
         else
         cout << "Was I high (h) or low (l)?" << endl;
         cin >> answer;
         
         if (answer == 'l')
         {cout << "I guessed to low...\n" << endl;
	     lrange=guess;
	     continue;}
    
         if (answer == 'h')
         {cout << "I guessed to high...\n" << endl;
	     hrange=guess;
	     continue;}
	     
        }
      }
        while (correct != 'y');
  
          cout << "Wonderful, I guessed correctly." << endl;
                
          if (tries ==1)
              cout << "Oh Wow!  I have set a new record of only " << tries << " try." << endl;
          else 
              cout << "It took me " << tries << " tries to guess the number.  I think I can do better." << endl;
          
        
  again = playAgain();
         
  } 
  cout << "Thanks for playing" << endl;
 
  system("PAUSE");	
  return 0;
}
char playAgain()
    {
      char response;
        do
          {
              cout << "Play 'Guess the number' again? (y/n)" << endl;
                  cin >> response;
                    } while (response != 'y' && response != 'n');
  
    return response;
    }




Share this post


Link to post
Share on other sites
I'll just list some things that'll hopefully get you pointed in the right direction:

1) What's the difference between <cstdio> and <stdio.h>? The answer is that <stdio.h> isn't necessarily compliant; you only need to #include <cstdio>.

2) When you compile, did you get any warnings? If so -- pay attention to them. They actually hold the clue to your problems. On my end, these are the warnings I encounter:
Quote:
warning C4700: local variable 'again' used without having been initialized
warning C4700: local variable 'guess' used without having been initialized

3) To use the random functions in C++ (and any other language), you only need to seed the random function once, at the beginning of your program. Multiple calls to srand( ) are usually only utilized when wanting to recreate specific results based on a known seed value. As it is, just calling it once will serve to sufficiently randomize succeeding calls to rand( ).

4) Learning the structure of an if/else tree will make your code more readable, especially when there are lots of continues involved.

5) This.

6) system("PAUSE"); is a little on the not-quite-right side. The correct way to keep the program from disappearing before you can read the final output is to run it as an end user would - from the command line. For debugging purposes, it's easy enough to put a breakpoint there, or, if using a Visual Studio flavor, ctrl-F5 will run without debugging, and won't return immediately.

7) This
int randomNumber = rand();  //generate rand
int number = (randomNumber % 100) + 1; // number between 1 - range
is the same as this: int number = (rand( ) % 100) + 1;
There are several other places where some variables aren't needed, and getting rid of them completely could clean things up a bit.

These should help you not only get it up and running, but up and running more smoothly and simply. Post back with more questions!
-jouley

Share this post


Link to post
Share on other sites
Thank you for the quick response jouley,
I do have some questions...

1) Do you mean that #include <cstdio> should replace #include <stdlib.h>? You mentioned stdio.h yet I don't have that in my code (or at least I don't think I have it).

2) I didn't get any warnings when I compiled... I am using DEV-CPP, so that could be related. Anyway, I have taken your advise here and intitiated the variables before they are used.

3) I thought that srand needed to be part of the whole random generation part... thanks for pointing that out to me. I have now placed it out of the scope of the While loop... I will play with that and see how that tidies it up.

4) I agree... my code is somewhat messy. I will clean this up, yet is this part of the problem with my not getting the code to do what I require?

5) thanks for that link... I have read it and I understand that I should be more judgmental about where I use Namespace.

6) I am not sure what else to use instead of system("PAUSE");. I want the window to remain open so I can assess the outcome, yet apart from waiting for an imput, I don't know another way but pause. Any advise is welcome.

7) I have cleaned it somewhat... yet some of the variables seem to be fairly important... although I don't know if that is really true. I am trying to make the random numbers be selected from a certain range, at the start the range is from 1-100, yet after that it is to regenerate numbers until it is within the new range specified by the responses to the computer's guesses. This was my best solution to the problem, yet again I would welcome advise on better avenues.

Share this post


Link to post
Share on other sites
Quote:
Original post by Dhadson
1) Do you mean that #include <cstdio> should replace #include <stdlib.h>? You mentioned stdio.h yet I don't have that in my code (or at least I don't think I have it).

Apologies, I mistyped. The same idea holds for <cstdlib> and <stdlib.h> -- you only need the former. Sorry for the confusion.

Quote:
2) I didn't get any warnings when I compiled... I am using DEV-CPP, so that could be related. Anyway, I have taken your advise here and intitiated the variables before they are used.

Ah - check your configurations, and see if you have everything set to as picky as it can go; I haven't used Dev-C++ in a while, so I'm not sure what to look for, or even if it's possible, but those warnings should definitely be mentioned.

Quote:
4) I agree... my code is somewhat messy. I will clean this up, yet is this part of the problem with my not getting the code to do what I require?

I think the problem will become more noticeable when you clean things up. In particular -- what's the difference between guess and number?

Quote:
6) I am not sure what else to use instead of system("PAUSE");. I want the window to remain open so I can assess the outcome, yet apart from waiting for an imput, I don't know another way but pause. Any advise is welcome.

Have you gotten to know Dev-C++'s debugging capabilities? If no, I'd highly recommend it. Stepping through the code a line at a time will help you find problems much more quickly. If you have, then you'll recognize the term breakpoint - just put one at the end of your code, it'll break execution before things disappear.

Running the program from the command line is another option.

Quote:
7) I have cleaned it somewhat... yet some of the variables seem to be fairly important... although I don't know if that is really true. I am trying to make the random numbers be selected from a certain range, at the start the range is from 1-100, yet after that it is to regenerate numbers until it is within the new range specified by the responses to the computer's guesses. This was my best solution to the problem, yet again I would welcome advise on better avenues.

The cleanliness and careful usage of variables will really help in finding errors. (See numbers 2 and 4.) As far as getting a random number in the range goes,
int aRandomNumberInTheRange = (rand( ) % (highLimit - lowLimit)) + lowLimit;
That should do the trick, and it's pretty straightforward.

8) Why do you declare all your variables at the beginning of main( )? This is necessary in C, but not really a good practice in C++. Declaring variables near their first use can cut down on memory usage and, perhaps more importantly in this case, clarifies code and points out *possible* unnecessary variables.

Keep it up - when you get it working, I think you'll understand the importance of code clarity. Also, learning to use your debugger is key. Best of luck!
-jouley

Share this post


Link to post
Share on other sites
Quote:
Original post by Dhadson
1) Do you mean that #include <cstdio> should replace #include <stdlib.h>? You mentioned stdio.h yet I don't have that in my code (or at least I don't think I have it).

No, stdlib.h should be replaced by cstdlib. He probably just forgot what you wrote :). stdlib.h is a library header for C. C++ includes all standard functionality in the std namespace while C does not. So C++ kept the functionality but changed the names of the headers by dropping .h from the end and adding a c to the beginning.

Quote:
3) I thought that srand needed to be part of the whole random generation part... thanks for pointing that out to me. I have now placed it out of the scope of the While loop... I will play with that and see how that tidies it up.

Here's how rand and srand usually work. It saves the last value used and does some math on it to make a new value. Something like this(except the results will probably be a lot more random):

unsigned long next = 1;
int rand (void)
{
next = next * 1103515245L + 12345L;
return (unsigned int)((next > 16) & 0x7fff;
}
void
srand (unsigned int seed)
{
next = seed;
}


Quote:
4) I agree... my code is somewhat messy. I will clean this up, yet is this part of the problem with my not getting the code to do what I require?


Cleaner code is often easier to debug and find problems. If you can't read it, how can you fix it?

Quote:
6) I am not sure what else to use instead of system("PAUSE");. I want the window to remain open so I can assess the outcome, yet apart from waiting for an imput, I don't know another way but pause. Any advise is welcome.

Learn about the Command Line. To open the command line go to the start menu, then type 'cmd' in the run window. There's also a link somewhere in the start menu that will open it directly, but I'm on a mac right now and can't remember where. This will give some type of overview on the command line:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true

Basically if you want a quick and dirty way to run the program without that pesky 'system("pause");' in your code you need to change the way you run the program. Visual C++ allows for 'run without debuggin' which would keep the program open automatically. You can distribute a batch file with the text
NAME_OF_PROGRAM
pause
inside it and have the user click that file to run your program.

Hope this helps at least a little bit.

Share this post


Link to post
Share on other sites
Thanks to you both, I have tried to follow your advise... yet I still encounter the same problems.

There seems to be one main problem with the game. The game doesn't have a problem if you tell it the number is higher or lower... yet if on later guesses you change instructions (for example, the first guess was low, and the second was high) the game hangs.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this