编程绘制小球的动态碰撞轨迹。在屏幕的同一水平线上(设备坐标系)有两个小球,当第一个小球撞击另一个小球后,前者静止,后者将沿前一个小球的运动方向继续运动。
//程序名称:printf()动画—运动的小球
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<conio.h>
//定义延时时间,运动区的宽度和高度
#define DELAY 100
#define WIDTH 80
#define HEIGHT 24
//定义全局变量,位置和速度
int X1 = 0, Y1 =10,X2=40,Y2=10;
int Vx1 = 1, Vy1 = 0,Vx2=1,Vy2=0;
int t,i=0;
//函数声明
void Ball();
void HideCursor();
void GotoXy(int x, int y);
int main(void)
{
//接收键盘数据的变量
char ch = '\0';
system("color 2C");
system("title 运动的小球-动量守恒");
//隐藏光标
HideCursor();
//ESC退出
while(ch != 27)
{
Ball();
if(kbhit())
ch = getch();
}
system("cls");
//结束程序
return 0;
}
//计算球的轨迹
void Ball()
{
//画球
GotoXy(X1, Y1);
printf("●");
GotoXy(X2,Y2);
printf("●");
//延时
Sleep(DELAY);
//擦球
GotoXy(X1, Y1);
printf(" ");
GotoXy(X2,Y2);
printf("");
//触界反弹
if(0==X1&&Vx1<0)
{putchar('\007');
}
if((WIDTH - 2) == X2 && Vx2 > 0)
{Vx2 *= -1;
putchar('\007');}
if(X1=X2-2)
{t=Vx1;
Vx1=Vx2;
Vx2=t;
i*=-1;
putchar('\007');
}
//计算下一个周期的位置
switch(i)
{
case 1:
X1 += 2 * Vx1;break;
case -1:
X2 += 2 * Vx2;break;
}
}
//隐藏光标,头文件<windows.h>
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = {1, 0}; //后边的0代表光标不可见
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),
&cursor_info);
}
//光标移动,头文件<windows.h>
void GotoXy(int x, int y)
{
HANDLE hout; //定义句柄变量hout
COORD coord; //定义结构体coord
coord.X = x;
coord.Y = y;
hout = GetStdHandle(STD_OUTPUT_HANDLE); //获得标准输出(屏幕)句柄
SetConsoleCursorPosition(hout, coord); //移动光标
}