我正在为 iPhone 制作一款 RPG 游戏,一切都很顺利,但我需要知道如何保存我的游戏关卡,这样即使用户关闭在后台运行的应用程序,整个游戏也不会重新开始. 我什至在考虑带回老式游戏并制作它,以便您必须输入密码才能从上次中断的地方开始。但即便如此,我也不知道如何正确保存游戏。另外,即使我确实保存了游戏,即使应用程序完全关闭,我如何才能让它保持保存状态?到目前为止,我已经尝试将保存数据代码添加到该AppWillTerminate
行但仍然没有。任何帮助表示赞赏。
问问题
844 次
2 回答
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 看起来像这样:
使用数组意味着在重新加载游戏状态时,您必须知道存储项目的顺序,这还不错,但是如果您想要更可靠的方法,您可以尝试使用 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 看起来像这样:
于 2012-08-23T06:07:23.710 回答
0
要保存关卡:
[[NSUserDefaults standardUserDefaults] setInteger:5 forKey:@"level"];
要读取级别:
NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey:@"level"];
每当用户进入该级别时,我都会设置它。您可以等到您被发送到后台,但等待真的没有意义。
于 2012-08-23T03:42:19.160 回答