I’m working on a Tetris-like game in C and I have two functions, check_left_side_occupation
and check_right_side_occupation
, which are very similar. I want to refactor them to avoid code duplication, but I’m not sure how to achieve that. Here is the relevant part of my code:
void check_right_side_occupation(int (*field)[field_width], figure *piece)
{
int x, y;
for (y=0; y < piece_size; y++) {
/* first different part */
for (x=piece_size-1; x >= 0; x--) {
/* end */
if (piece->form[y][x] == 0)
continue;
else {
if (field[y+piece->y_decline][x+piece->x_shift] == 1) {
/* second different part */
piece->x_shift--;
/* end */
return;
}
}
}
}
}
void check_left_side_occupation(int (*field)[field_width], figure *piece)
{
int x, y;
for (y=0; y < piece_size; y++) {
/* first different part */
for (x=0; x < piece_size; x++) {
/* end */
if (piece->form[y][x] == 0)
continue;
else {
if (field[y+piece->y_decline][x+piece->x_shift] == 1) {
/* second different part */
piece->x_shift++;
/* end */
return;
}
}
}
}
}
void side_pixel_occupied_by_field(
move_direction direction, int (*field)[field_width], figure *piece
)
{
switch (direction) {
case left:
check_left_side_occupation(field, piece);
break;
case right:
check_right_side_occupation(field, piece);
}
}
Is there a way to refactor these functions to avoid the code duplication and still maintain the functionality for checking both the left and right sides of the piece?
Any help or suggestions would be greatly appreciated!