拥有一个维护所有统计信息的单例类(共享对象)很好。
示例:假设 MyGame 用于存储所有游戏统计信息。//在 MyGame.h 中
typedef enum
{
kGameMode_Practice = 1001,
kGameMode_Stress,
kGameMode_TimeBattle,
}GameMode;
@interface MyGame: NSObject
{
GameMode mGameMode;
int mHighScore;
}
@property(nonatomic,assign) GameMode gameMode;
@property(nonatomic,assign) int highScore;
+(MyGame*)sharedGameObject;
//在MyGame.mm
static MyGame *gGame = nil;
@implementation MyGame
@synthesize gameMode=mGameMode;
@synthesize highScore=mHighScore;
+(MyGame*)sharedGameObject
{
if(!gGame)
{
gGame = [[MyGame alloc] init];
}
return gGame;
}
-(void)saveData //Call this from applicationWillResignActive
{
NSUserDefaults *userDafs = [NSUserDefaults standardUserDefaults];
[userDafs setInteger:self.highScore forKey:@"highScore"];
[userDafs setInteger:self.gameMode forKey:@"gameMode"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)loadData //call this from UIApplication didFinishLaunchingWithOptions
{
NSUserDefaults *userDafs = [NSUserDefaults standardUserDefaults];
self.highScore = [userDafs integerForKey:@"highScore"]
self.gameMode = (GameMode)[userDafs integerForKey:@"gameMode"]
}
//您可以在选择菜单按钮时设置游戏模式
[MyGame sharedGameObject].gameMode = kGameMode_Practice
//检查游戏中的任何地方
if([MyGame sharedGameObject].gameMode == kGameMode_Practice)
还要在应用程序终止时保存这些值,并在应用程序启动时加载相同的值。
[[MyGame sharedGameObject] saveData];
根据游戏模式,您可以更改游戏玩法。使用单个通用类进行游戏逻辑并检查游戏模式并进行调整..当您为 3 种类型设计 3 个单独的类时,将来需要在所有文件中更新一个.. 尽可能多地使用通用代码很好.