(no.00005) iOS implementation bomb man game (vii): Serialization representation of game data

Source: Internet
Author: User

Panda Pig • Patty original or translated works. Welcome reprint, Reprint please indicate the source.
If you feel that the writing is not good please tell me, if you feel good please support a lot of praise. Thank you! Hopy;)

Use the Plist list file to represent game data

Because there are many different levels in this bomber game, the difficulty goes up, so for each level we have to store the data somewhere, there are many ways to save it, and here we choose to use the Plist list file to save the data for each level.

Select the resources directory, where you create a new plist file, named Levelsdata.plist.

Next we want to think about the inside to store God horse data.

There are roughly the number of bricks per level, the number of enemies each, the remaining time limit and the score of the clearance reward.

The number of levels of enemies needs to be refined, because one of our goals at the beginning of the game is to build a variety of enemies, so here to give a corresponding number of each enemy.

As discussed above, the final plist content is basically the following:

Memory representation of game data

With the plist file is not enough, we also need to read the contents of plist into memory, which is read in the way of class instances.

We created a new GameData class in Xcode that inherits from NSObject.

Open the GameData.h header file, set as follows:

#import <Foundation/Foundation.h> //class for managing game data @interface gamedata : nsobject +(ID) Sharedinstance;@property(nonatomic,Assign)NsintegerBombexploderange;//bomb blast range@property(nonatomic,Assign)BOOLIsmanualexplode;//Whether to detonate manually@property(nonatomic,Assign)BOOLIsfearbomb;//Is the player afraid of bombs@property(nonatomic,Assign)NsintegerBombcountlimit;//Number of bombs limit@property(nonatomic,Assign)NsintegerLife//Player's fate@property(nonatomic,Assign)BOOLIsplayerspeedup;//Whether the player is in an accelerated state@property(nonatomic,Assign)BOOLCanplayeracrossbrick;//Whether the player can wear bricks@property(nonatomic,Assign)BOOLCanplayeracorssbomb;//Whether the player can wear bombs@property(nonatomic,Assign)NsintegerPlayertotalscore;//Players have to divide@property(nonatomic,Assign)NsintegerCurlevelnumber;//Current level number@property(nonatomic,Assign)NsintegerCurlevelbrickcount;//Current level bricks quantity//@property (nonatomic,assign) Nsinteger Curlevelenemycount; Number of enemies at current level@property(nonatomic,Assign)NsintegerCurlevelfscount;//Current level the number of ordinary enemies@property(nonatomic,Assign)NsintegerCurlevelfsghostcount;//Current level fsghost number of enemies@property(nonatomic,Assign)NsintegerCurlevelfsdogcount;//Current level Fsdog number of enemies@property(nonatomic,Assign)NsintegerCurlevelfscattracercount;//Current level fscattracer number of enemies@property(nonatomic,Assign)NsintegerCurlevelgpcount;//Current level game props quantity@property(nonatomic,Assign)NsintegerCurlevellefttime;//Current level time limit (seconds)@property(nonatomic,Assign)NsintegerCurlevelpassscore;//Current level clearance score-(void) synchronize;-(void) savegamedata;-(void) loadgamedata;-(void) initgamedata;-(void) Setgamedatawhenlevellose;//Register default game data and use it if the app is running for the first time. (because you have not yet deposited data)-(void) Regdefaultgamedata;@end

The inside defines a number of attributes, divided into two parts: and the current level related to the game and the main character of the content, we can roughly distinguish from the name of the attribute, here is not introduced, the comments are done in detail.

There are not many methods defined in the GameData class, and a class method sharedinstance is used to return a unique instance of the class, and all that is left is the instance method used to read and save the game data.

Implementation of the GameData class

Let's take a look at the implementation code for GameData, first of all the implementation of the class Singleton method:

//返回GameDate类唯一单例+(instancetype)sharedInstance{    staticdispatch_once_t once;    static GameData *sharedInstance;    dispatch_once(&once,^{        sharedInstance = [self new];    });    return sharedInstance;}

There is nothing to say, then another simple synchronization method:

//将NSUserDefaults数据写入磁盘-(void)synchronize{    [[NSUserDefaults standardUserDefaults]synchronize];}

Here is the Loadgamedata method for reading the data:

//Read the game data from disk-(void) loadgamedata{nsdictionary*dict = [[NsuserdefaultsStandarduserdefaults] 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 = [[NSBundleMainbundle] Pathforresource:s_levelsdatafile OfType :@"Plist"];//Read the level data into the array    Nsarray*levelsdataary = [NsarrayArraywithcontentsoffile:plistfullpath]; Nsassert ( Self. Curlevelnumber>0&& Self. Curlevelnumber<= levelsdataary. Count,                                                            @"Error curlevel number!");The //level is beginning with 1, so you want to adjust the starting from 0 in the array.    Nsintegerindex = Self. Curlevelnumber-1;//Get each data in the level in turn     Self. Curlevelbrickcount= [Levelsdataary[index][kcurlevelbrickcount] intvalue]; [ SelfInitcurlevelemenycount:levelsdataary[index][kcurlevelenemycount]]; Self. Curlevelgpcount= [Levelsdataary[index][kcurlevelgpcount] intvalue]; Self. Curlevellefttime= [Levelsdataary[index][kcurlevellefttime] intvalue]; Self. Curlevelpassscore= [Levelsdataary[index][kcurlevelpassscore] intvalue];}

The code is simple, reading the level and player data separately and then setting the corresponding instance variable.

Finally, the Savegamedata method for writing the 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 data dictionary to nsuserdefaults instance[[NsuserdefaultsStandarduserdefaults] Setobject:dict Forkey:kplayerdata]; [ SelfSynchronize];}

This method is the inverse method of the Read method, and finally calls the [self synchronize] to brush the in-memory data into the plist, ensuring that the data is not lost.

Game data class is an essential function of every game, you can consider it into a template class for the use of different programs.

Next we continue to introduce other parts of the game, see you;)

(no.00005) iOS implementation bomb man game (vii): Serialization representation of game data

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.