使用C++ fopen制作游戏存档
(2011-12-22 20:45:30)
标签:
cit |
分类: c/c |
#ifndef SAVE_H_
#define SAVE_H_
#define NumGameLevel 4 //我定义了4个大关卡
#define NumLevel 6//这个为小关卡
#define SaveMgr Save::Instance()
//因为也许我其他的控制也需要用来修改存档信息包括存档的一些验证所以我把他做成了一个单件..
class Save {
public:
Save();
~Save();
static Save* Instance();
void LoadSave();
void LoadGame();
void SaveGame();
int GetSave(int Level);
void SetSave(int Level,int Num);
private:
int m_nSave[NumGameLevel];//记录关卡文件很简单..
char m_pSaveFile[255];//记录了存档的目录..因为我只需要一个存档所以我是写死的..大家可以灵活修改
};
#endif
#import "Save.h"
#import <stdio.h>
#import <fcntl.h>
Save::Save()
{
}
Save::~Save()
{
}
void Save::LoadSave()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentsDirectory = [paths objectAtIndex:0];
NSString *SaveFileName = @"/SaveGame";
NSLog(@"%d path is:%@",0,DocumentsDirectory);
const char* SaveFile = [[DocumentsDirectory stringByAppendingString:SaveFileName]UTF8String];
sprintf(m_pSaveFile, "%s",SaveFile);
NSLog(@"path is:%s",m_pSaveFile);
FILE *p_File;
if ((p_File = fopen(m_pSaveFile, "rt"))==NULL)
{
NSLog(@"文件打开失败,正在新建立文件");
p_File = fopen(m_pSaveFile, "wt");
if (p_File!=NULL)
{
for (int i=0; i<NumGameLevel; ++i)
{
fprintf(p_File, "%d\n",1);
}
NSLog(@"新存档文件建立成功");
fclose(p_File);
}
}
}
Save* Save::Instance()
{
static Save instance;
return &instance;
}
void Save::SetSave(int Level,int Num)
{
m_nSave[Level-1] = Num;
}
void Save::LoadGame()
{
FILE *p_File;
if ((p_File = fopen(m_pSaveFile, "rt"))==NULL){
NSLog(@"path is:%s",m_pSaveFile);
fclose(p_File);
NSLog(@"文件打开失败");
}else {
int Num = 0;
for (int i=0; i<NumGameLevel; i++)
{
fscanf(p_File, "%d",&Num);
if (Num>0&&Num<NumLevel) {
m_nSave[i] = Num;
}else {
m_nSave[i] = 1;
}
}
fclose(p_File);
}
}
void Save::SaveGame()
{
FILE *p_File;
if ((p_File = fopen(m_pSaveFile, "wt+"))==NULL){
fclose(p_File);
NSLog(@"文件保存失败");
}
for (int i=0; i<NumGameLevel; ++i) {
fprintf(p_File, "%d/n",m_nSave[i]);
}
fclose(p_File);
}
int Save::GetSave(int Level)
{
return m_nSave[Level-1];
}
前一篇:iphone 网络编程总结
后一篇:导航器添加自定义的按钮