I have written a solution of a Mars Rover problem in C++ using OOP, but I am not fully satisfied with the design. What changes can I make to improve the design?
Problem description is:
A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.
In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class Rover{
int x;
int y;
char orientation ;
public :
Rover();
Rover( int , int , char );
void rotateLeft();
void rotateRight();
void movePosition();
void displayPosition();
};
Rover :: Rover()
{
x =0;
y =0;
orientation = 'N';
}
Rover :: Rover ( int positionX , int positionY , char Orientation )
{
x= positionX;
y= positionY;
orientation = Orientation ;
}
void Rover:: displayPosition()
{
cout<<x<<" "<<y<<" "<<orientation;
}
void Rover :: rotateLeft()
{
if(orientation=='N')
orientation= 'W';
else if(orientation=='W')
orientation='S';
else if(orientation=='S')
orientation='E';
else if(orientation=='E')
orientation='N';
}
void Rover :: rotateRight()
{
if(orientation=='N')
orientation= 'E';
else if(orientation=='W')
orientation='N';
else if(orientation=='S')
orientation='W';
else if(orientation=='E')
orientation='S';
}
void Rover ::movePosition()
{
if(orientation=='N')
y++;
else if(orientation=='W')
x--;
else if(orientation=='S')
y--;
else if(orientation=='E')
x++;
}
int main()
{
int x,y; char orient ;
cin>>x>>y>>orient;
Rover firstRover(x,y,orient);
firstRover.displayPosition();
string roverMovement;
cin>>roverMovement;
for(int i=0 ; i < roverMovement.size() ; i++ )
{
if(roverMovement[i]=='L')
firstRover.rotateLeft();
else if(roverMovement[i]=='R')
firstRover.rotateRight();
else
firstRover.movePosition();
}
firstRover.displayPosition();
return 0;
}
How the design of this code can be improved?
movePosition
into something likemoveForward
. Also, I would never use bracket-less if blocks. \$\endgroup\$ – njzk2 Jun 29 '16 at 19:15