贪吃蛇游戏数据保存代码用c++编写
时间: 2023-06-25 18:02:26 浏览: 115
以下是一个简单的贪吃蛇游戏数据保存的示例代码,使用C++语言编写:
```c++
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const string SAVE_FILE = "snake_save.txt"; // 保存文件名
struct Point {
int x;
int y;
Point(int x, int y) : x(x), y(y) {}
};
struct GameData {
int score;
vector<Point> snake;
Point food;
};
void saveGameData(const GameData& data) {
ofstream file(SAVE_FILE);
if (file.is_open()) {
file << data.score << endl;
for (const auto& p : data.snake) {
file << p.x << " " << p.y << endl;
}
file << data.food.x << " " << data.food.y << endl;
file.close();
cout << "Game data saved to " << SAVE_FILE << endl;
} else {
cout << "Error: Unable to open file " << SAVE_FILE << endl;
}
}
GameData loadGameData() {
ifstream file(SAVE_FILE);
GameData data;
if (file.is_open()) {
file >> data.score;
int x, y;
while (file >> x >> y) {
data.snake.emplace_back(x, y);
}
file >> data.food.x >> data.food.y;
file.close();
cout << "Game data loaded from " << SAVE_FILE << endl;
} else {
cout << "Error: Unable to open file " << SAVE_FILE << endl;
}
return data;
}
int main() {
// 示例代码,创建一个游戏数据并保存
GameData data;
data.score = 100;
data.snake.emplace_back(1, 1);
data.snake.emplace_back(2, 1);
data.snake.emplace_back(3, 1);
data.food = Point(5, 5);
saveGameData(data);
// 加载游戏数据并输出
GameData loadedData = loadGameData();
cout << "Loaded score: " << loadedData.score << endl;
cout << "Loaded snake:" << endl;
for (const auto& p : loadedData.snake) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
cout << "Loaded food: (" << loadedData.food.x << ", " << loadedData.food.y << ")" << endl;
return 0;
}
```
该代码使用了文件流(fstream)来读写数据,将游戏数据保存到指定的文件中,也可以从文件中加载游戏数据。在示例代码中,我们创建了一个GameData结构体,包含了游戏得分、贪吃蛇的身体坐标、以及食物坐标等数据。在保存数据时,我们将这些数据按照一定格式写入到文件中;在加载数据时,我们则按照相同的格式从文件中读取数据,并构造出一个新的GameData对象。
阅读全文