How to cycle through an array of CGPoints - objective-c

I have created an array of 16 CGpoints representing 16 positions on a game board. This is how i set up the array CGPoint cgpointarray[16]; I would like to create a for loop to cycle through each item in the array and check if the touch is within x distance of a position (i have the position as a CGPoint. I don't have much experiance with xcode or objective c. I know the python equivalent would be
for (i in cgpointarray){
//Stuff to do
}
How would i accomplish this? Thanks

for (int i = 0; i < 16; i++){
CGPoint p = cgpointarray[i];
//do something
}
Or if you want to use the NSArray Class:
NSMutableArray *points = [NSMutableArray array];
[points addObject:[ NSValue valueWithCGPoint:CGPointMake(1,2)]];
for(NSValue *v in points) {
CGPoint p = v.CGPointValue;
//do something
}
( not tested in XCode )

This should do it:
for (NSUInteger i=0; i < sizeof(cgpointarray)/sizeof(CGPoint); i++) {
CGPoint point = cgpointarray[i];
// Do stuff with point
}

I would normally go for the NSValue approach above but sometimes you are working with an API where you can't change the output. #Andrews approach is cool but I prefer the simplicity of .count:
NSArray* arrayOfStructyThings = [someAPI giveMeAnNSArrayOfStructs];
for (NSUInteger i = 0; i < arrayOfStructyThings.count; ++i) {
SomeOldStruct tr = arrayOfStructyThings[i];
.... do your worst here ...
}

Related

Objective-C/Cocos2D - Display different Sprites with Animation on the same positon on the Screen

Hello i have a big question and i don't find a way to solve my problem till now.
I work on simple game with objective-c and cocos2D.
I have 3 different objects (sprites with animation) and four fixed position on the screen.
Alternately with a interval i want to display the different objects on the positions.
I wanted to do it with a double for() to position the objects. And in the for for i want to create a multidimensional array with all the objects.
And then i want to create a Method where i have access to the time-interval and the frequency of the different objects.
Do you think i can solve my problem with this solution or do you know a better way…??
It would be great if anybody could help me.
Thanky you
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"myPlist.plist"];
myArray = [[CCArray alloc] init];
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
Figure *figure = [Figure spriteWithSpriteFrameName:#"a0001.png"];
figure.position = ccp(j * figure.contentSize.width + 50, i * figure.contentSize.height + 50);
[myArray addObject: figure];
[self addChild:figure z:1];
}
}
I do not know how you structured your plist, but I imagine that you have renamed the images in this way:
a0001.png
a0002.png
a0003.png
why you don't try to make a more simple for loop instead of a "for inside a for" for place only 3 images at your view and manage your file like this:
for (int i = 1; i < 3; i++) {
Figure *figure = [Figure spriteWithSpriteFrameName:[NSString stringWithFormat:#"a000%i.png", i]]
figure.position = //add something that fit with your layout
[myArray addObject: figure];
[self addChild:figure z:1];
}

Objective C, maze generation and 2D arrays

I need to generate a random maze with given width and height. I could do this in Perl with Depth-first search algorithm, in which I use 2D arrays, something like this:
for my $i (0 .. $h - 1) {
for my $j (0 .. $w - 1) {
push #{ $cell[$i] }, '1';
}
push #{ $cell[$i] }, '0';
}
for my $i (0 .. $w) {
$cell[$h][$i] = '';
}
While in Objective C, there's no 2D array. I'm kind of lost now. What is the equivalent of 2D array in Objective C so that I pretty much can use the same data structure as in Perl?
Thanks.
One way is to use Objective-C style array:
NSMutableArray *cell = [NSMutableArray arrayWithCapacity:h];
for (int i=0; i<h; ++i) {
NSMutableArray *row = [NSMutableArray arrayWithCapacity:w];
for (int j=0; j<w; ++j) {
// use a random number
[row addObject:[NSNumber numberWithInt:rand()]];
}
// add one row
[cell addObject:row];
}
Another way is just to use C style array:
int **cell = malloc(h*sizeof(int *));
for (int i=0; i<h; ++i) {
cell[i] = malloc(w*sizeof(int));
for (int j=0; j<w; ++j) {
cell[i][j] = rand();
}
}
// after you used it remeber to free it
for (int i=0; i<h; ++i) {
free(cell[i]);
}
free(cell);
cell = NULL;
Use this github library to generate maze.
https://github.com/DoubleEqual/MazeGenerator-tool
The result looks like this for 24x24 maze:
A 2-Dimentional or N-Dimentional arrays are nothing but a way to store the data. If you want a 2-D array its fairly simple, but little bit tricky in obj-c, you have to creates 2nd level arrays, then insert it into first level.
See the code below :
NSMutableArray *twoDArray = [NSMutableArray new]; //this is first level
//below are second level arrays inserted in index 0 to 2.
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"00",#"01",#"02",nil] atIndex:0];
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"10",#"11",#"12",nil] atIndex:1];
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"20",#"21",#"22",nil] atIndex:2];

Most efficient way to draw lines from array of points in cocos2d

Given an NSMutableArray of dynamic CGPoints, what is the fastest and most efficient way to draw lines from array[0] to array[1], array[1] to array[2], etc.? Should I rewrite my function in C or C++ for better performance? Currently my framerate suffers dramatically when there are more than ~20 points in the array. I am using cocos2d v2.0.0-rc2 and I currently have:
-(void)draw
{
for (int i = 0; i < [points count]; i+=2)
{
CGPoint startFromArray = [[points objectAtIndex:i] CGPointValue];
CGPoint endFromArray = [[points objectAtIndex:i+1] CGPointValue];
ccDrawLine(startFromArray, endFromArray);
}
[super draw];
}
There's no need to use iteration here. Cocos2d has a built-in function called ccDrawPoly(). You can use it like this:
CGPoint *verts = malloc(sizeof(CGPoint) * [points count]);
for (int i = 0; i < [points count]; i++) {
verts[i] = [[points objectAtIndex:i] CGPointValue];
}
ccDrawPoly(verts, [points count], NO);
free(verts);
Obviously, you'll get even better performance if you store your CGPoints in a C array instead of boxing and unboxing them from NSValues, but if you really need the mutability, that can't be helped.
As for the third argument of ccDrawPoly(), setting it to YES will connect the start and end points of the array, making a closed polygon, while using NO will just make a bunch of open lines.

Sort Array of CGPoints

I am trying to figure out what the fastest/cleanest way to sort an array of CGPoints would be. I think I could achieve this using loops but that might not be the fastest and I hope it isn't the cleanest way. I would like to take an array of random CGPoints and sort them say by smallest x coordinate to largest, or smallest x and y coordinate to largest.
After the correct comment by Chuck, I've updated the answer using the sortUsingComparator method:
Here is the complete code with sample data:
First we generate 100 random values that we enter to the Array:
NSMutableArray *testArray = [[NSMutableArray alloc] initWithCapacity:100];
for (int i=0; i<100; i++) {
CGPoint testPoint = CGPointMake(arc4random()%100, arc4random()%100);
[testArray addObject:[NSValue valueWithCGPoint:testPoint]];
}
and here is the actual code to sort the array:
[testArray sortUsingComparator:^(id firstObject, id secondObject) {
CGPoint firstPoint = [firstObject CGPointValue];
CGPoint secondPoint = [secondObject CGPointValue];
return firstPoint.x>secondPoint.x;
}];
finally we can verify that the array was sorted, by printing it:
NSLog(#"%#",testArray);
The C qsort() function is probably your best bet if you just have a plain array of CGPoints. Something like this:
int compareXCoords(CGPoint *a, CGPoint *b) {
return b->x - a->x;
}
// Later:
CGPoint points[100];
// initialize points somehow
qsort(points, 100, sizeof(CGPoint), compareXCoords);
// points is now sorted by the points' x coordinates
According to my comment, it's a good solution insert them on a NSMutableArray keeping the sort you decide.
You have to do something like this:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];
CGPoint candidate;
// Look for the position it has to be
int 0;
for (CGPoint point in array) {
i++;
// Compare candidate with current point
// You have to define this condition, when point is greater than candidate
if (point > candidate) {
break;
}
}
[array insertObjectAtIndex:i-1];
Maybe my code has some errors, I can't check if it's correct now.

Multidimensional arrays - what's the most convenient way to work with them in Objective-C?

I'm a beginner in Objective-C and I'm trying to find the most convenient way to work with multidimensional arrays in Objective-C. Either I am missing something or they are very ugly to work with.
Let's say we have a classic problem:
read input from file; on the first line, separated by space(" ") are the width and height of the matrix (eg: 3 4)
on the following lines there is the content described by the values above
Eg:
3 4
a b c d
e f g h
i j k l
The first solution I thought of was:
NSMutableArray *matrix = [[NSMutableArray alloc] initWithCapacity: x]; //x = 3 in this specific case
NSMutableArray *cell;
for(cell in matrix)
{
cell = [NSMutableArray initWithCapacity: y];
for(int i = 0; i < y; i++) // y = 4
{
//object is a NSString containing the char[i][j] read from the file
[cell insertObject:object atIndex: i];
}
}
This was the first thing I had in mind when thinking about how I should get my values read from file in a multidimensional array. I know you can use C arrays, but since I will store NSObjects in it, I don't think is such a great idea. Nonetheless, from my point of view is easy to work with C arrays rather the solution I got with Objective-C.
Is there another way you could build a multidimensional array in obj-c and easier than the one above?
How about looping them?
I know I can do something like
NSArray *myArray;
for(int i=0; i < [array count]; i++)
{
[myArray arrayWithArray: [array objectAtIndex: i]];
for(int j=0; j < [myArray count]; j++)
{
NSLog(#"array cell [%d,%d]: %s", i, i, [myArray objectAtIndex: j]);
}
}
But that is still more complicated than your average C multidimensional array loop.
Any thoughts on this?
Objective-C is a superset of C, if you want to work with multidimensional arrays like you would in C, do it that way. If you want to work with objects doing it the Cocoa way, then that's fine too, but you will write more code to do it.
Can you not simply make an array of id?
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
id ptr[3][4];
NSObject *p;
ptr[0][0] = p;
}
You can do nothing more with NSArray or NSMutableArray in this regard. That is there is nothing like objectAtIndex:i :j
You can always create one-dimensional arrays of the size width * height instead:
const int size = width*height;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:size];
for (int i=0; i<size; ++i) {
NSString *string = [NSString stringWithFormat:#"col=%d, row=%d", i%width, i/width];
[array insertObject:string atIndex:i];
}
Nobody uses direct multi-dimensional arrays of any size in any computer language (except for homework). They simply use too much memory and are therefore too slow. Objective-C is an object-oriented language. Build a class that does what you need.