【发布时间】:2019-12-12 22:41:01
【问题描述】:
对于我的项目,我必须用 C++ 制作游戏。我们的老师选择了一款名为 Squadro 的棋盘游戏。为了快速解释,我们有一个有 49 个盒子和 10 个棋子,5 个红色和 5 个黄色的棋盘。并且在每一回合,玩家都必须移动他们的棋子等。
游戏一开始是这样的:
如果你想了解更多关于这款游戏的信息,请点击此链接:https://www.youtube.com/watch?v=pzOK7b_sq2I(虽然是法语,但我想你会明白的)。但问题不在这里。我用 SFML 等制作了一个 GUI。我们必须再实现一项功能。事实上,我们必须让用户保存他们的游戏或不保存。我设法通过在文本文件中写入日期、玩家姓名和游戏的“矩阵”来做到这一点。这是我的问题:启动游戏。我认为这可能并不难,但我尝试了很多想法。那么我需要什么来解决我的问题?我必须打开名为“saves.txt”的文本文件(已经完成)并获取有用的数据:获取游戏日期、玩家姓名并构建我的矩阵,最后我可以启动游戏。为了帮助我完成这项任务,我与您分享我已经完成的工作以及我的 saves.txt 的样子。
感谢您的帮助!
目前我的 saves.txt 看起来像:
我保存游戏的代码:
else if(event.key.code == sf::Keyboard::Escape) //if the user press escape it will close the SFML Window
{
window.close();
system("cls");
cout << "Wanna save the game? " << endl;
string choice;
cin >> choice;
if((choice == "yes") || (choice == "Yes") || (choice == "YES"))
{
//Get date and current time
time_t tt;
struct tm * ti;
time (&tt);
ti = localtime(&tt);
cout << asctime(ti) << endl;
//Opening the file
string const File("saves.txt");
ofstream Flux(File.c_str(), ios::app);
Flux << "----------------------------------------------------" << endl;
Flux << "date " << asctime(ti) << endl;
Flux << "Type of game : two players" << endl;
Flux << "currentPlayer : " << currentPlayer << endl;
Flux << "waitingPlayer : " << waitingPlayer << endl;
cout << endl;
if(Flux)
{
for(int u=0; u < 7; u++)
{
for(int v=0; v < 7; v++)
{
if(game[u][v] != ' ')
{
Flux << game[u][v] << " line : " << u << " | column :" << v << endl;
}
}
cout << endl;
}
Flux << "\n----------------------------------------------------" << endl;
}
else
{
cerr << "ERROR : Impossible to save the game ! " << endl;
}
}
else
{
exit(0);
}
还有我未完成的函数 loadGame();
void loadGame()
{
vector<string> dateGame(5);
ifstream file;
file.open("saves.txt");
if(file.fail())
{
cerr << "Error at the opening of the file";
exit(1);
}
string search = "date";
bool isFound = 0;
while(!file.eof())
{
string temp = "";
getline(file,temp);
for(int i = 0; i < search.size(); i++)
{
if(temp[i]==search[i])
{
isFound = 1;
dateGame.push_back(search[i]); //it doesn't work
}
else
{
isFound =0;
break;
}
}
if(isFound)
{
cout << "Password is: ";
for(int i = search.size()+1;i<temp.size();i++)
cout << temp[i];
break;
}
}
if(file.eof()&&(!isFound))
{
cout << "String not found!\n";
}
file.close();
}
得到我的数据后,我就可以启动 init(char game[7][7], ... , **params);
编辑:我的游戏是这样表示的:
char game[7][7] = {
{' ',' ',' ',' ',' ',' ',' '},
{'>',' ',' ',' ',' ',' ',' '},
{'>',' ',' ',' ',' ',' ',' '},
{'>',' ',' ',' ',' ',' ',' '},
{'>',' ',' ',' ',' ',' ',' '},
{'>',' ',' ',' ',' ',' ',' '},
{' ','A','A','A','A','A',' '}
};
【问题讨论】:
-
嘿,不幸的是,它不相关。在添加我的矢量 dateGame 之前,它运行良好。
-
//it doesn't work没什么好说的。这可能意味着你的电脑长了腿,吃掉了你的房子。幸运的是,我已经弄清楚了这个“上下文”的事情。我花了几十年的时间,但这是值得的。search[i]是char但dateGame.push_back(search[i]);想要std::string。 -
哦,我明白了(我不得不承认这是一个大错误)。但是我该怎么做呢?
-
我将不得不将解决方案留给弄清楚您要做什么的人。我可以帮助您摆脱编译器错误,但从长远来看,这对您没有任何好处。
标签: c++ file text game-development