我正在为iPhone制作一款角色扮演游戏,一切都很顺利,但我需要知道如何保存我的游戏级别,以便即使用户关闭在后台运行的应用程序,整个游戏也不会重新开始。我甚至在考虑恢复老式的游戏,这样你就必须输入密码才能从你停止的地方开始。但即使这样,我也不知道如何正确地保存游戏。此外,即使我确实保存了游戏,我如何能够使它保持保存,即使应用程序完全关闭?到目前为止,我已经尝试将保存数据代码添加到AppWillTerminate行,但仍然没有结果。任何帮助都是非常感谢的。
发布于 2012-08-23 14:07:24
我不确定您是否要保存用户所处的级别,或者是否要保存游戏状态。如果你只是想保存用户所在的级别,你应该使用@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-23 11:42:19
要保存标高,请执行以下操作:
[[NSUserDefaults standardUserDefaults] setInteger:5 forKey:@"level"];要读取标高:
NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey:@"level"];每当用户进入该级别时,我都会设置它。你可以等到你被送到后台,但是等待真的没有意义。
https://stackoverflow.com/questions/12084117
复制相似问题