how can we create scoring in iphone game - iphone

I want to create score when a target is hit...
whenever a target is hit
int targetHit=0;
targerhit=targethit+1;
now I want to show that in label....
CCLabel* label2 = [CCLabel labelWithString:#"null" <-----i want to add score herer?and keep changing it ?how can i
fontName:#"Marker Felt"
fontSize:30];
label2.position = ccp(400, 295);
[self addChild:label2];

Suppose you have an integer score and String scoreString associated to a CCLabel scoreLabel. These thre elements must all be attributes of your class (maybe a CCLayer).
Now, if you just want to update the scoreLabel you have to:
//create a range object
NSRange range;
//it starts from the first character(0) and ends at the scoreString length
range.location=0;
range.length = [scoreString length];
//then delete the characters of the string which fall in the range (that means all)
[scoreString deleteCharactersInRange:range];
//then use appendFormat to update the scoreString with the latest score value
[scoreString appendFormat:#"%07d",score];
//therefore update the label
[scoreLabel setString:scoreString];

I didn't use cocos2d yet, but here is some info that i've found.
(void) setString: (NSString *) string
changes the string to render
Warning:
Changing the string is as expensive as creating a new CCLabel.

Related

Display a number in a label but have it count up the number

I have a UILabel in my class and I would like the view to display the number but to count up to the number. For example, If the number was 368, it would climb quickly to the 250-300's then start to slow down as it gets to the number. Now this number will not always be 368, the number varies. It could be 6 or 129 or 1023 so it can't be a set-in-stone number. I obviously know how to create the UILabel as I already have it being used in my app, I just need help with counting upwards to it.
I have a "Player view", blah blah blah they get a score and it is passed to another view "Gameover view" and the score is display in a the UILabel.
Here is the code for the "Player view" to pass the data:
//finalScore is a int and so is currentScore
second.finalScore = self.currentScore;
Here is the code for the "Gameover view" to pass the data:
- (void)viewWillAppear:(BOOL)animated {
// scoreLabel is the IBOutlet to the UILabel in IB for displaying the score.
self.currentIndex++;
if(self.currentIndex == [self.numbersArray count]) self.currentIndex = 0;
self->scoreLabel.text = [NSString stringWithFormat:#"%d",self->finalScore];
}
Thanks in advance!
I figured it out myself. I found this control and it works just as I need it to! Click Here
You can update the UILabel object in a loop, using the Timer. As time progresses at a certain interval, "slow it down" by adding on the difference in time. Sample code for updating a UI object via Timer is a common bit of code on the Internet, as it's the way you code progress bars.
how to use the progress bar in the iphone app
Just call this method every certain interval (ex every 0.1 seconds), using a NSTimer
It will increment the value up to the target number.
-(void)countUp:(id)sender {
int targetNumber = yourNumber;
int currentNumber = [[myLabel text] intValue];
// Calculate the increment for this time. Mess with this for different speeds.
// Just multiply some of the numbers by some constants (ex. 2) until you
// achieve the desired effect.
double increment = (targetNumber - currentNumber) / targetNumber;
NSString *newValue = [NSString stringWithFormat:#"%f",currentNumber + increment];
[myLabel setText:newValue];
if ([newValue doubleValue] >= targetValue) {
[(NSTimer *)sender invalidate];
}
}
For the timer:
[NSTimer scheduledTimerWithInterval:0.1
target:self
selector:#selector(countUp:)
userInfo:nil
repeats:YES];
using literals it become quite easy to play
UILabel * label;
label.text = #(label.text.integerValue+1).stringValue;

Using an array of strings for UISlider

I want to change a UILabel with strings based on an array. Here is what I have so far:
- (IBAction) sliderValueChanged:(UISlider *)sender {
scanLabel.text = [NSString stringWithFormat:#" %.f", [sender value]];
NSString *wholeText = #"Very Bad";
self.scanLabel.text = wholeText;
}
Instead of just "Very Bad," I want different values to show "very Bad, Bad, Okay, Good, Very Good."
Where do I declare the NSMutableArray, and how do I implement it with the slider?
Update: Thank you all for your help! (I love stackoverflow)
This is not compiler checked...but you may get some idea.
NSArray *texts=[NSArray arrayWithObjects:#"very Bad", #"Bad", #"Okay", #"Good", #"Very Good",nil];
NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
self.scanLabel.text=[texts objectAtIndex:sliderValue];
You declare it in the same class as the above method.
Let's say it's called wholeTexts.
The code will look like this:
- (IBAction) sliderValueChanged:(UISlider *)sender {
scanLabel.text = [NSString stringWithFormat:#" %.f", [sender value]];
NSString *wholeText = [wholeTexts objectAtIndex:(wholeTexts.count - 1) * (int)(sender.value - sender.minimumValue)/(sender.maximumValue - sender.minimumValue)];
self.scanLabel.text = wholeText;
}
Put your text values into an array
NSArray* array = #[#"very Bad", #"Bad", #"Okay", #"Good", #"Very Good"];
set your slider to have a min value of 0 and maximum value of 4
turn your [sender value] into an int, eg floor([sender value])
pick an item from the array using your int, eg
NSString* result = [array objectAtIndex:myInt];
You can implement the array anywhere you want, as long as it's created before you need to use the slider. Sliders can only have a value between 0 and 1 in iOS, so you'll need to multiply the value by something to get numbers as high as the number of items in your array (minus 1), and you'll need to convert them to an integer, so you can use that value as the index into the array. Something like this:
- (IBAction) sliderValueChanged:(UISlider *)sender {
scanLabel.text = [myArray objectAtIndex:(int)(sender.value * 10)];
}

Recognizing all objects generated by a loop

This question is a bit related to one I posed previously entitled "Recognizing UIButton from a loop".
In this case, I have generated a bunch of UITextFields with a loop. When the value of one of them is changed, I'm able to recognize which textfield it was.
However, I want to then edit every textfield that was generated. Specifically, I get input from the one textfield that was edited, and I want to recalculate the other textfields based on the input and name of the recognized textfield.
How do I call for every one of the other generated, non-edited textfields to be modified?
/Vlad
Since you are already using tags, this is what viewWithTag is used for:
// Get a reference to the textfield with tag 3
UITextField *textField3 = (UITextField *)[self.view viewWithTag:3];
// Calculate your new value
float result = 4.32; // Calculate the value that you want the textfield with tag 3 to display
// Change the contents
textField3.text = [NSString stringWithFormat:#"%f", result];
store the text fields in an array, then when you want to change the value
[self.myTextFieldArray enumerateObjectsUsingBlock:^(UITextField *textField, NSUInteger idx, BOOL *stop){
if (![textField isEqual:theTextFieldThatWasEdited])
textField.text = #"whatever text you want";
}];

Updating label based on picker value the very first time a view is loaded

I'm new to iPhone development, so my apologies if this is a ridiculous question.
I'm following a sample from a book where it creates a exchange rate UIPicker and when you select one of the entries, it displays the conversion of US dollars into whatever currency is picked.
I want the value to be updated in my label before I start changing the value from the picker.
The very first time i enter my US dollar value in the textbox and I click on the "Return" button, i want the label to update and displays its equivalent value in whatever currency is currently selected in the picker.
I have the correct code in the didSelectRow event, and that part works as long as i start spinning the picker's component wheels, so I thought I'd take that code and put it in a function which would have one parameter i.e. row and this function would then be called from didSelectRow where the row parameter would be passed and then I would:
This is the code from the didSelectRow:
float rate = [[exchangeRates objectAtIndex:row] floatValue];
float dollars = [dollarText.text floatValue];
float result = dollars * rate;
NSString *resultString = [[NSString alloc] initWithFormat:#"%.2f USD = %.2f %#", dollars, result, [countryNames objectAtIndex:row]];
resultLabel.text = resultString;
[resultString release];
Call this function when the "Did End on Exit" event for the textbox but my I'm having two problems:
What is the correct way to write the function. Whatever way I write the function, I get various errors/warnings
How do i get the currently select row of the picker, so that I can pass it to this function when the "Did End on Exit" event occurs when i click on the "Return" button.
Thanks
T.
I am not sure, I completely understood you what exactly you are trying to do here. but still I am going ahead what you can do here is:
first of all declare an class variable of type int which will store the row index whenever didSelectRow delegate method will be called, mean time create a method like:
-(void)updateLabel:(int) rowIndex
{
float rate = [[exchangeRates objectAtIndex:row] floatValue];
float dollars = [dollarText.text floatValue];
float result = dollars * rate;
NSString *resultString = [[NSString alloc] initWithFormat:#"%.2f USD = %.2f %#", dollars, result, [countryNames objectAtIndex:rowIndex]]; // here it will go rowIndex which is the row value you stored in your variable
resultLabel.text = resultString;
[resultString release];
}
and call this method when you hit return.
I hope this helps you.
~Manoj

Reuse Cocos2d CocosNodes

I am trying to create a cool score counter in my iPhone game, where I created the digits 0 to 9 in photoshop and I want to update the score every second.
What I am doing now is the following:
In my init I load all the digit sprites into an array, so that the array has 10 items.
I created a method which breaks down the current score (eg. 2000) into single digits and gets the sprites from the array and after that adds them to a parent CocosNode* object.
Every second I get the parent CocosNode by it's tag and replace it with the new parent object.
Currently I am already running into problems with this, because the score 2000 uses the 0-digit three times and I cannot re-use sprites.
- (CocosNode*) createScoreString:(int) score
{
NSLog(#"Creating score string : %d", score);
NSString* scoreString = [NSString stringWithFormat:#"%d", score];
int xAxes = 0;
CocosNode* parentNode = [[Sprite alloc] init];
for (NSInteger index = 0; index < [scoreString length]; index++)
{
NSRange range;
range.length = 1;
range.location = index;
NSString* digit = [scoreString substringWithRange:range];
Sprite* digitSpriteOriginal = [self.digitArray objectAtIndex:[digit intValue]];
Sprite* digitSprite = [digitSpriteOriginal copy];
[digitSprite setPosition:cpv(xAxes, 0)];
xAxes += [digitSprite contentSize].width - 10;
[parentNode addChild:digitSprite];
}
return parentNode;
}
Am I handling this the right way within cocos2d or is there some standard functionality for this? Also, if this is correct, how can I 'reuse' the sprites?
I believe that you want to use the LabelAtlas class, you'll only need to provide a compatible bitmap (like one the fps counter uses).