In the ShooterGame, for loops would make things much easier than using while loops for two reasons. One, it allows you to directly access objects in an array as the loop variable rather than an integer of the index which you use to get the object. Two, you do not have to set up a temporary integer or add 1 to it every loop. There are two ways to use a for loop. The first one I will demonstrate is for objects:
For(enemyShip* e in listOfEnemies)
{
CCLOG([NSString* stringWithFormat:@"Position:%d,%d",
e.getPosition.x,
e.getPosition.y]);
}
In this example, e is the enemyShip object. Each loop, the for loop assigns the next sequential object in listOfEnemies to e. There is one drawback to this though. You may not add or remove any enemyShips to listOfEnemies inside the for loop. If you want to do that, you could try this:
NSMutableArray* listToRemove = [[NSMutableArray alloc] init];
For(enemyShip* e in listOfEnemies)
{
if(condition)
[listToRemove addObject:e];
}
For(enemyShip* e in listToRemove)
{
[listOfEnemies removeObject:e];
}
Of course, you should replace "condition" with an actual BOOL if you want the code to work. But this will allow you to remove any enemyShips from the listOfEnemies if needed.
Here is the second way to use a for loop with integers. This will have the exact same conditions as the while loops we use in class with the temporary integers, but is much easier:
int max = [listOfEnemies count];
For(int i=0;i< max;i=i+1)//instead of i=i+1, i+=1 or even i++ will do the exact same thing
{
enemyShip* e = [listOfEnemies getObjectAtIndex:i];
CCLOG([NSString* stringWithFormat:@"Position:%d,%d",
e.getPosition.x,
e.getPosition.y]);
}
This may look a bit more familiar since it is similar to the while loops we use. It takes integer i and gets the objectAtIndex i in listOfEnemies. However, a key difference is the syntax inside the condition of the for loop. The first command declares the loop variable and gives it a value. The second condition is to determine when the for loop is done. The last command gives the increment at which i is changed. The last command is the replacement to the line we usually add to the end of the while loop to increase i; the for loop does that for us.
Note, I wrote this code from memorization and it may have syntax errors. If it does, please notify me so that I can fix it.
No comments:
Post a Comment