(No. 00005) iOS-based pop-up game (7): Game data serialization presentation

Source: Internet
Author: User

(No. 00005) iOS-based pop-up game (7): Game data serialization presentation

 

Use plist list files to represent game data

Because there are many different levels in this bombing game, and the difficulty increases in turn, we have to store data for each level somewhere, there are many ways to save, here we choose to use the plist list file to save the data of each level.

Select the Resources directory and create a new plist file named LevelsData. plist.

Next, let's think about how to store Shenma data.

There are roughly the number of bricks for each level, the number of enemies for each level, the remaining time limit for each level, and the score for passing through the reward.

The number of level enemies needs to be refined, because one of our initial goals in the game is to create multiple enemies, so here we need to provide a corresponding number for each enemy.

According to the content discussed above, the final plist content is roughly as follows:


Memory representation of game data

It is not enough to have the plist file. We also need to read the plist content to the memory, which is read by class instances.

We create a new GameData class in Xcode, which inherits from NSObject.

Open the GameData. h header file and set it as follows

#import
// Classes for managing game data
@interface GameData: NSObject

+ (id) sharedInstance;

@property (nonatomic, assign) NSInteger bombExplodeRange; // The bomb explosion range
@property (nonatomic, assign) BOOL isManualExplode; // Whether to manually detonate
@property (nonatomic, assign) BOOL isFearBomb; // Are players afraid of bombs
@property (nonatomic, assign) NSInteger bombCountLimit; // Limit the number of bombs
@property (nonatomic, assign) NSInteger life; // The player's life
@property (nonatomic, assign) BOOL isPlayerSpeedUp; // Whether the player is in acceleration
@property (nonatomic, assign) BOOL canPlayerAcrossBrick; // Whether players can wear bricks
@property (nonatomic, assign) BOOL canPlayerAcorssBomb; // Whether the player can wear a bomb
@property (nonatomic, assign) NSInteger playerTotalScore; // Total player score

@property (nonatomic, assign) NSInteger curLevelNumber; // Current level number
@property (nonatomic, assign) NSInteger curLevelBrickCount; // Number of current level bricks
// @ property (nonatomic, assign) NSInteger curLevelEnemyCount; // Number of enemies in the current level

@property (nonatomic, assign) NSInteger curLevelFSCount; // The number of common enemies in the current level
@property (nonatomic, assign) NSInteger curLevelFSGhostCount; // The number of FSGhost enemies in the current level
@property (nonatomic, assign) NSInteger curLevelFSDogCount; // The number of FSDog enemies in the current level
@property (nonatomic, assign) NSInteger curLevelFSCatTracerCount; // Number of enemies in current level FSCatTracer

@property (nonatomic, assign) NSInteger curLevelGPCount; // Number of current level game props
@property (nonatomic, assign) NSInteger curLevelLeftTime; // Current level time limit (seconds)
@property (nonatomic, assign) NSInteger curLevelPassScore; // Current level pass score

-(void) synchronize;
-(void) saveGameData;
-(void) loadGameData;
-(void) initGameData;
-(void) setGameDataWhenLevelLose;
// Register the default game data, which will be used if the app is run for the first time. (Because you have not yet saved the data)
-(void) regDefaultGameData;

@end
There are several attributes defined in it, which are divided into two parts: the content related to the current level and the state of the game protagonist, you can roughly distinguish it from the name of the attribute. detailed.

There are not many methods defined in the GameData class.One class method sharedInstance is used to return the only instance of the class, and the rest are all instance methods used to read and save game data.

Implementation of GameData class
Next, let's look at the implementation code of GameData, first of all, the implementation of class singleton methods:

// Return the only singleton of GameDate class
+ (instancetype) sharedInstance {
    static dispatch_once_t once;
    static GameData * sharedInstance;
    dispatch_once (& once, ^ {
        sharedInstance = [self new];
    });
    return sharedInstance;
}
There is nothing to say about the content, and then another simple synchronization method:

// Write NSUserDefaults data to disk
-(void) synchronize {
    [[NSUserDefaults standardUserDefaults] synchronize];
}
Here is the loadGameData method to read data:

// Read game data from disk
-(void) loadGameData {
    NSDictionary * dict = [[NSUserDefaults standardUserDefaults] objectForKey: kPlayerData];

    self.bombExplodeRange = [dict [kBombExplodeRange] intValue];
    self.isManualExplode = [dict [kIsManualExplode] boolValue];
    self.isFearBomb = [dict [kIsFearBomb] boolValue];
    self.bombCountLimit = [dict [kBombCountLimit] intValue];
    self.life = [dict [kLife] intValue];
    self.isPlayerSpeedUp = [dict [kIsPlayerSpeedUp] boolValue];
    self.canPlayerAcrossBrick = [dict [kCanPlayerAcrossBrick] boolValue];
    self.canPlayerAcorssBomb = [dict [kCanPlayerAcrossBomb] boolValue];
    self.playerTotalScore = [dict [kPlayerTotalScore] intValue];
    self.curLevelNumber = [dict [kCurLevelNumber] intValue];

    // Get the full path of the level data file
    NSString * plistFullPath = [[NSBundle mainBundle] pathForResource: s_LevelsDataFile
                                                                        ofType: @ "plist"];
    // Read the level data into the array
    NSArray * levelsDataAry = [NSArray arrayWithContentsOfFile: plistFullPath];
    NSAssert (self.curLevelNumber> 0 && self.curLevelNumber <= levelsDataAry.count,
                                                            @ "Error curLevel Number!");

    // The level starts from 1, so it needs to be adjusted to start from 0 in the array.
    NSInteger index = self.curLevelNumber-1;
    // Get each data in the level in turn
    self.curLevelBrickCount = [levelsDataAry [index] [kCurLevelBrickCount] intValue];

    [self initCurLevelEmenyCount: levelsDataAry [index] [kCurLevelEnemyCount]];

    self.curLevelGPCount = [levelsDataAry [index] [kCurLevelGPCount] intValue];
    self.curLevelLeftTime = [levelsDataAry [index] [kCurLevelLeftTime] intValue];
    self.curLevelPassScore = [levelsDataAry [index] [kCurLevelPassScore] intValue];
}
The code is very simple, which is to read the data of level and player separately and then set the corresponding instance variables.

Finally, the saveGameData method to write data:

// Write game data to disk
-(void) saveGameData {
    // Create a data dictionary
    NSDictionary * dict = @ (kBombExplodeRange: @ (self.bombExplodeRange),
                           kIsManualExplode: @ (self.isManualExplode),
                           kIsFearBomb: @ (self.isFearBomb),
                           kBombCountLimit: @ (self.bombCountLimit),
                           kLife: @ (self.life),
                           kIsPlayerSpeedUp: @ (self.isPlayerSpeedUp),
                           kCanPlayerAcrossBrick: @ (self.canPlayerAcrossBrick),
                           kCanPlayerAcrossBomb: @ (self.canPlayerAcorssBomb),
                           kPlayerTotalScore: @ (self.playerTotalScore),
                           kCurLevelNumber: @ (self.curLevelNumber)
                           };
    // Write the data dictionary to the NSUserDefaults instance
    [[NSUserDefaults standardUserDefaults] setObject: dict forKey: kPlayerData];
    [self synchronize];
}
This method is the inverse method of the read method, and finally [self synchronize] is called to flash the data in the memory into the plist to ensure that the data will not be lost.

The game data class is an indispensable function class for each game, you can consider making it into a template class for different programs to use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.