接下来是尽力过重大重构的用户界面函数组。
首先笔者分离出了一批功能绘图函数,如下:
misc.cpp
void paintBlackRect(Rect rect)
{
for(int j = rect.upperLeft.y; j <= rect.lowerRight.y; j++) {
for(int i = rect.upperLeft.x; i <= rect.lowerRight.x; i++) {
putchar_ex(Coord(i, j), BLACK_BACK_BLACK_CHAR, ' ');
}
}
return;
}
void paintHorizontalStick(int start_x, int y, int length)
{
for(int i = 0; i < length; i++) {
putchar_ex(Coord(start_x+i, y), BLACK_BACK_WHITE_CHAR, STICK_HORI);
}
return;
}
void paintVerticalStick(int x, int start_y, int length)
{
for(int i = 0; i < length; i++) {
putchar_ex(Coord(x, start_y+i), BLACK_BACK_WHITE_CHAR, STICK_VERT);
}
return;
}
void paintBox(Rect rect)
{
putchar_ex(Coord(rect.upperLeft.x, rect.upperLeft.y), BLACK_BACK_WHITE_CHAR, UPPER_LEFT);
putchar_ex(Coord(rect.lowerRight.x, rect.upperLeft.y), BLACK_BACK_WHITE_CHAR, UPPER_RIGHT);
putchar_ex(Coord(rect.upperLeft.x, rect.lowerRight.y), BLACK_BACK_WHITE_CHAR, LOWER_LEFT);
putchar_ex(Coord(rect.lowerRight.x, rect.lowerRight.y), BLACK_BACK_WHITE_CHAR, LOWER_RIGHT);
paintHorizontalStick(rect.upperLeft.x+1, rect.upperLeft.y, (rect.lowerRight.x-rect.upperLeft.x)-1);
paintHorizontalStick(rect.upperLeft.x+1, rect.lowerRight.y, (rect.lowerRight.x-rect.upperLeft.x)-1);
paintVerticalStick(rect.upperLeft.x, rect.upperLeft.y+1, (rect.lowerRight.y-rect.upperLeft.y)-1);
paintVerticalStick(rect.lowerRight.x, rect.upperLeft.y+1, (rect.lowerRight.y-rect.upperLeft.y)-1);
return;
}
paintBlackRect
函数将指定矩形范围绘制为黑色,paintHorizontalStick
函数绘制横线,paintVerticalStick
函数绘制竖线, paintBox
函数绘制指定大小和位置的矩形。
Rect
是矩形类,它定义在 coord.h中:
coord.h (节选)
class Rect {
public:
Rect(void)
{
upperLeft = Coord(0, 0);
lowerRight = Coord(0, 0);
}
Rect(Coord _upperLeft, Coord _lowerRight)
{
int upperLeft_x = std::min(_upperLeft.x, _lowerRight.x);
int upperLeft_y = std::min(_upperLeft.y, _lowerRight.y);
int lowerRight_x = std::max(_upperLeft.x, _lowerRight.x);
int lowerRight_y = std::max(_upperLeft.y, _lowerRight.y);
upperLeft = Coord(upperLeft_x, upperLeft_y);
lowerRight = Coord(lowerRight_x, lowerRight_y);
}
Coord upperLeft, lowerRight;
};
通过构造函数中的处理,确保了左上角坐标和右下角坐标不会混乱。