Using multiple images and to display at random - objective-c

How could I make it randomize what image shows up so that there is a different one displaying every time. Here is my code, and the images I want to add to get randomized are for instance "tutorial2.png" and "tutorial3.png". Where would I add them into this line of code so that it randomizing which one is displayed. I'm not too experience either so detail and code would be appreciated, thanks.
self.help=[CCSprite spriteWithFile:#"tutorial.png"];
self.help.position=ccp(ws.width/2,ws.height*4/4/2);
[self addChild:self.help];

You first add images to Array eg: theArray.
then using following code to get random index
NSUInteger randomIndex = arc4random() % [theArray count];
then.
self.help=[CCSprite spriteWithFile:[NSString stringWithFormat:#"%#",[theArray[i]]]];
self.help.position=ccp(ws.width/2,ws.height*4/4/2);
[self addChild:self.help];

Related

How do you get an int++ to keep counting past 9?

I'm relatively new to Objective-C and I'm trying to create a game.
I currently have a score counter as such:
-(void)score {
scorenumber++;
scorelabel.text = [NSString stringWithFormat:#"%i", scorenumber];
}
The problem I'm having is I can seem to get the score to keep counting past 9. every time it reaches 9 it then resets back to 0 instead of going onto 10 11 12 and so fourth.
How can I solve this? what I'm trying to accomplish is that everytime theres an intersect between coin and star it adds +1 to score and every time it passes through tunnel it adds +1 to score
heres the entire code.
Your problem is that the UILabel (or whatever else displays your number) isn't large enough to show more than one number. When it reaches 10, you only see the second digit, which is why you think it has been reset to 0.
Try making a longer scorelabel.
If your design allows you to let the label have different width, you can use sizeToFit to give it enough width to display its text
-(void)score {
scorenumber++;
scorelabel.text = [NSString stringWithFormat:#"%i", scorenumber];
[scorelabel sizeToFit]; // <------------
}

objects in array no index position

I have an array which is a parsed xml feed which i want to add to another array using the code....
int insertIdx = [blogEntries count];
for (RSSItem *nextItem in feedItems) {
[blogEntries insertObject:nextItem atIndex:insertIdx];
//[blogEntries addObject:nextItem];
insertIdx += 1;
}
For some reason all of the objects in the blogEntries array all have an index of 0, when i slog them all out using...
for (RSSItem *nextItem in blogEntries)
NSLog(#"title - %#, pos - %i", nextItem.title, [blogEntries IndexOfObject:nextItem]);
do you know why the index might not be updating?
Any help would be appreciated
Did you try to use addObject: instead of insertObject:atIndex?
Are you sure that objects are different as:
indexOfObject:
Returns the lowest index whose corresponding array value is equal to a given object.
I was not able to refrain myself On the Topic of adding many item at once into a NSMutableArray, I do prefer to use this method :
- (void)addObjectsFromArray:(NSArray *)otherArray
it remove that useless for loop. (unless you need to do some other work in that loop)
And as of your problem, viperking have a big hint about a possible problem you may be facing. (if that is the case you may need to validate your isEqual: method.

Allow User to Save Generated Array String for Later Viewing

I'm creating a small app that generates baby names from 2 separate NSArrays. I have 1 setup for first name and 1 setup for middle name. When the button is pushed it concatenates 2 NSStrings at random as seen with this code:
int a = arc4random() % 2;
int b = arc4random() % 2;
// populate the array for the names
NSArray *firstNameArray = [NSArray arrayWithObjects: #"Anna",
#"Amy",
#"Amber", nil];
NSArray *middleNameArray = [NSArray arrayWithObjects: #"Brenda", #"Beatrix", nil];
// concatenate strings at index of array
NSString *fullName = [NSString stringWithFormat:#"%# %#", [firstNameArray objectAtIndex:a], [middleNameArray objectAtIndex:b]];
// display the newly created first & middle names
babyname.text = fullName;
I'm kind of at a loss for how to allow a user to 'favorite' a particular name and save it to a new view (probably table view). Can anyone point me in the right direction here?
What you would probably want to do is store the names selected so that you could refer to them later. You may wish to create a Person class or something of the like and have a property in it called favorite which is a BOOL value. Then you would just have to set the favorite property to YES for the ones the user wants to favorite.
A good mechanism to store a custom class and have it persist is Core Data, but it really depends on how many Person instances you will/could have. Core Data is really easy to implement once you get the hang of it and there are many tuorials online of how to use it. I would check out the iTunesU videos from Stanford on CoreData using UIDocument and UIManagedDocument. I found them very helpful.
Good Luck.
You have given a snippet of your code from which the exact flow of your logic in your program is incomprehensible , assuming that u have a textfield for user to input and a button to mark it as favorite then in the action of button you can get the text from textfield and store it in some array .Moreover you don't store data in tableview but you display it there.You can then use the Favorited array to display the names in a tableview .
You can use NSUserDefaults,plist,sqlite,coredata for persistent storage.
NSUserDefaults and plist can handle only low amount data efficiently.
Please See My Link on
persistent storage
Tutorial on TableView

Error removing sprites from a spritesheet in Cocos2D

I'm in the initial building stages of an iphone game, and I'm using sprite sheets to create some random people, each one with sub-sprites for hair, clothing etc.
I'm storing my sprite images in spritesheets using CCSpriteBatchNode. I'm just doing an initial setup test now, where you tap the screen to generate a new random set of people. So the weird thing is, you can tap once and it will remove the old people and replace them with new people, but the second time, it crashes with the error:
"CCSpriteBatchNode doesn't contain the sprite. Can't remove it"
Now I'm sure I've added the sprite to the batch node, in my Person.m constructor I have this line:
[spriteSheet addChild:person];
In my test code in ccTouchesEnded I've got the following code:
//updated with changes suggested by Mazyod and Jer
for(int i=6; i>=0; i--){
Person *per = [_people objectAtIndex:i];
[_people fastRemoveObjectAtIndex:i];
[_spritesheet removeChild:per cleanup:YES];
per = nil;
}
for(int i = 0; i < 7; i++){
Person *per = nil;
per = [Citizen personFromCountry:_country1 WithSpriteSheet:_spritesheet];
per.position = ccp(100 + (50 * i),160);
[_people addObject:per];
[_spritesheet addChild:per];
}
Can anybody suggest what I'm missing? I've read a bunch about spritesheets in cocos2d and am given to understand that removing individual sprites is tricky so I'm sure there's some vital lines I need to add here. Thanks for your help!
Edit: I googled the error and found this thread: http://www.cocos2d-iphone.org/forum/topic/17170 which seems to confirm that Cocos2d thinks I'm not adding the sprite to the spritesheet - but I am, as proven by the fact that the sprites add correctly the first time, just not the second.
One solution is to simply avoid removing the sprites at all, just make them invisible and redraw them with new characteristics when they need to be reused. I'd rather know what the real solution is though because it seems cleaner.
Looks like you need to change
[_people addObject:per];
to
[_people replaceObjectAtIndex:i withObject:per];
In your first loop you are just setting the value of the object in the array to nil, but not removing it from the array. In the second loop you just add it onto the end of the array, but your array already has 7 nils in it.
Let me know if it works.
Well, I could help you clear out one thing for now:
Any CCNode can only be a child to one parent. ie It has to have a single parent.
But, what you have here:
for(int i=0; i<7; i++){
Person *per = [_people objectAtIndex:i];
[self removeChild:per cleanup:YES];
[_spritesheet removeChild:per cleanup:YES];
per = nil;
}
Suggest you are trying to add the person to both the spriteSheet and self at the same time.. Check your Log, it must have something like:
cocos2d: removeChild, child not found.
And from the error you are getting, I am betting that the person is added to self and not to the sprite sheet.
So, how to solve this?
Well, you have to add the person to the spriteSheet as a child, then add the spriteSheet to self as a child. (Actually, the order you add them doesn't matter).
Sort this out, and maybe this problem will go away, or at least it will be clearer so we can help you.
I just want to mention my experience here with this problem and how I solved it.
Remember, you are either trying to remove a child that was never added..
OR
Trying to remove a child TWICE.
This was the case for me. The collision detection in my game was solid (at least I thought). Then randomly, like 1 out of every 7-10 runs... I would get this crash. I realized it was because I had coded my projectiles to be removed once they intersected a target.
I did not however, put a failsafe where IF my tick method detected that it was in collision with MORE then 1 target at a time.
This was because for every projectile, I iterated through each target to check for a collision, then removed the respective projective if collision was detected. So I created a simple BOOL, and set it to YES if it had already collided with a target. Then I only checked for collision if the projectile had not collided with anything.
So... before:
if (CGRectIntersectsRect(projectileRect, targetRect))
{
//code to remove projectile
}
After:
if (CGRectIntersectsRect(projectileRect, targetRect) && projectile.hasHitaTarget == NO)
{
//code to remove projectile
}

view does not load at correct time

The program I'm writing has a view with several tiles on it that are scrambled properly when the following code is executed:
[self scrambleBoard];
[self.view setNeedsDisplay];
where scrambleBoard is a method I have that mixes up the tiles randomly. The above code works correctly and shows the final scrambled position of the tiles.
The problem I have is that I want to give the program the appearance of the tiles actually scrambling, sort of like animation, but not really so, it would just show 8 consecutive different scrambled views. So I incorporated the above code into the following loop:
for (int i = 0; i < 8; i++)
{
[self scrambleBoard];
[self.view setNeedsDisplay];
usleep(250000);
}
The problem is that instead of showing 8 different scrambled views in succession, I only get the final scrambled view. Any help would be appreciated - thanks in advance
Gil
My guess is that you are simply blocking the thread as a sleep is almost always the wrong thing to use on the main thread.
I believe the final view is only really calculated at the end of the runloop which will essentially just give you the result of the last jumbling.