I have an assignment to make a robot controller for a University project. At the moment it is going quite well, but I have a niggling bug that is just darn annoying and I can't seem to correct it.
Basically, I have to design a contrasting controller to enable random movement while avoiding obstacles. So, I have a robot which appears as "R" on the console, which is within a 10 by 10 area. Here is the code I use to initialise my 2D vector, and then draw the grid:
void matrix::init() // init my 2D vector
{
dot = 10; // 10 by 10 area
vector2D.resize(dot);
for (int i=0; i<dot; i++)
{
vector2D[i].resize(dot);
}
}
void matrix::draw() // drawing the vector to the screen
{
for(int i=0; i<dot; i++)
{
for(int j=0; j<dot; j++)
{
cout <<vector2D[i][j]<<"."; // I being the Y access, J the X access
}
cout<<endl;
}
}
void matrix::update()
{
init();
draw();
}
This is in its own class called matrix.cpp
, which is then called in the main.cpp with m.update();
m
being an object of matrix
Now, the robot position on screen is being set with this code within the matrix.cpp
class
void matrix::robotPosition(int x, int y)
{
bot = 'R';
cout << "X Pos"<< x <<endl;
cout << "Y Pos"<< y <<endl;
vector2D[x][y] = bot; // Outputting location of robot onto the grid / matrix
}
There is more code I have developed to control the position on screen, but I don't think that is needed at this point in my question.
int main()
{
matrix m;
robot r;
while(true)
{
m.update(); // vector2D init and draw
m.robotPosition(r.getX(), r.getY());
r.update();
system("pause");
}
}
Every time my program loops through the while loop it draws another robot on the screen, but doesn't seem to remove the old one. The code works by assigning a certain X
and Y
in the 2D vector with the char 'R'
(Which is my Robot). Is my thinking correct that I will have to draw the 2D matrix after each movement cycle?
Thanks
When you first set the robot position to, say, (5,5), you will set
vector2D[5][5]
toR
. Then if you set the position to something like (5,6), you will setvector2D[5][6]
toR
. Now both elements[5][5]
and[5][6]
are set toR
, so the robot is in both positions.There are a few solutions that depend on how you want to design it:
matrix
and at the beginning ofrobotPosition
set that position to whatever the non-robot character is. This will clear the previous position before setting the new one.update
at the beginning of each frame, which attempts to resize the vectors to exactly the same size they already are - this doesn't clear it. Instead, you should do that work in the constructor, and you can turninit
into aclear
function.matrix
for each time step, then you need to move the declaration ofmatrix m;
into thewhile
loop. Then you have one for each frame which should be cleared during construction (if you move theinit
stuff to the constructor).