读取和写入游戏的文件

reading and writing file for a game

本文关键字:文件 游戏 读取      更新时间:2023-10-16

我正在用随机初始化的字母(例如B A S T E N(制作一个游戏,用户将只使用这些字母输入尽可能多的单词。我有一个文件,其中包含正确的单词及其相应的点。我的问题是如何防止用户一遍又一遍地使用相同的单词?

我正在尝试使用 ofstream,以便每当用户输入正确的单词时,它都会被添加到空白文件中

void start()
{
    char ch;
    do {
        clrscr();
        long* newptr = 0;
        time_t start = time(newptr);
        char arr[10][50] = {" B A N S E T ", " R E D G A E ", " S A H L E S ", " P R G N I S ",
                            " A L E R L Y ", " L A C S A U ", " A C Q U K Y ", " M B L U E J ",
                            " Z E D Z U B ", " L E A Z D Z "};
        int i = 0, sum, x;
        while (i != 2) {
            clrscr();
            sum = 0;
            do {
                clrscr();
                cout << "t**********************************************n";
                cout << "t*             W O R D  S E E K E R           *n";
                cout << "t**********************************************n";
                cout << "nttttt SCORE: " << sum << " /50 pts"
                     << "n                  ******************************n";
                cout << "                  *       " << arr[i] << "        *n";
                cout << "                  ******************************nn";
                cout << " 6 letter=10pts, 5 letter=8pts, 4 letters=6pts, 3 letter=4ptsnn";
                char a[20], b[20];
                int c;
                // this is where I have my problem
                if (i == 0) {
                    ifstream fin;
                    fin.open("lvl1.txt");
                    if (fin.fail()) {
                        cout << "File doesn't exist!";
                        exit(1);
                    }
                    ofstream fout;
                    fout.open("trial.txt");
                    if (fout.fail()) {
                        cout << "Output file opening failed.n";
                    }
                    cout << "tEnter word: ";
                    cin >> a;
                    do {
                        fout << a;
                        fin >> b >> c;
                        if (fin.eof() == 1) {
                            cout << "Incorrect! Try Again!";
                            delay(1000);
                            exit(1);
                        }
                    } while (strcmp(a, b) != 0);
                    fin.close();
                    if (strcmp(a, b) == 0) {
                        sum += c;
                    }
                }
            } while (sum < 50);
            i++;
        }
        x = time(newptr) - start;
        cout << "ntGood Job! Your time is " << x << " secondsn";
        cout << "tDo you want to continue?(Y/N): ";
        cin >> ch;
    } while (ch != 'n' || ch != 'N');
}

一个问题是,您是要在运行时还是程序结束后记住这些单词。

要在程序结束后记住单词,请将它们写入文件。

若要记住用户在运行时输入的单词,请使用容器,例如 std::vector 。 将单词追加到容器,然后对容器进行排序。 在追加之前,可以使用std::binary_search在容器中查找单词。