溫馨提示×

C++ 貪吃蛇怎樣保存和加載游戲

c++
小樊
85
2024-06-25 17:04:51
欄目: 編程語言

在C++中,可以使用文件輸入輸出操作來保存和加載貪吃蛇游戲的狀態(tài)。以下是一個簡單的示例代碼,演示如何保存和加載貪吃蛇游戲的狀態(tài):

#include <iostream>
#include <fstream>
#include <vector>

struct SnakeSegment {
    int x;
    int y;
};

struct GameData {
    int score;
    std::vector<SnakeSegment> snakeSegments;
};

void saveGame(const GameData& gameData, const std::string& filename) {
    std::ofstream file(filename);
    if (file.is_open()) {
        file << gameData.score << std::endl;
        for (const SnakeSegment& segment : gameData.snakeSegments) {
            file << segment.x << " " << segment.y << std::endl;
        }
        file.close();
        std::cout << "Game saved successfully!" << std::endl;
    } else {
        std::cout << "Unable to open file for saving game data." << std::endl;
    }
}

GameData loadGame(const std::string& filename) {
    GameData gameData;
    std::ifstream file(filename);
    if (file.is_open()) {
        file >> gameData.score;
        int x, y;
        while (file >> x >> y) {
            SnakeSegment segment = {x, y};
            gameData.snakeSegments.push_back(segment);
        }
        file.close();
        std::cout << "Game loaded successfully!" << std::endl;
    } else {
        std::cout << "Unable to open file for loading game data." << std::endl;
    }
    return gameData;
}

int main() {
    GameData gameData;
    gameData.score = 100;
    gameData.snakeSegments = {{1, 1}, {2, 1}, {3, 1}};

    saveGame(gameData, "saved_game.txt");

    GameData loadedGameData = loadGame("saved_game.txt");

    std::cout << "Loaded game score: " << loadedGameData.score << std::endl;
    std::cout << "Loaded game snake segments:" << std::endl;
    for (const SnakeSegment& segment : loadedGameData.snakeSegments) {
        std::cout << "(" << segment.x << ", " << segment.y << ")" << std::endl;
    }

    return 0;
}

在這個示例中,SnakeSegment 結(jié)構(gòu)體表示蛇的一個段落,GameData 結(jié)構(gòu)體表示整個游戲的狀態(tài),包括分?jǐn)?shù)和蛇的段落列表。saveGame 函數(shù)用于將游戲狀態(tài)保存到文件中,loadGame 函數(shù)用于從文件中加載游戲狀態(tài)。在 main 函數(shù)中,我們創(chuàng)建一個游戲狀態(tài),保存到文件中,并從文件中加載游戲狀態(tài)進(jìn)行驗證。

請注意,這只是一個簡單的示例,實際的游戲保存和加載可能需要更復(fù)雜的邏輯,比如保存游戲地圖、食物位置等更多的信息。您可以根據(jù)實際需求擴(kuò)展和修改代碼。

0