如何在C语言中重构相似函数,消除类俄罗斯方块游戏的代码重复?
重构类俄罗斯方块的左右侧占用检查函数(消除代码重复)
当然可以重构,核心思路是把两个高度相似函数中的重复逻辑提取为通用函数,用参数区分左右方向的差异点。以下是具体实现方案:
重构后的代码
首先定义通用的侧方占用检查函数,封装重复逻辑:
void check_side_occupation(int (*field)[field_width], figure *piece, int start_x, int step_x, int shift_adjust) { int x, y; for (y = 0; y < piece_size; y++) { // 根据步长正负判断循环终止条件,适配左右遍历方向 for (x = start_x; (step_x > 0) ? (x < piece_size) : (x >= 0); x += step_x) { if (piece->form[y][x] == 0) continue; if (field[y + piece->y_decline][x + piece->x_shift] == 1) { piece->x_shift += shift_adjust; return; } } } }
接着修改side_pixel_occupied_by_field,直接调用通用函数:
void side_pixel_occupied_by_field( move_direction direction, int (*field)[field_width], figure *piece ) { switch (direction) { case left: // 左侧检查:x从0正序遍历,占用时x_shift加1 check_side_occupation(field, piece, 0, 1, 1); break; case right: // 右侧检查:x从piece_size-1倒序遍历,占用时x_shift减1 check_side_occupation(field, piece, piece_size - 1, -1, -1); break; } }
如果原有代码中其他地方还在调用check_left_side_occupation和check_right_side_occupation,可以保留这两个函数作为通用函数的简单包装:
void check_left_side_occupation(int (*field)[field_width], figure *piece) { check_side_occupation(field, piece, 0, 1, 1); } void check_right_side_occupation(int (*field)[field_width], figure *piece) { check_side_occupation(field, piece, piece_size - 1, -1, -1); }
重构逻辑说明
两个原函数的差异点被完全封装为三个参数:
start_x:x轴遍历的起始位置(左侧为0,右侧为piece_size-1)step_x:x轴遍历的步长(左侧为+1正序,右侧为-1倒序)shift_adjust:检测到占用时x_shift的调整量(左侧为+1,右侧为-1)
这种重构方式的优势:
- 消除了代码重复,所有核心检测逻辑只需要维护一处
- 后续如果需要修改检测规则(比如调整判断条件、修改偏移逻辑),无需同时修改两个函数,降低出错概率
- 保留了原有函数的调用逻辑,不会影响其他依赖代码
内容的提问来源于stack exchange,提问作者Fyodor
相关产品推荐
相关产品推荐

