C++ 卡在切换游戏区域时

C++ Stuck in switching through my game's areas

本文关键字:游戏 区域 C++      更新时间:2023-10-16

大家好,我正在学习如何制作基于文本的RPG游戏,但我遇到了一个错误。所以首先这是我的代码:

#include <iostream>
using namespace std;
void newGameFunc();
void titleFunc();
int userInput = 0;
int playerInfo[2];
int playerLocation = 0;

bool running = 1;
int main() {
    while (running) {
        titleFunc();
        if (playerLocation == 1) {
            cout << "You are standing in the middle of a forest. A path veers off to the East and to the West.n";
            cout << " 1: Go Eastn 2: Go Westn";
            cin >> userInput;
            if (userInput == 1) playerLocation = 2; //East
            else if (userInput == 2) playerLocation = 3; //West 
        }
        if (playerLocation == 2) {
            cout << "You are in the Eastern edge of the forest. It's heavilly forested and it's almost imposible to navigate through. You do find 2 flags though.n";
            cout << " 1: Turn Backn 2: Pick the FLAG.n";
            cin >> userInput;
            if (userInput == 1) playerLocation = 1; //Start
            if (userInput == 2) running = 0;
        }
        if (playerLocation == 3) {
            cout << "There is a passage way that leads to a town in the seemingly distant town. There are two guards with shining metal chainmail which scales look as magistic as reptilian scales. Their logo resembles a black dragon spewing a string of fire. They tell you that in order to pass you must give them their lost flags.n";
            cout << " 1: Give the flags to both guards.n 2: Turn around.n 3: Bribe them--NOT AVAILABLE.)n";
        }
    }
    return 0;
}
void titleFunc() {
    cout << "tttt---Fantasee---nnn";
    cout << "tttt   1: Playn";
    cin >> userInput;
    if (userInput == 1) {
        newGameFunc();
    }
    else {
        running = 0;
    }
    return;
}
void newGameFunc() {
    cout << "Welcome to Fantasee, a world of adventure and danger.n";
    cout << "Since you are a new hero, why don't you tell me a little about yourself?n";
    cout << "For starters, are you a boy or a girl?n 1: Boyn 2: Girln";
    cin >> userInput;
    playerInfo[0] = userInput;
    cout << "And what kind of person are you?n 1: Warriorn 2: Archern 3: All-roundern";
    cin >> userInput;
    playerInfo[1] = userInput;
    playerLocation = 1;
    system("cls");
    return;
}

所以问题是,假设当我进入playerLocation 2并且我想回到playerLocation 1时,它只会启动函数titleFunc();而不是if (playerLocation == 1)语句。

您可能希望将titleFunc()放在 while 循环之前:

int main() {
    while (running) {
        titleFunc();
        ...

到:

int main() {
    titleFunc();
    while (running) {
        ...

你现在的方式,你在循环的每次迭代中都继续运行titleFunc(),并用它重置游戏。