以下是使用C语言实现简单弹跳小球的代码:
#include#include #include #define WIDTH 70 #define HEIGHT 20 void gotoxy(int x, int y) { COORD pos; HANDLE hOutput; pos.X = x; pos.Y = y; hOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput, pos); } int main() { int x = WIDTH / 2; // 小球的初始X坐标 int y = HEIGHT / 2; // 小球的初始Y坐标 int dx = 1; // 小球在X轴上的移动速度 int dy = 1; // 小球在Y轴上的移动速度 while (1) { // 清屏 system("cls"); // 移动小球 x += dx; y += dy; // 检测小球是否碰到边界 if (x <= 0 || x >= WIDTH) { dx = -dx; // 改变小球在X轴上的移动方向 } if (y <= 0 || y >= HEIGHT) { dy = -dy; // 改变小球在Y轴上的移动方向 } // 输出小球 gotoxy(x, y); printf("O"); // 延时 Sleep(50); } return 0; }
在Windows下运行此程序,会显示一个小球在命令行窗口中上下左右移动的效果。