Reputation: 361
I'm building a battleships game and I need some advices how to deal with this problem.
Okey so the problem is that the game ends when both players has shoot down all the ships, this is controlled by a while loop and i want it to break as fast as one player has shot down the opponent.
The problem is at the function void ShootAtShip(int board1[], int board2[], string names[], int cap)
and the while loop says while ((board1[i] != 0 || board2[i] != 0))
what I think is the problem is that the while loop has to run all the way from top to bottom before it ends, I want it to break in the middle IF board1 gets all 0's.
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";
}
Upvotes: 0
Views: 166
Reputation: 2684
So the reason the loop does not break is because you are using the wrong logic operator in your condition.
while ((board1[i] != 0 || board2[i] != 0))
should be
while (board1[i] && board2[i])
I believe you're thinking "if board 1 is empty or board 2 is empty, then break", but what you typed out is "if board 1 has anything left, or board 2 has anything left, keep going".
Also, do note that if (n != 0)
is potentially more efficient (and just the same) as if (n)
.
Upvotes: 4