Problem with Objective-C for loop - iphone

I have two methods, the generateRandomCard method gets called within the testMethod, where there is a for loop that runs 100 times. That way it works perfect, but if I set the for loop limit to 1000 or any other number greater than 100 it crashes. Can you see what's wrong??
- (void)testMethod {
Globals *myGlobals = [Globals sharedInstance];
int rankOfFirst = 0;
int rankOfSecond = 0;
int playerOneWin = 0;
int playerTwoWin = 0;
int ties = 0;
float firstPercent = 0;
float secondPercent = 0;
float tiePercent = 0;
FiveEval *evaluator = [FiveEval theEvaluator];
for (int i = 0; i < 100; i++) {
short fPF = [self generateRandomCard];
short fPS = [self generateRandomCard];
short sPF = [self generateRandomCard];
short sPS = [self generateRandomCard];
short fFlop = [self generateRandomCard];
short sFlop = [self generateRandomCard];
short tFlop = [self generateRandomCard];
short tur = [self generateRandomCard];
short riv = [self generateRandomCard];
rankOfFirst = [evaluator getRankOfSeven:fFlop
:sFlop
:tFlop
:tur
:riv
:fPF
:fPS];
rankOfSecond = [evaluator getRankOfSeven:fFlop
:sFlop
:tFlop
:tur
:riv
:sPF
:sPS];
if (rankOfFirst > rankOfSecond) {
playerOneWin++;
} else if (rankOfSecond > rankOfFirst) {
playerTwoWin++;
} else {
ties++;
}
[myGlobals.alreadyPickedCards removeAllObjects];
}
firstPercent = ((float)playerOneWin/(float)10000)*100;
secondPercent = ((float)playerTwoWin/(float)10000)*100;
tiePercent = ((float)ties/(float)10000)*100;
NSLog(#"First Player Equity: %f", firstPercent);
NSLog(#"Second Player Equity: %f", secondPercent);
NSLog(#"Tie Equity: %f", tiePercent);
}
- (short)generateRandomCard {
Globals *myGlobals = [Globals sharedInstance];
short i = arc4random()%51;
for (int j = 0; j < [myGlobals.alreadyPickedCards count]; j++) {
if (i == [[myGlobals.alreadyPickedCards objectAtIndex:j] shortValue]) {
[self generateRandomCard];
}
}
[myGlobals.alreadyPickedCards addObject:[NSNumber numberWithShort:i]];
return i;
}

You're probably overflowing your stack in the recursive call to -generateRandomCard. If you generate a card that's already been picked, you call yourself recursively (and ignore the result, which is a different bug). So, if your random number stream gave you an unlucky sequence that kept returning cards you've already picked, then you'll recurse infinitely until the stack overflows.
Change your card selection algorithm so that instead of using rejection sampling with the potential for infinite looping/recursion, it uses an algorithm with a bounded runtime such as the Fisher-Yates shuffle.

Not sure if this could in any way lead to the crash - It may be unrelated. However, it does look like you have a bug in the way you recursively call generateRandomCard when a card is found in the alreadyPickedCards array. Instead of
[self generateRandomCard];
I think you should have
return [self generateRandomCard];

You have in -testMethod:
[myGlobals.alreadyPickedCards removeAllObjects];
and in -generateRandomCard you have:
for (int j = 0; j < [myGlobals.alreadyPickedCards count]; j++) {
if (i == [[myGlobals.alreadyPickedCards objectAtIndex:j] shortValue]) {
[self generateRandomCard];
}
}
I can't bet for sure, but this looks like a situation where you removeAllObjects in 1 loop and access an out of bound index in another loop.
If you wanna play like this with arrays, I suggest you make copies of arrays and remove items from those copied arrays.

Related

FPS Lag scheduler?

I've been getting FPS lag. I've looked around and people say to use
[self schedule:#selector(gameLoop:) interval: 1/60.0f];
When I use this I get choppy lag. but when I use
[self schedule:#selector(gameLoop:)];
It's a lot smoother. Here is a snippet of my movement code.
- (void)gameLoop :(ccTime)dt
{
[self manageCannon:dt];
[self manageBullets:dt];
[self manageEnemies:dt];
[self manageAllies:dt];
}
- (void) manageEnemies :(ccTime)dt
{
enemyClass *tempEnemy;
for(int i = 0; i < [enemies count]; i++)
{
tempEnemy = [enemyClass new];
tempEnemy = [enemies objectAtIndex:i];
tempEnemy.position = ccp(tempEnemy.position.x-tempEnemy.speed*dt,tempEnemy.position.y);
if((tempEnemy.position.x - tempEnemy.range) < [wall getwally])
{
tempEnemy.speed = 0;
}
if(tempEnemy.health < 1)
{
tempEnemy.alive = false;
}
if(tempEnemy.alive == false)
{
[enemies removeObjectAtIndex:i];
[tempEnemy removeFromParentAndCleanup:true];
}
}
}
I always try to write my own code from scratch, so if you can help me out with other things that i'm doing that is incorrect that would be very helpful towards me.
It's hard to say what is slowing down your app from the information given. As LearnCocos2D suggested, you can use Instruments to figure out where the slow stuff is. Or if you want to get very granular analysis, you can always use the following macros in your code:
#define TIC start = [NSDate date]
#define TOC -[start timeIntervalSinceNow]
#define TOCP NSLog(#"TIME: %f", TOC)
Before using, be sure to declare NSDate *start in scope of use. Then just put a series of TIC/TOC or TIC/TOCP pairs in your code to print out times your code is taking in different places. You can very quickly find the bottlenecks this way.

making my own tile system cause lag

- (void) loadStartingTiles //16 by 24
{
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
#"clonespritesheet.plist"];
for(int x = 0; x < 16; x++) //minus 1 for one at the begining
{
for(int y = 0; y < 26; y++)
{
CCSprite *tempsprite;
switch (currentscreen[x][y])
{
case 0:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block0.png"];
break;
case 1:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
}
tempsprite.position = ccp(y*20+10,(16-x)*20-10); //+10 for align for tile size
[self addChild:tempsprite z:3];
[tiles addObject:tempsprite];
}
}
}
So I make a bunch of sprites from an int array that tells them where they should be then i add them into the nsmutable array tile. then i move everything in the array to the left slowly, and im losing around 20 FPS. what is a more efficient way to make a tile system? my goal is to make randomly generated tiles later on.
- (void) manageTiles:(CGFloat)dt
{
int tileamount = [tiles count];
for(int i = 0; i < tileamount; i++)
{
CCSprite *tempsprite = [tiles objectAtIndex:i];
tempsprite.position = ccp(tempsprite.position.x-20*dt,tempsprite.position.y);
}
}
EDIT: the awnser is
int themap = -20;
- (void) manageTiles:(CGFloat)dt
{
tiles.position = ccp(tiles.position.x-10*dt,tiles.position.y);
NSLog(#"%d",themap);
if(tiles.position.x < themap)
{
CCSprite *tempsprite;
for(int i = 0; i < 16; i++)
{
[tiles removeChildAtIndex:0 cleanup:YES];
}
for(int i = 0; i < 16; i++)
{
switch (tilewall[i])
{
case 0:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
case 1:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
}
tempsprite.position = ccp((themap*-1)+500+10,((16-i)*20-10));
[tiles addChild:tempsprite];
}
themap = themap-20;
}
}
Where you are going wrong is, you are not using a CCSpriteBatchNode. A CCSpriteBatchNode will draw all of the tiles in one draw operation instead of doing one draw operation per tile. The drawbacks are, each tile in the batch node will have the same zOrder (in a way), and it all must use one source spritesheet per batch node. SO basically if you wanted different layers at different zOrders, or different layers which use different source images for the tiles, you would have to create multiple batch nodes, one for each.
http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_c_c_sprite_batch_node.html
Preload the tempsprite variable outside your loop:
CSprite *sprite0 = [CCSprite spriteWithSpriteFrameName:#"block0.png"];
CSprite *sprite1 = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
And then refer them to them in the loop:
switch (currentscreen[x][y])
{
case 0:
tempsprite = sprite0;
break;
case 1:
tempsprite = sprite1;
break;
}
or even better:
tempsprite = currentscreen[x][y] ? sprite1 : sprite0;
Oh, and your inner loop should refer to 24, not 26.

iPhone:How can I shuffle buttons in view

I have many no. of buttons on my view and I want to shuffle the buttons(change in position) then how can I shuffle the button in my view.
use arc4random()
and change position of your buttons
In your .h file : UIButton *buttonsarray[10];
In your .m file :
// Make array of button using following way.I used this method to creates button and you can use yours.
- (void)viewDidLoad {
[super viewDidLoad];
float y = 5;
int x = 0;
int count = 0;
for (int i = 0 ; i < 10; i++)
{
count ++;
buttonsarray[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonsarray[i].frame = CGRectMake(x, y, 100, 100);
[buttonsarray[i] setTitle:[NSString stringWithFormat:#"%d",i+1] forState:UIControlStateNormal];
x = x + 105;
[self.view addSubview:b[i]];
if(count == 3)
{
count = 0;
x = 0;
y = y+ 105;
}
}
}
// This function will soufflé your buttons
- (IBAction)btnClicked:(id)sender
{
int n = 10;
int swaper;
for (int i = 0 ; i < 10 ; i++)
{
int r = arc4random()%n;
if(r != swaper){
swaper = r;
CGRect r1 = buttonsarray[i].frame;
buttonsarray[i].frame = buttonsarray[swaper].frame;
buttonsarray[swaper].frame = r1;
n--;
}
}
}
Hope,this will help you..
You can do this
Make an Array with a group of CGPoints you will need to store the points as strings.
In the layoutSubViews method set something like this:
-(void)layoutSubViews{
[self.subviews enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
CGPoint newPoint = CGPointFromString([positionsArray objectAtIndex:idx]);
object.frame = CGRectMake(newPoint.x,newPoint.y,object.frame.size.width,object.frame.size.height);
}];
}
Then you will need to shuffle the positions in the positions array, you can see an example method here :How to Shuffle an Array
Now every time you need to Shuffle the positions you can call -(void)setNeedsLayout on your view.
There are more options but that was the first I thought of.
Good Luck

objective C for-loop break and continue

How can i use a 'break' statement within a for-loop which continues form a specified label?
ex;
outer: for(int i = 0;i<[arABFBmatches count];i++){
for(int i = 0;i<[arABFBmatches count];i++){
//
break _____;
}
}
How to break to outer?
Hard to say from your question. I'd interpret it that you want to skip the rest of the iterations of the inner loop and continue the outer loop?
for (int i = 0; i < [arABFBmatches count]; i++) {
for (int j = 0; j < [arABFBmatches count]; j++) {
if (should_skip_rest)
break; // let outer loop continue iterating
}
}
Note that I changed the name of your inner loop invariant; using i in both is inviting insanity.
If you want to break from both loops, I wouldn't use a goto. I'd do:
BOOL allDoneNow = NO;
for (int i = 0; i < [arABFBmatches count]; i++) {
for (int j = 0; j < [arABFBmatches count]; j++) {
if (should_skip_rest) {
allDoneNow = YES;
break;
}
}
if (allDoneNow) break;
}
Roughly:
for(int i = 0;i<[arABFBmatches count];i++){
for(int j = 0;j<[arABFBmatches count];j++){
//
goto outer_done;
}
}
outer_done:
Objective-C does not have labelled break.
From Apple's Objective-C docs:
Objective-C is defined as a small but powerful set of extensions to
the standard ANSI C language.
So break and continue can be used wherever they are permitted in C.
continue can be used in looping constructs (for, while and do/while loops).
break can be used in those same looping constructs as well as in switch statements.
BOOL done = NO;
for(int i = 0;i<[arABFBmatches count] && !done; i++)
{
for(int i = 0;i<[arABFBmatches count] && !done;i++)
{
if (termination condition)
{
// cleanup
done = YES;
}
}
}
'break' will only get you out of the innermost loop or switch. You can use 'return' to exit out of a function at any time.Please have a look at the this link.

Need help with a memory management problem in my game model

I'm a beginner level programmer trying to make a game app for the iphone and I've encountered a possible issue with the memory management (exc_bad_access) of my program so far. I've searched and read dozens of articles regarding memory management (including apple's docs) but I still can't figure out what exactly is wrong with my codes. So I would really appreciate it if someone can help clear up the mess I made for myself.
//in the .h file
#property(nonatomic,retain) NSMutableArray *fencePoleArray;
#property(nonatomic,retain) NSMutableArray *fencePoleImageArray;
#property(nonatomic,retain) NSMutableArray *fenceImageArray;
//in the .m file
- (void)viewDidLoad {
[super viewDidLoad];
self.gameState = gameStatePaused;
fencePoleArray = [[NSMutableArray alloc] init];
fencePoleImageArray = [[NSMutableArray alloc] init];
fenceImageArray = [[NSMutableArray alloc] init];
mainField = CGRectMake(10, 35, 310, 340);
..........
[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:#selector(gameLoop) userInfo:nil repeats:YES];
}
So basically, the player touches the screen to set up the fences/poles
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(.......) {
.......
}
else {
UITouch *touch = [[event allTouches] anyObject];
currentTapLoc = [touch locationInView:touch.view];
NSLog(#"%i, %i", (int)currentTapLoc.x, (int)currentTapLoc.y);
if(CGRectContainsPoint(mainField, currentTapLoc)) {
if([self checkFence]) {
onFencePole++;
//this 3 set functions adds their respective objects into the 3 NSMutableArrays using addObject:
[self setFencePole];
[self setFenceImage];
[self setFencePoleImage];
.......
}
}
else {
.......
}
}
}
}
The setFence function (setFenceImage and setFencePoleImage is similar to this)
-(void)setFencePole {
Fence *fencePole;
if (!elecFence) {
fencePole = [[Fence alloc] initFence:onFencePole fenceType:1 fencePos:currentTapLoc];
}
else {
fencePole = [[Fence alloc] initFence:onFencePole fenceType:2 fencePos:currentTapLoc];
}
[fencePoleArray addObject:fencePole];
[fencePole release];
and whenever I press a button in the game, endOpenState is called to clear away all the extra images(fence/poles) on the screen and also to remove all existing objects in the 3 NSMutableArray. Point is to remove all the objects in the NSMutableArrays but keep the array itself so it can be reused later.
-(void)endOpenState {
........
int xMax = [fencePoleArray count];
int yMax = [fenceImageArray count];
for (int x = 0; x < xMax; x++) {
[[fencePoleImageArray objectAtIndex:x] removeFromSuperview];
}
for (int y = 0; y < yMax; y++) {
[[fenceImageArray objectAtIndex:y] removeFromSuperview];
}
[fencePoleArray removeAllObjects];
[fencePoleImageArray removeAllObjects];
[fenceImageArray removeAllObjects];
........
}
The crash happens here at the checkFence function.
-(BOOL)checkFence {
if (onFencePole == 0) {
return YES;
}
else if (onFencePole >= 1 && onFencePole < currentMaxFencePole - 1) {
CGPoint tempPoint1 = currentTapLoc;
CGPoint tempPoint2 = [[fencePoleArray objectAtIndex:onFencePole-1] returnPos]; // the crash happens at this line
if ([self checkDistance:tempPoint1 point2:tempPoint2]) {
return YES;
}
else {
return NO;
}
}
else if (onFencePole == currentMaxFencePole - 1) {
......
}
else {
return NO;
}
}
So the problem here is, everything works fine until checkFence is called the 2nd time after endOpenState is called. So its like tap_screen -> tap_screen -> press_button_to_call_endOpenState -> tap screen -> tap_screen -> crash
What I'm thinking of is that fencePoleArray got messed up when I used [fencePoleArray removeAllObjects] because it doesn't crash when I comment it out. It would really be great if someone can explain to me what went wrong. And thanks in advance.
First, a couple of suggestions:
if (!elecFence) {
fencePole = [[Fence alloc] initFence:onFencePole
fenceType:1 fencePos:currentTapLoc];
}
else {
fencePole = [[Fence alloc] initFence:onFencePole
fenceType:2 fencePos:currentTapLoc];
}
You’re making this too hard, how about this:
const int fenceType = elecFence ? 2 : 1;
Fence *fencePole = [[Fence alloc] initFence:onFencePole
fenceType:fenceType fencePos:currentTapLoc];
And this:
int xMax = [fencePoleArray count];
int yMax = [fenceImageArray count];
for (int x = 0; x < xMax; x++) {
[[fencePoleImageArray objectAtIndex:x] removeFromSuperview];
}
for (int y = 0; y < yMax; y++) {
[[fenceImageArray objectAtIndex:y] removeFromSuperview];
}
Could be shortened using makeObjectsPerformSelector:
const SEL remove = #selector(removeFromSuperview);
[fencePoleImageArray makeObjectsPerformSelector:remove];
[fenceImageArray makeObjectsPerformSelector:remove];
This is shorter and safer, as the xMax bound in your code is computed from fencePoleArray and used to iterate over fencePoleImageArray. (Could be right, could be wrong.)
Now to the objectAtIndex: call. If the array is still in memory and you tried to access an object beyond the array bounds, you would get an exception. So that I guess that either the array or some of the objects in it got released without you knowing it. You could try to NSLog the array and the object on given index and try to log their retainCount. If the logging line crashes, you have found the object that’s been released and can start looking for the cause.
(And one more thing: You should split the game logic into a separate model class. This simplifies the code and makes it easier to reason about.)
If you want to use properties, you should use self.propertyName = ... instead of propertyName = ....
Hope this will help.