Question
I have been trying to show the current status on the Battleship game (C programming). Please have a look at the code and let me
I have been trying to show the current status on the Battleship game (C programming). Please have a look at the code and let me know where I should fix! Thank you.
-: Unknown
Hit: *
Miss: x
-------------------------------------------------
Reference code:
#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.topLeftY && posY
int isFinished(struct Ship * ships, int n) { int cnt=0;
for(int i=0;i int main() { struct Ship ships[5]; initialize(ships); // array to store the game char game[10][10]; // initialize all values to unknown '-' for(int i=0;i while (1) { // for each time print the current state of the board for(int i=0;i int posX = 0; int posY = 0; scanf("%d %d", &posX,&posY); int hit = 0; for (int i = 0; i 0) { printf("hit "); // if there is a hit mark '*' in the board game[posX-1][posY-1] = '*'; if (isFinished(ships, 5)) { printf("All ships are sunk "); break; } } else { printf("miss "); // if there is no hit mark 'x' in the board game[posX-1][posY-1] = 'x'; } } return 0; } -------------------------------------------------- Please be able to produce the outputs below:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started