Question: (c) Extend step 2 and enable to show the current status -: Unknown Hit: * Miss: x #include #include #include struct Ship { char name[32];

(c) Extend step 2 and enable to show the current status

-: Unknown

Hit: *

Miss: x

#include #include #include

struct Ship { char name[32]; int topLeftX; int topLeftY; int bottomRightX; int bottomRightY; int hit; };

void initialize(struct Ship * ships) { strcpy(ships[0].name, "Carrier"); ships[0].topLeftX = 2; ships[0].topLeftY = 2; ships[0].bottomRightX = 2; ships[0].bottomRightY = 6; ships[0].hit = 0;

strcpy(ships[1].name, "BattleShip"); ships[1].topLeftX = 3; ships[1].topLeftY = 4; ships[1].bottomRightX = 3; ships[1].bottomRightY = 7; ships[1].hit = 0;

strcpy(ships[2].name, "Cruiser"); ships[2].topLeftX = 7; ships[2].topLeftY = 4; ships[2].bottomRightX = 9; ships[2].bottomRightY = 4; ships[2].hit = 0; strcpy(ships[3].name, "Submarine"); ships[3].topLeftX = 5; ships[3].topLeftY = 5; ships[3].bottomRightX = 5; ships[3].bottomRightY = 7; ships[3].hit = 0; strcpy(ships[4].name, "Destroyer"); ships[4].topLeftX = 8; ships[4].topLeftY = 8; ships[4].bottomRightX = 9; ships[4].bottomRightY = 8; ships[4].hit = 0; }

int isHit(struct Ship ship, int posX, int posY) { if(posX>=ship.topLeftX&&posX<=ship.bottomRightX&&posY>=ship.topLeftY&&posY<=ship.bottomRightY) return 1; else return 0; }

int isFinished(struct Ship * ships, int n) { int cnt = 0; for (int i = 0; i < n; i++) { if(ships[i].hit==1){ cnt++; } } if (cnt==n) { return 1; } else { return 0; } }

int main() { struct Ship ships[5]; initialize(ships);

char game[10][10]; for(int i=0; i<10; ++i){ for(int j=0; j<10; ++j){ game[i][j] = '-'; } }

while (1) { for(int i=0; i<10; ++i){ for(int j=0; j<10; ++j){ printf("%c", game[i][j]); } printf(" "); } int posX = 0; int posY = 0; scanf("%d %d", &posX, &posY);

int hit = 0; for (int i = 0; i < 5; ++i) { if (isHit(ships[i], posX, posY)) { ships[i].hit = 1; hit = 1; } } if (hit > 0) { printf("hit "); game[posX - 1][posY - 1] = '*'; if (isFinished(ships, 5)) { printf("All ships are sunk "); break; } } else { printf("miss "); game[posX - 1][posY - 1] = 'x'; } } return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!