游戏在if语句之后停止

Game Stops after If statement

本文关键字:之后 语句 if 游戏      更新时间:2023-10-16

我运行此代码,但是当我到达屏幕边缘时,它不允许我进入新的旅行方向而不是关闭控制台。/p>

class weapon
{
public:
    weapon();
    weapon(int x, int y);
    int xPos;
    int yPos;
};
weapon::weapon()
{
    xPos = 0;
    yPos = 0;
}
weapon::weapon(int x, int y)
{
    xPos = x;
    yPos = y;
}

struct Game
{
    weapon Bow;
    weapon Sword;
};
int main()
{
    weapon * Bow = new weapon(4, 6);   // how to add cout to this to show you have the weapon?
    int xPos = 1;
    int yPos = 1;
    char input = '#';

    while (xPos >= 1 && xPos <= 20 && yPos >= 1 && yPos <= 20)
    {
        cout << "Current x-coord = " << xPos << " Current y-coord = " << yPos << endl;
        cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
        cin >> input;
        switch (input)
        {
        case 'E': case 'e':
            ++xPos;
            break;
        case 'W': case 'w':
            --xPos;
            break;
        case 'N': case 'n':
            ++yPos;
            break;
        case 'S': case 's':
            --yPos;
            break;
        }
        if (xPos <= 0 || xPos >= 21 || yPos <= 0 || yPos >= 21)
        {
            cout << "There is a wall in the way!" << endl;             //how do i make it continue the game after hitting a wall
            cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
            //cin >> input;     // this whole section needs some fixing
        }
    }

    return 0;
}

正确的解决方案应返回到WHIL循环,允许用户输入旅行的新输入方向。

一旦到达墙,while的条件为false,循环退出。

我将进行修改条件而不是首先修改,然后检查它是否有效:

while (xPos >= 1 && xPos <= 20 && yPos >= 1 && yPos <= 20)
{
    cout << "Current x-coord = " << xPos << " Current y-coord = " << yPos << endl;
    cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
    cin >> input;
    switch (std::toupper(input))
    {
    case 'E':
        if (xPos < 20)
            ++xPos;
        else
            cout << "There is a wall to the east!" << endl;
        break;
    case 'W':
        if (xPos > 1)
            --xPos;
        else
            cout << "There is a wall to the west!" << endl;
        break;
    // and the other two cases...
}