Reputation: 361
I'm having a little bit problem with my game. What I want is when one out of two arrays becomes all 0's the loop will stop. Currently the loop stops when both arrays are equal to zero.
What I think is the problem but don't have a solution is that I have both array statements in one loop, it will run from top too bottom EVEN if array1(border1) has gotten all 0's.
What to you think?
void ShootAtShip(int board1[], int board2[], string names[], int cap) {
const int hit = 0;
int shot = 0;
bool won = false;
int temp;
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: 1204
Reputation: 2210
Especially when writing games, it's a good idea to try and organize your code into functions. Personally I would do something like this:
bool isGameOver(int board1[], int board2[], size_t cap)
{
bool lost1 = true;
bool lost2 = true;
for (size_t i = 0; i < cap && lost1 != false; ++i)
if (board1[i] != 0)
lost1 = false;
if (lost1)
return true;
for (size_t i = 0; i < cap && lost2 != false; ++i)
if (board2[i] != 0)
lost2 = false;
return lost2;
}
Then use this as a conditional to break the loop.
Since you are using c++ however, why not abstract the boards into a class? This would allow you to store info such as how many ships are left in each board.
Also consider using the std::array
class template in c++ so you won't have to pass the array size seperately and try to use size_t
or std::size_t
for array indexing.
Upvotes: 0
Reputation: 11499
The key is that you have to check the state of the entire board at each loop iteration. Like this:
void ShootAtShip(int board1[], int board2[], string names[], int cap) {
for (int i = 0; i < cap; i++)
{
while ( 1 )
{
bool board1HasShips = false;
bool board2HasShips = false;
for ( int j = 0; j < cap; j++ )
{
if ( board1[j] != 0 )
{
board1HasShips = true;
break;
}
}
for ( int j = 0; j < cap; j++ )
{
if ( board2[j] != 0 )
{
board2HasShips = true;
break;
}
}
if ( !board1HasShips || !board2HasShips ) break;
// past this point we know that both boards have ships.
// shoot at ships
}
}
}
Upvotes: 1