即使应用关闭,也可以在我的应用中保存游戏关卡?

时间:2012-08-23 02:54:43

标签: ios xcode save game-engine

我正在为iPhone制作RPG游戏,一切都很好但我需要知道如何保存我的游戏级别,以便即使用户关闭在后台运行的应用程序,整个游戏也不会重新开始。我甚至想把旧式游戏带回来并制作它,以便你必须输入密码才能从你离开的地方开始。但即便如此,我也不知道如何正确地保存游戏。即使我确实保存了游戏,即使应用程序完全关闭,我怎么能保持保存?到目前为止,我已经尝试将保存数据代码添加到AppWillTerminate行,但仍然没有。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

我不确定您是要保存用户所在的级别,还是要保存游戏状态。如果您只想保存用户所在的级别,则应使用@ EricS的方法(NSUserDefaults)。保存游戏状态有点复杂。我会做这样的事情:

//Writing game state to file
    //Some sample data
    int lives = player.kLives;
    int enemiesKilled = player.kEnemiesKilled;
    int ammo = player.currentAmmo;

    //Storing the sample data in an array
    NSArray *gameState = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt:lives], [NSNumber numberWithInt:enemiesKilled], [NSNumber numberWithInt:ammo], nil]; 

    //Writing the array to a .plist file located at "path"
    if([gameState writeToFile:path atomically:YES]) {
        NSLog(@"Success!");
    }

//Reading from file
    //Reads the array stored in a .plist located at "path"
    NSArray *lastGameState = [NSArray arrayWithContentsOfFile:path];

.plist看起来像这样:

enter image description here

使用数组意味着在重新加载游戏状态时,您必须知道存储项目的顺序,这不是那么糟糕,但如果您想要一个更可靠的方法,您可以尝试使用像这样的NSDictionary:

//Writing game state to file
    //Some sample data
    int lives = player.kLives;
    int enemiesKilled = player.kEnemiesKilled;
    int ammo = player.currentAmmo;
    int points = player.currentPoints;

    //Store the sample data objects in an array
    NSArray *gameStateObjects = [NSArray arrayWithObjects:[NSNumber numberWithInt:lives], [NSNumber numberWithInt:enemiesKilled], [NSNumber numberWithInt:points], [NSNumber numberWithInt:ammo], nil];

    //Store their keys in a separate array      
    NSArray *gameStateKeys = [NSArray arrayWithObjects:@"lives", @"enemiesKilled", @"points", @"ammo", nil];

    //Storing the objects and keys in a dictionary
    NSDictionary *gameStateDict = [NSDictionary dictionaryWithObjects:gameStateObjects forKeys:gameStateKeys];

    //Write to file
    [gameStateDict writeToFile:path atomically: YES];

//Reading from file
    //Reads the array stored in a .plist located at "path"
    NSDictionary *lastGameState = [NSDictionary dictionaryWithContentsOfFile:path];

字典.plist看起来像这样:

enter image description here

答案 1 :(得分:0)

保存级别:

[[NSUserDefaults standardUserDefaults] setInteger:5 forKey:@"level"];

阅读关卡:

NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey:@"level"];

每当用户进入该级别时,我都会设置它。你可以等到你被送到后台,但是等待真的没有意义。

相关问题