Question: I have C++ Plus code below for a game of battleship (one-way single player where the person guesses where the ships are located.) Currently the
I have C++ Plus code below for a game of battleship (one-way single player where the person guesses where the ships are located.) Currently the ships in this game only take up one spot on the grid. Could you modify the code to where my five ships vary in sizes just like the real game?
#include
#include
using namespace std;
const int SIZE = 10;
const int NUMBER_OF_SHIP= 5;
void displayGrid(char grid[][SIZE]) {
cout << " |";
for (int i = 0; i < SIZE; i++) {
cout << " " << i << " |";
}
cout << endl;
for (int i = 0; i < SIZE; i++)
{
for (int i = 0; i <= SIZE; i++)
{
cout << "---+";
}
cout << endl << " " << i << " |";
for (int j = 0; j < SIZE; j++)
{
cout << " " << grid[i][j] << " |";
}
cout << endl;
}
for (int i = 0; i <= SIZE; i++)
{
cout << "---+";
}
cout << endl;
}
void initializeGrid(char grid[][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
grid[i][j] = '-';
}
}
}
bool isEmpty(int coordinates[NUMBER_OF_SHIP][5], int rowValue, int colValue) {
for (int i = 0; i < NUMBER_OF_SHIP; i++) {
if (coordinates[i][0] == rowValue && coordinates[i][1] == colValue) {
return false;
}
}
return true;
}
void placeTwoShip(int coordinates[NUMBER_OF_SHIP][5]) {
int rowIndex = rand() % 10;
int colIndex = rand() % 10;
coordinates[0][0] = rowIndex;
coordinates[0][1] = colIndex;
for (int i = 1; i < NUMBER_OF_SHIP; i++) {
rowIndex = rand() % 10;
colIndex = rand() % 10;
if (isEmpty(coordinates, rowIndex, colIndex)) {
coordinates[i][0] = rowIndex;
coordinates[i][1] = colIndex;
} else {
i--;
}
}
}
void playGame(char grid[SIZE][SIZE], int coordinates[NUMBER_OF_SHIP][5]) {
int count = 0;
int row, col;
while (count != NUMBER_OF_SHIP) {
cout << "Enter The coordinate:";
cin >> row >> col;
if (isEmpty(coordinates, row, col)) {
grid[row][col] = 'M';
cout << "MISS!" << endl;
} else {
grid[row][col] = 'H';
count++;
cout << "HIT!" << endl;
}
displayGrid(grid);
}
cout << "Game Over!" << endl;
}
int main() {
srand(time(NULL));
int shipCoordinates[NUMBER_OF_SHIP][5];
char grid[SIZE][SIZE];
initializeGrid(grid);
placeTwoShip(shipCoordinates);
/*for(int i=0;i cout<<"Ship "<<(i+1)<<"("< }*/ displayGrid(grid); playGame(grid, shipCoordinates); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
