×
Change Orientation
Change Theme, Dark/Light
Go to Spaces
#include
using namespace std; int main() { // We put "1" to indicate there is a ship. bool ships[4][4] = { { 0, 1, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }; // Keep track of how many hits the player has and how many turns they have played in these variables int hits = 0; int numberOfTurns = 0; // Allow the player to keep going until they have hit all four ships while (hits < 4) { int row, column; cout << "Selecting coordinates\n"; // Ask the player for a row cout << "Choose a row number between 0 and 3: "; cin >> row; // Ask the player for a column cout << "Choose a column number between 0 and 3: "; cin >> column; // Check if a ship exists in those coordinates if (ships[row][column]) { // If the player hit a ship, remove it by setting the value to zero. ships[row][column] = 0; // Increase the hit counter hits++; // Tell the player that they have hit a ship and how many ships are left cout << "Hit! " << (4-hits) << " left.\n\n"; } else { // Tell the player that they missed cout << "Miss\n\n"; } // Count how many turns the player has taken numberOfTurns++; } cout << "Victory!\n"; cout << "You won in " << numberOfTurns << " turns"; return 0; }
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 1
Miss
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 2
Hit! 3 left.
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 2
Miss
Selecting coordinates
Choose a row number between 0 and 3: 3
Choose a column number between 0 and 3: 2
Hit! 2 left.
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 2
Hit! 1 left.
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 0
Miss
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 1
Hit! 0 left.
Victory!
You won in 7 turns
Process returned 0 (0x0) execution time : 24.994 s