I am writing a chess project using C++ and SDL. In this method I calculate all available moves a Knight can make and I want to refactor it. I basically move the knight Up/Down 2 squares and then Left/Right 1 square and then do the opposite. As you can see in the 2 for loops the difference is the way tempPosition.x and tempPosition.y are incremented and then the 2nd loop is the same as the first,but swapped (see comments)
std::vector<Position> available;
Position tempPosition;
int directions_double[2] = {-2, 2};
int directions_single[2] = {-1, 1};
for(int double_step : directions_double) {
tempPosition = position_;
tempPosition.x += double_step; // x+=doublestep
Position temp2_position = tempPosition;
for(int single : directions_single) {
tempPosition = temp2_position;
tempPosition.y += single; //y+=single step
if(InBoard(tempPosition))
available.push_back(tempPosition);
else
break;
}
}
for(int double_step : directions_double) {
tempPosition = position_;
tempPosition.y += double_step; //y += doublestep
Position temp2_position = tempPosition;
for(int single : directions_single) {
tempPosition = temp2_position;
tempPosition.x+=single; //x+= single step
if(InBoard(tempPosition))
available.push_back(tempPosition);
else
break;
}
}
return available;
}
The difference is very small. I thought of implementing a flag technique, but it didn't seem 'clean' enough. Any thoughts? Thank you.