C ++建议如何打破while循环

时间:2014-09-29 12:09:54

标签: c++ arrays

我正在建造一艘战列舰游戏,我需要一些建议来解决这个问题。

Okey所以问题是当两个玩家击落所有船只时游戏结束,这是由一个while循环控制的,我希望它能够像一个玩家击落一样快地突破对手。

问题在于函数void ShootAtShip(int board1[], int board2[], string names[], int cap)而while循环说while ((board1[i] != 0 || board2[i] != 0))我认为问题是while循环必须在它结束之前从上到下一直运行,我希望它在中间突破IF板1全部为0。

    bool isGameOver(int board1[], int board2[], int cap)
{
    bool lost1 = true;
    bool lost2 = true;
    for (int i = 0; i < cap && lost1 != false; ++i)
        if (board1[i] != 0)
            lost1 = false;
    if (lost1)
        return true;
    for (int i = 0; i < cap && lost2 != false; ++i)
        if (board2[i] != 0)
            lost2 = false;
    return lost2;
}

void ShootAtShip(int board1[], int board2[], string names[], int cap) {
    const int hit = 0;
    int shot = 0;
    int temp;
    isGameOver(board1, board2, cap);

    for (int i = 0; i < cap; i++) {
        while ((board1[i] != 0 || board2[i] != 0)) { //detects if any board has all their ships shot down

            cout << names[1] << " set a position to shoot." << endl;
            cin >> shot;
            temp = shot;

            while ((shot >= cap) || (shot < 0)) {       //detects if the number is allowed
                cout << "That number is not allowed, " << names[1] << " set a position to shoot." << endl;
                cin >> shot;
            }

            if (board1[shot] != 0) {
                board1[shot] = 0;
                cout << "Hit!" << endl;
            }
            else {
                cout << "You missed." << endl;
            }

            shot = 0;

            cout << names[0] << " set a position to shoot." << endl;
            cin >> shot;

            while ((shot >= cap) || (shot < 0)) {       //detects if the number is allowed
                cout << "That number is not allowed, " << names[0] << " set a position to shoot." << endl;
                cin >> shot;
            }

            if (board2[shot] != 0) {
                board2[shot] = 0;
                cout << "Hit!" << endl;
            }
            else {
                cout << "You missed." << endl;
            }

        }


    }



    cout << "Testing is while loop stops";
}

1 个答案:

答案 0 :(得分:4)

因此循环不会中断的原因是因为您在条件中使用了错误的逻辑运算符。

while ((board1[i] != 0 || board2[i] != 0)) 应该 while (board1[i] && board2[i])

我相信你正在思考&#34;如果第1板是空的或者第2板是空的,那么打破&#34;,但是你输入的是&#34;如果第1板还剩下任何东西,或者董事会2还剩下任何东西,继续前进&#34;。

另外,请注意if (n != 0)可能比if (n)更有效(并且相同)。