Search code examples
iphoneobjective-cxcodecocos2d-iphone2d-games

High score and current score on the screen during the game


I want to show on the screen the current score of the gameplay and the storical best score. It is work, but every times i restart the game the best score change even if the current score is lower than the best score.

CCLabelTTF *punteggio;
    NSString *stringa;
    NSString *stringa2;
    CCLabelTTF *punteggioMAX;

    int score;
    int scoreMAX;

There are the methods to SAVE the score, to add the score and to reset the score at the end of the game.

-(void)aum{
    score++;
    stringa = [NSString stringWithFormat:@"Punteggio: %d",score];
    [punteggio setString:stringa];
}



-(void)res{
    score=0;
    stringa = [NSString stringWithFormat:@"Punteggio: %d",score];
    [punteggio setString:stringa];
}

-(void)sal{
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    [ud setInteger:score forKey:@"Punteggio"];
    [ud synchronize];
}

-(void)sal2{
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    [ud setInteger:scoreMAX forKey:@"Punteggio"];
    [ud synchronize];
}

And in the init method:

NSString *fontName = @"score.fnt";
        stringa = [NSString stringWithFormat:@"Punteggio: %d",score];
        punteggio = [CCLabelBMFont labelWithString:stringa fntFile:fontName];
        punteggio.scale = 0.4;
        punteggio.position=ccp(40,altezzaSchermo - 15);
        [self addChild:punteggio];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        score=[ud integerForKey:@"Punteggio"];



        stringa2 = [NSString stringWithFormat:@"Best Score: %d",score];
        punteggioMAX = [CCLabelBMFont labelWithString:stringa2 fntFile:fontName];
        punteggioMAX.scale = 0.4;
        punteggioMAX.position=ccp(40,altezzaSchermo - 35);
        [self addChild:punteggioMAX];
        scoreMAX=[ud integerForKey:@"punteggioMAX"];


 if(score>scoreMAX) scoreMAX = score;

        [self res];

Thank you.


Solution

  • you are saving max score with the wrong key. Try :

    -(void)sal2{
        NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
        [ud setInteger:scoreMAX forKey:@"punteggioMAX"];
        [ud synchronize];
    }