Building a simple guessing game, iPhone - iphone

I'm trying to build a simple guessing game. I'm having a weird problem:
-(int)setRandom {
randomNum=(int)arc4random() % 100;
return randomNum;
}
-(IBAction)submit
{
num=[self setRandom];
if([numberField.text intValue] > num)
randomNumLabel.text=#"Too high. Try again";
else if([numberField.text intValue] < num)
randomNumLabel.text=#"Too low. Try again";
else
randomNumLabel.text=#"You got it, congrats!";
}
The problem is that I get a new random number every time I press submit. I thought that the first method would create the random number, and it would be the same every time, but apparently not. How do I fix this?

Don't call setRandom every time in submit. arc4random() returns a new random number every time you call it.
Create a property to store the random number and set it only when you need to -- in init and when the game resets.

For this purpose you need a global variable.so first a fall declare
NSInteger num; in .h class then in viewDidLoad write like this
- (void)viewDidLoad {
num=[self setRandom];
//you stuff
}
then in submit
-(IBAction)submit
{
if([numberField.text intValue] > num)
randomNumLabel.text=#"Too high. Try again";
else if([numberField.text intValue] < num)
randomNumLabel.text=#"Too low. Try again";
else
{
randomNumLabel.text=#"You got it, congrats!";
num=[self setRandom];
}
}
-(int)setRandom {
randomNum=(int)arc4random() % 100;
return randomNum;
}
Here you get a random number at view load then you get new random number when your answer matches with the number.
So this will help you.

Related

I have phone number which I want to show the number first three number and last two number like 700XXXXX20 like this?

I have phone number which I want to show the number first three number and last two number like 700XXXXX20 like this. How can I show that? Can anyone please help me?
Doesn't substring work for you?
Something like
String hiddenPhone = '${phone.substring(0,3)}${'X' * (phone.length - 5)}${phone.substring(phone.length - 2)}';
var i =0;
var buffer = new StringBuffer();
<your number string>.runes.forEach((int rune) {
++i;
var character=new String.fromCharCode(rune);
if(i >2 && i<9){
buffer.write("*");
}else{
buffer.write(character);
}
});
print(buffer);
You can use buffer for your state change to update UI

How Do I Implement If-Statement within Method?

Im a noob to iphone development and I am having trouble implementing an if-statement within the didSelectIndex method of AwesomeMenu. The method fires and returns the value of the index selected, but it doesn't respond when I attempt to use the index in a conditional statement within the method. For example, my log only prints "Select the index : 0", but not "Index 0". This is very frustrating to say the least. Any help is greatly appreciated.
MY CODE:
- (void)AwesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx{
if (idx==0) {
NSLog(#"Index 0"); //Doesn't print
}else if(idx==1){
NSLog(#"Index 1"); //Doesn't print
}else{
NSLog(#"Else Block test"); //Doesn't print
}
NSLog(#"Select the index : %d",idx); //<--This Works.
}
The delegate is simply set incorrectly.
The boilerplate code for Awesome Menu includes the NSLog statement that is being called. Your above code is fine. You are simply not setting the delegate for the menu to the appropriate object. As a result, your above code never runs.
If you need assistance in this matter, please post the code demonstrating how you initialize your AwesomeMenu.
In any case, search your entire project for the phrase "Select the index" and you will find the delegate method that is actually being executed instead of your current code.
There is no problem with your If - else statement. check your (NSInteger)idx closely.
Its working fine
[self AwesomeMenu:nil didSelectIndex:1];
- (void)AwesomeMenu:(id )menu didSelectIndex:(NSInteger)idx{
if (idx==0) {
NSLog(#"Index 0"); //Doesn't work
}else if(idx==1){
NSLog(#"Index 1"); //Doesn't work
}
NSLog(#"Select the index : %d",idx); //<--This Works.
}
Output
Index 1
Select the index : 1
You can try:
NSInteger i = 2;
NSInteger j = 2;
if (i == j) {
NSLog(#"equal")
}

How can I control UISlider Value Changed-events frequency?

I'm writing an iPhone app that is using two uisliders to control values that are sent using coreBluetooth. If I move the sliders quickly one value freezes at the receiver, presumably because the Value Changed events trigger so often that the write-commands stack up and eventually get thrown away. How can I make sure the events don't trigger too often?
Edit:
Here is a clarification of the problem; the bluetooth connection sends commands every 105ms. If the user generates a bunch of events during that time they seem to que up. I would like to throw away any values generated between the connection events and just send one every 105ms.
This is basically what I'm doing right now:
-(IBAction) sliderChanged:(UISlider *)sender{
static int8_t value = 0;
int8_t new_value = (int8_t)sender.value;
if ( new_value > value + threshold || new_value < value - threshold ) {
value = new_value;
[btDevice writeValue:value];
}
}
What I'm asking is how to implement something like
-(IBAction) sliderChanged:(UISlider *)sender{
static int8_t value = 0;
if (105msHasPassed) {
int8_t new_value = (int8_t)sender.value;
if ( new_value > value + threshold || new_value < value - threshold ) {
value = new_value;
[btDevice writeValue:value];
}
}
}
I guess that it does make sense to still triggered them... What I would do in your case, would be to check the delta between the current value and the previous value. For instance:
Current value -> 5.
Next value -> 6.
Delta 1
Just a bit of pseudo-code:
if(delta>5){
//do your stuff
}
I wouldn't probably do this but:
-(void)sliderValueChanged:(UISlider *)sender{
[self performSelector:#selector(removeAction:) withObject:sender afterDelay:0.3];
// Do your stuff
}
- (void)removeAction:(UISlider *)sender{
[sender removeTarget:self action:#selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
[self performSelector:#selector(addAction:) withObject:sender afterDelay:0.3];
}
- (void)addAction:(UISlider *)sender{
[mySlider addTarget:self action:#selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
}
I didn't tested this, but I think you get the idea.
You could get complicated and filter the input from the slider based on either some timestamp or whether the difference between the new value and the old value is greater than some threshold.
A simpler way would be to just use a different event: touchEnded. That way you are only sending a final value and not all the intermediate values.
May not be appropriate for your app but it is not entirely clear what you are needing to do.
Just an idea, but what you could do is not send in the value changed event. You could store the value of the last transmission in a variable, then you could have a timer running in the background that checks if the last value sent is different to the current slider value, if it is then send the new value. The timer could be set to fire every 105ms and it will only send value every 105ms if the new value is different to the last sent value.

Problem with stringByEvaluatingJavaScriptFromString

I wanna to know abt "stringByEvaluatingJavaScriptFromString".
According to the apple doc.
"The result of running script or nil if it fails."
I have a method in which inside a for loop i'm passing a string value to stringByEvaluatingJavaScriptFromString. what will it do ?? will this get response for every string or something else will happen??
I was doing like this...
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options {
for (int idx = 0; idx < [endPoints count]; idx ++)
{
NSString *msg = [NSString stringWithFormat:#"loadDirections('%#', '%#', %#)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
[googleMapsAPI stringByEvaluatingJavaScriptFromString:msg];
}
}
Inorder to get response to every string what should I do? I think that it should get response to every string that i'm passing here. Please tell me what m doing wrong and how would i manipulate my code to get response to all strings that m passing.
Any help would be appreciated .Thnx in advance.
You should make your javascript method to return a default string or something if even an error occurs in the script.
function loadDirections()
{
try
{
//Your code goes here which returns some result
}
catch(err)
{
var errorFlag = "ERROR";
return errorFlag;
}
}
and then you should alter your Objective C code like below
NSString *msg = [NSString stringWithFormat:#"loadDirections('%#', '%#', %#)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
if([msg isEqualToString:#"ERROR")
{
//Do some error handling
}
else
{
//Your actual code goes here
}
Update for the comment:
To solve your javascript asynchronous problem either (1) you can change your design and call the javascript method only after getting response from the first call (2) or else you can use NSTimer which will will give a little time for the execution. In my opinion changing your design as per the first option would be perfect.
Have a look at these questions
stringByEvaluatingJavaScriptFromString doesn't always seem to work
return value javascript UIWebView

How to get high scores from OpenFeint?

In their support OpenFeint give you this, but I don't quite understand. How can I get the leaderboard data, say top 10 and show it in my own UI?
Original link: http://www.openfeint.com/ofdeveloper/index.php/kb/article/000028
[OFHighScoreService getPage:1 forLeaderboard:#"leaderboard_id_string" friendsOnly:NO silently:YES onSuccess:OFDelegate(self, #selector(_scoresDownloaded:)) onFailure:OFDelegate(self, #selector(_failedDownloadingScores))];
- (void)_scoresDownloaded:(OFPaginatedSeries*)page
{
NSMutableArray* highscores = nil;
if ([page count] > 0)
{
if ([[page objectAtIndex:0] isKindOfClass:[OFTableSectionDescription class]])
{
// NOTE: In the following line, we access "[page objectAtIndex:1]" to retrieve high scores from
// the global leaderboard. Using "[page objectAtIndex:0]" would retrieve scores just for the local player.
// Older versions of OpenFeint did not break this out into 2 sections.
highscores = [(OFTableSectionDescription*)[page objectAtIndex:1] page].objects;
}
else
{
highscores = page.objects;
}
}
for (OFHighScore* score in highscores)
{
// ...
}
}
- (BOOL)canReceiveCallbacksNow
{
return YES;
}
The code to request a page of high scores is the first line, i.e.:
[OFHighScoreService getPage:1 forLeaderboard:#"leaderboard_id_string" friendsOnly:NO silently:YES onSuccess:OFDelegate(self, #selector(_scoresDownloaded:)) onFailure:OFDelegate(self, #selector(_failedDownloadingScores))];
You put this line in the place where you want to start the query for high scores. You can change the page number as required. Once the page of high scores has been retrieved, the callback _scoresDownloaded is called. The example shows you how you would iterate through the OFHighScore objects in the highscores array. You would replace the comment // ... with your own code to show the scores to the player, or whatever.
(In case of error _failedDownloadingScores is called; you should implement that to show an error.)