#ifndef BATTLESHIP_H_ #define BATTLESHIP_H_ // coordinates (location) of the shi
ID: 3531074 • Letter: #
Question
#ifndef BATTLESHIP_H_
#define BATTLESHIP_H_ // coordinates (location) of the ship and shots
class location{
public:
location(void); // void constructor, assigns -1 to X
void pick(void); // picks a random location
void fire(void); // asks the user to input the // coordinates of the next shot
void print(void) const; // prints location in format "a1" // returns true if the two locations match
friend bool compare(location, location);
private:
static const int fieldSize=5; // the field (ocean) is fieldSize X fieldSize
int x; // 1 through fieldSize
char y; // 'a' through fieldSize };
// contains ship's coordinates (location) and whether is was sunk
class ship{
public:
ship(void); // void constructor, sets sunk=false
bool match(location) const; // returns true if this location matches
// the ship's location
bool isSunk(void) const {return(sunk);}; // checks to see if the ship is sunk
void sink(void); // sets "sunk" member variable of the ship to true
void setLocation(location); // deploys the ship at the specified location
void printShip(void) const; // prints location and status of the ship
private:
location loc;
bool sunk;
}; // contains the fleet of the deployed
Explanation / Answer
//untested, but something like this:
//battleship.cpp
#include<iostream>
#include<ctime>
#include<cstdlib>
#include"battleship.h"
using namespace std;
location::location(void){x=-1;}
void location::pick(void){
x=rand()%fieldSize;
y='a'+rand()%fieldSize;
}
void location::fire(void){
bool flag=false;
do{
flag=false;
cout<<"Please enter coordinate(char#): ";
cin>>y>>x;
if(x>fieldSize|| x<1){
cout<<"Invalid x coordinate entered. ";
flag=true;
}
if((y>=fieldSize+'a')||(y<'a')){
cout<<"Invalid y coordinate entered. ";
flag=true;
}
}while(flag==true);
x--;
return;
}
void location::print(void)const{
cout<<y<<x;
}
friend bool compare(location a,location b){
return ((a.x==b.x)&& (a.y==b.y));
}
ship::ship(void){sunk=false;}
bool ship::match(location l) const{
return compare(loc,l);
}
bool ship::isSunk(void) const {return sunk;} // checks to see if the ship is sunk
void ship::sink(void){sunk=true;}
void ship::setLocation(location l ){ //this may give you permission error, so you might need to add mutators to location class
loc.x=l.x;
loc.y=l.y;
}
void ship::printShip(void) const{
cout<<y<<x+1;
if(sunk==false)
cout<<" up";
else
cout<<" sunk";
return;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.