*C++ Finally, fill in the code for a play function that uses the battleShip clas
ID: 3731670 • Letter: #
Question
*C++
Finally, fill in the code for a play function that uses the battleShip class (SEE CODE AT BOTTOM) and runs a game of Battleship. Keep hitting all three ships until all three have been sunk, and always hit them in the order Destroyer, Carrier, then Cruiser.
void play(){ //TODO: Declare 3 instances/objects of the battleship class: Destroyer Carrier Cruiser
//TOD0: Give the ships a size: Destroyer-3 Carrier-5 Cruiser-2
// you will need to call the appropriate methods
// Once you have this running for one, expand this while loop to include the other two instances. Have the while loop end when all three ships have been sunk.
// Make your while condition while ship one is not sunk OR ship two is not sunk OR ship three is not sunk.
while(ship_one.isSunk() == false){ ship_one.recordHit(); } } If your program is running correctly, we expect the following output: Destroyer has been hit 1 times. Carrier has been hit 1 times. Cruiser has been hit 1 times. Destroyer has been hit 2 times. Carrier has been hit 2 times. Cruiser has been hit 2 times. Destroyer has been hit 3 times. Carrier has been hit 3 times. Cruiser has been hit 3 times. Destroyer has been sunk. Destroyer has been hit 4 times. Carrier has been hit 4 times. Cruiser has been hit 4 times. Destroyer has been sunk. Destroyer has been hit 5 times. Carrier has been hit 5 times. Cruiser has been hit 5 times. Destroyer has been sunk. Carrier has been sunk. Cruiser has been sunk.
class battleShip
{
private:
string name;
int size;
int hits;
public:
battleShip(string nm)
{
name=nm;
size=-1;
hits=0;
}
~battleShip()
{
}
void setShipName(string nm)
{
name=nm;
}
string getShipName()
{
return (name);
}
void setSize(int n)
{
size=n;
}
int getSize()
{
return(size);
}
void recordHit()
{
hits++;
if(size>=hits)
cout<<name<<" has been hit "<< hits<<" times."<<endl;
}
bool isSunk()
{
if(hits>=size)
{
cout<<name<<" has been sunk. "<<endl;
return 1;
}
return 0;
}
};
Explanation / Answer
Please find my implementation.
void play(){
// declaring three vaariables
battleShip Destroyer("Destroyer");
battleShip Carrier("Carrier");
battleShip Cruiser("Cruiser");
// setting the ship size
Destroyer.setSize(3);
Carrier.setSize(5);
Cruiser.setSize(2);
while(Destroyer.isSunk() == false){
Destroyer.recordHit();
}
while(Carrier.isSunk() == false){
Carrier.recordHit();
}
while(Cruiser.isSunk() == false){
Cruiser.recordHit();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.