Search code examples
iphonexcode4cocos2d-iphone

How to set high score and only changes if it is surpassed


Like the game helicopter or like Left 4 dead survival mode I want the score to stay and only change if score is surpassed. Here is the code I have so far. ./m file

                    _score = 0;
                         _oldScore = -1;
     self.scoreLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(100, 50) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:32];
     _scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width, _scoreLabel.contentSize.height);
     _scoreLabel.color = ccc3(255,0,0);
     [self addChild:_scoreLabel z:1];     



if (_score != _oldScore) {
    _oldScore = _score;
    [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]];



}

and the .h file

       int _score;
int _oldScore;
CCLabelTTF *_scoreLabel;

I tried to put

      _score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"];

        [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"];
           [[NSUserDefaults standardUserDefaults] synchronize];        

but when i did that it only saved the data and keeps going up rather than starting over and only change when score is surpassed.


Solution

  • You need to compare if your score is more than the old score and just save it then.

    For example,

    if (_score > _oldscore) {
      // Save out new score as it is more than the old score
    
      // Then reset ready for next time
      _oldscore = _score;
      _score = 0;
    }
    

    However, if you are struggling with something like this, I would suggest you are going to be in for a whole lot of problems unless you stop and learn the basics of programming now before progressing further in your development.