class Child:public Parent{
public:
enum Direction { Left, Right, Up, Down };
Direction direction;
void Update();
private:
int x,y;
void ChangeDirection();
void Draw();
};
I need the Update() function which invokes ChangeDirection() and Draw() to increment and decrements the x y values upon current direction which i have done. My problem is that y or x cannot be (-)value.
And also ChangeDirection() should assign a random direction to direction data and again this direction must be different to current direction. I was able to cout random directions within the same ChangeDirection() function this way
Direction direction = static_cast<Direction>(rand() % 4);
cout << direction;
but again sometime it prints the same direction. Now what i want is, the random assignment to direction should occur in ChangeDirection() member function not allowing the current value again but it should display the results through the void Draw(); member function which increments or decrements the x y values without letting it to be (-)value (should be clamped to 0). this is what i have done for that.
if ( direction == 0 ){
cout << "Right";
x++;
}
else if (direction == 1 ){
cout << "Down";
y++;
}
else if (direction == 2 ){
cout << "Up";
y--;
}
else if (direction == 3 ){
cout << "Left";
x--;
}
Draw();
But it is giving (-)values. how do I step forward ..
Since you are assigning a random direction, it makes sense that the direction which is assigned sometimes is equal to the previous direction. Try something like:
Direction direction = static_cast<Direction>((currentDirection + 1 + (rand() % 3) ) % 4);
to ensure that you get a new direction
Edit: To answer the other part of your question, you must check the value of x and y prior to incrementing or decrementing to ensure that they are within the bounds of whatever you are currently using. Here is an example of what I am talking about:
if(x > 0){
x--;
} else {
//do something else
}