Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++ program use the new style od C++ not the old one. Simple Battleship You w

ID: 3689726 • Letter: I

Question

In C++ program use the new style od C++ not the old one.

Simple Battleship

You will make a game similar to the classic board game Battleship. You will set up a 5 x 5, 2 dimensional array. In that array, you will use a random number generator to select 5 elements that will act as the placeholders for your "battleships". Your user will get 10 guesses to "seek and destroy" the battleships. After their 10 guesses, you will tell them how many ships they found. At some point during the program, you will need to display the game board (this is to assess your ability to traverse a 2 dimensional array).

Sample output (your program may vary in approach):

_______________________________

Welcome to Battleship! You have 10 chances to sink the 5 Battleships.

Enter a coordinate: 2 3
That is a miss!
Enter a coordinate: 4 1
That is a hit! There are 4 remaining ships.
Enter a coordinate: 5 5
That is a miss!
Enter a coordinate: 3 2
That is a miss!
Enter a coordinate: 1 1
That is a hit! There are 3 remaining ships.
Enter a coordinate: 2 4
That is a miss!
Enter a coordinate: 3 5
That is a miss!
Enter a coordinate: 4 5
That is a miss!
Enter a coordinate: 1 3
That is a hit! There are 2 remaining ships.
Enter a coordinate: 3 3
That is a miss!
You hit 3 out of 5 ships.
------------------------------------
2 0  2 0 0
0 0 -1 -1 0
0 -1 -1  1 -1
2 0 0 -1 0
0 0 0  1 -1

2 = Hit, 1 = Ship, -1 = Missed shot

Explanation / Answer

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
int arr[5][5];
srand (time(NULL));
int x,y,rem=5,hit=0;

for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
arr[i][j] = 0;
}
}


for(int i=1; i<=5; i++){
x = rand() % 5 + 1;   
y = rand() % 5 + 1;
arr[x-1][y-1] = 1;
}
  
cout << "Welcome to Battleship! You have 10 chances to sink the 5 Battleships" << endl;
  
int m=1;
while(m<=4){

if(hit==5){
break;
}
  
cout << "Enter a coordinate:" << endl;
cin >> x >> y;
  
if(arr[x-1][y-1]==1){
hit++;
arr[x-1][y-1] = 2;
cout << "That is a hit! There are " << --rem << " ships remaining." << endl;   
}else{
arr[x-1][y-1] = -1;
cout << "That is a miss!" << endl;   
}
m++;
}
  
cout << "You hit "<< hit <<" out of 5 ships." << endl;

for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
cout << arr[i][j] << " " << flush;
}
cout << endl;
}
}