Monday, 15 August 2011

How to make a local leaderboard

If your not up for implementing Game Center into your app, you can easily just create a simple local score system using plists.

Create a plist like this
The way I have my levels formated is, there are 3 "cups"; easy, medium and hard. Each cup has a certain amount of levels in them, and then each level will have its scores.

To read/write to the plist, I created a class which handles everything for us. Here is the code
@implementation scoreAndSaveClass

NSString* pathOfPlist;

+(void) getPathOfScoreList{
    
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    pathOfPlist = [documentsDirectory stringByAppendingPathComponent:@"scoresFile.plist"]; 
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath: pathOfPlist]) 
    {
        NSString * bundle = [[NSBundle mainBundle] pathForResource: @"scoresFile" ofType:@"plist"];
        
        [fileManager copyItemAtPath:bundle toPath: pathOfPlist error:&error]; 
    }
}

+(void) setLevelScore:(float) inScore andTheDifficulty:(NSString*) difficulty andTheLevel:(int) level{
     //get path of plist
    [self getPathOfScoreList];
    
    NSMutableDictionary * indexOfPlist = [[[NSMutableDictionary alloc] initWithContentsOfFile:pathOfPlist] autorelease];

    //gets dictionary of levels from this difficulty
    NSMutableDictionary * indexOfLevels = [indexOfPlist objectForKey:difficulty];
    
    //gets the array of scores for this level
    NSMutableArray *arrayOfLevelScores = [indexOfLevels objectForKey:[NSString stringWithFormat:@"Level%i", level]];

    //adds the users newest score to the array
    [arrayOfLevelScores addObject:[NSNumber numberWithFloat:inScore]];
    
    //updates the cup's dictionary to be the array with the latest values
    [indexOfLevels setValue:arrayOfLevelScores forKey:difficulty];

    //saves changes
    [indexOfPlist writeToFile: pathOfPlist atomically:YES];

    
}

+(NSArray*) getSortedScore:(NSString*) difficulty andTheLevel:(int) level{
    //get path of plist
    [self getPathOfScoreList];
    
    NSMutableDictionary * indexOfPlist = [[[NSMutableDictionary alloc] initWithContentsOfFile:pathOfPlist] autorelease];

    //gets the array of score depends on what cup is selected
    NSMutableDictionary * indexOfLevels = [indexOfPlist objectForKey:difficulty];
    
    //gets the array of score depends on what level is selected
    NSMutableArray *arrayOfLevelScores = [indexOfLevels objectForKey:[NSString stringWithFormat:@"Level%i", level]];
    
    //this sorted the array in ascending order
    NSSortDescriptor * temp= [[NSSortDescriptor alloc] initWithKey:@"doubleValue" ascending:NO];
    [arrayOfLevelScores sortUsingDescriptors:[NSArray arrayWithObject:temp]];
        
    return arrayOfLevelScores;
    
@end

 
To read/write to the plist, you call the required function. At the start of each function it calls the "get path" function which will set the string to be the location of the plist. Because each plist is structured as dictionary, we use dictionaries to browse through the plist.

Whenever you call the function to read/write a score you must pass a string into the function, which you will set to be either "Easy", "Medium" or "Hard" (at least it is for me, depends on how you structured your plist).

To display the latest score I created just a simple loop that loops the top 10 score, or if there is less than 10 scores, it lists all the scores it can.

int maxNumOfScores = MIN([scoreArray count], 15);
        
        for (int i = 0; i <maxNumOfScores; i++) {
         
            CCLabelTTF * scoreLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"Score %i", [[scoreArray objectAtIndex:i] intValue]] fontName:@"Marker Felt" fontSize:20];
            [self addChild:scoreLabel];
            scoreLabel.position = ccp(240, (280 - i*20));
            
        }

No comments:

Post a Comment