★ TouchArcade needs your help. Click here to support us on Patreon.

Simple guess counter

02-06-2009, 10:48 AM
#1
Senior Member [Original Poster]
Joined: Feb 2009
Posts: 156
Simple guess counter

I recently dove head first into objective c. I made a simple number guessing game and I would like to keep track of the guess count. I tried using the easy way

guessCount = guessCount +1

But it doesn't seem to be working. Any thoughts? I can't believe it is too difficult to do.
02-06-2009, 11:13 AM
#2
Quote:
Originally Posted by Turk View Post
I recently dove head first into objective c. I made a simple number guessing game and I would like to keep track of the guess count. I tried using the easy way

guessCount = guessCount +1

But it doesn't seem to be working. Any thoughts? I can't believe it is too difficult to do.
It would help to have a little more info than just that one line. How and where do you declare guessCount.

if you did:


Code:
- (void)checkGuess{
int guessCount;

//Some code to determine if guess was correct or not

guessCount = guessCount + 1;
}
and then you called that method each time, you'd overwrite any stored information in guessCount. i.e. each time guessCount would be reset to 0.

Instead you'll want to declare an instance variable at the top of your .m file.

So something like

Code:
@implementation YourViewController

int guessCount = 0;

- (void)checkGuess{

//Your code to determine correct guess

guessCount++; //"++" is the abbreviated code for guessCount = guessCount + 1;

}
If you have any questions shoot me a message. Also we have free video tutorials on our website for budding developers.
02-06-2009, 12:28 PM
#3
Senior Member [Original Poster]
Joined: Feb 2009
Posts: 156
Thanks for the reply and sorry I wasn't more specific. I declare the variable guessCount in the method that gets called when you press the button to generate the random number. The guess checking is done in a seperate method that begins (before the checking) with

guessCount = guessCount + 1

I declare the int guessCount in my .h file. I assign it a value of 0 in the generateRandomNumber method. Maybe the declaration needs to be in my .m within the generateRandomNumber method?

And I have checked out your site. Very informative and helpful!

Last edited by Turk; 02-06-2009 at 12:32 PM.
02-06-2009, 01:14 PM
#4
Quote:
Originally Posted by Turk View Post
I assign it a value of 0 in the generateRandomNumber method.
Well there's your problem! Every time you generate a random number what happens to your guessCount?

It gets turned back into a 0;

Try this instead

Code:
#import "guessCountViewController.h"

@implementation guessCountViewController

int guessCount = 0;

- (void)generateRandomNumber{
	//YOUR CODE
}

- (void)checkGuess{
	//YOUR CODE
	
	guessCount++;
}
That way you'll never reassign 0 to guessCount.