#include#include #include #include typedef struct ball_attribute { int left = 30; int right = 100; int bottom = 30; int top = 10; //界面大小 int velocity_x = 1; int velocity_y = 1; //运行速度 unsigned int x = 40; unsigned int y = 20; //原始坐标 }BA; void scanball(BA ball); void print(int x, int y); void printboundary(BA ball); void color(const unsigned short textColor); void SetPosC(COORD a); void HideCursor(); void main() { BA ball{}; system("mode con cols=188 lines=47");//显示框大小 scanball(ball); HideCursor(); while (1) { print(ball.right / 2, ball.top - 4), color(6), printf(" 弹 弹 球"), print(0, 0), color(16); printboundary(ball); if ((ball.x == ball.right) || (ball.x == ball.left)) ball.velocity_x = -ball.velocity_x; if ((ball.y == ball.top) || (ball.y == ball.bottom)) ball.velocity_y = -ball.velocity_y; //if (ball.x == ball.right) ball.velocity_x = -ball.velocity_x; ball.x += ball.velocity_x; ball.y += ball.velocity_y; print(ball.x, ball.y), color(2), printf("●"), color(16);//绿色小球 Sleep(25); } } void scanball(BA ball) { unsigned int a, b, c, d; int bool_1 = 0, bool_2 = 0; printf("输入界面大小,top=?,bottom=?,left=?,right=?n"); scanf_s(" %d %d %d %d",&a,&b,&c,&d); ball.top = a, ball.bottom = b, ball.left = c, ball.right = d; int speed_x=0, speed_y=0; do { printf("输入速度大小,velocity_x=?,velocity_y=?n"); scanf_s(" %d %d", &speed_x, &speed_y); if (abs(speed_x) > 5 || abs(speed_y) > 5) { printf("设定速度过快n"); bool_1 = 1; } else { ball.velocity_x = speed_x, ball.velocity_y = speed_y; bool_1 = 0; } } while (bool_1); int x, y; do { printf("输入ball原始坐标,y=?,x=?n"); scanf_s(" %d %d", &y, &x); if (x >= ball.left && x<= ball.right && y >= ball.top && y <= ball.bottom) { ball.x = x, ball.y = y; bool_2 = 0; } else { printf("输入错误n"); bool_2 = 1; } } while (bool_2); } void printboundary(BA ball) {//长:30--150;宽:10--40 for (int y = 1; y <= ball.bottom + 1; y++) {//y轴:第1行--第41行 if (y == ball.top || y == ball.bottom + 1) { for (int x = 1; x <= ball.right + 1; x++) {//x轴:第1列--第151列 if (x >= ball.left + 2) color(5), printf("-"), color(16); else printf(" "); } } else if (y >= ball.top && y <= ball.bottom) { for (int x = 1; x <= ball.right + 2; x++) { if (x == ball.left + 1 || x == ball.right + 2) color(12), printf("|"), color(16); else printf(" "); } } printf("n"); } } void color(const unsigned short textColor) //自定义函根据参数改变颜色 { if (textColor >= 0 && textColor <= 15) //参数在0-15的范围颜色 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), textColor); //用一个参数,改变字体颜色 else //默认的字体颜色是白色 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7); } void SetPosC(COORD a) { // set cursor HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(out, a); } void print(int x, int y) { COORD pos = { x, y }; SetPosC(pos); } //定义隐藏光标函数 void HideCursor() { CONSOLE_CURSOR_INFO cursor; cursor.bVisible = FALSE; cursor.dwSize = sizeof(cursor); HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorInfo(handle, &cursor); }



