Part 3 For part 3, you will write a function called fire (), which gives the res
ID: 644793 • Letter: P
Question
Part 3 For part 3, you will write a function called fire (), which gives the result of a player firing at a particular coordinate. The function header should look like this: x and y are the coordinates of the shots target space. You'll note that the functions returns a string. The function should return a different message depending on the result of the shot. . Return Out of bounds! if the target space is not on the grid ? Return HIT! if the target space contains a ship (i.e any character other than a ?, ?) . Return ?CLOSE!? if the target space does NOT contain a ship but there is a ship in any one of the 8 adjacent squares (so diagonals count!!) to the target space . Hint: Be careful about checking adjacent spaces when the target space is on the edge of the grid! ? Return -MISS!' in all other casesExplanation / Answer
#include <iostream>
using namespace std;
void printMap(char map[10][10]){
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 10; ++j){
cout << map[i][j];
}
cout << endl;
}
cout << endl;
}
void placeShip(char map[10][10], int x1, int y1, int x2, int y2, char ship){
if((x1 > 9 || x1 < 0) || (x2 > 9 || x2 < 0) || (y1 > 9 || y1 < 0) || (y2 > 9 || y2 < 0)){
cout << "Out of bounds" << endl;
return;
}
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 10; ++j){
if(map[i][j] == ship){
cout << "Ship already exists" << endl;
return;
}
}
}
if(!(x1 != x2 || y1 != y2)){
cout << "Neither horizontal nor vertical" << endl;
return;
}
if(x1 == x2){
int y11 = y1 > y2 ? y2 : y1;
int y22 = y1 > y2 ? y1 : y2;
for(int i = y11; i <= y22; ++i){
if(map[x1][i] != '.'){
cout << "another ship exists in those coordinates" << endl;
return;
}
}
for(int i = y11; i <= y22; ++i){
map[x1][i] = ship;
}
}
else{
int x11 = x1 > x2 ? x2 : x1;
int x22 = x1 > x2 ? x1 : x2;
for(int i = x11; i <= x22; ++i){
if(map[i][y1] != '.'){
cout << "another ship exists in those coordinates" << endl;
return;
}
}
for(int i = x11; i <= x22; ++i){
map[i][y1] = ship;
}
}
}
string fire(char map[10][10], int x, int y){
if((x > 9 || x < 0) || (y > 9 || y < 0)){
return "Out of bounds!";
}
if(map[x][y] != '.'){
return "HIT!";
}
for(int i = -1; i <= 1; ++i){
for(int j = -1; j <= 1; ++j){
if((x + i >= 0 && x + i <= 9) && (y + j >= 0 && y + j <= 9) && map[x + i][y + j] != '.'){
return "CLOSE!";
}
}
}
return "MISS!";
}
int main(){
char map[10][10];
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 10; ++j){
map[i][j] = '.';
}
}
printMap(map);
placeShip(map, 1, 1, 1, 3, 'b');
printMap(map);
cout << fire(map, 1, 0) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.