有一小球在一矩形框内的任意位置,初始时以随机角度,随机速度往下掉落,每次碰到边框时以随机角度,随机速度继续运行,按ESC键结束。编写程序模拟小球的运动过程。
#include <conio.h>//要用到_kbhit()函数
#include <time.h>//要用到随机数
#include <graphics.h>
int get_randx();//实现随机出现
int get_randy();
int get_kx();//1~6随机取一个
int get_ky();
int main()
{
initgraph(800, 800);
setbkcolor(RGB(150, 150, 90));
cleardevice();
int x = get_randx();
int y = get_randy();
int kx = get_kx();
int ky = get_ky();
while (!(_kbhit() && _getch() == 27))
{
if ((x + kx + 20) >= 800)//四个边界检测,若达到边界,进行回弹并赋予随机速度
{
kx = -(get_kx());
x += kx;
}
else if ((x + kx - 20) <= 0)
{
kx = get_kx();
x += kx;
}
if (y + ky + 20 >= 800)
{
ky = -(get_ky());
y += ky;
}
else if ((y + ky - 20) <= 0)
{
ky = get_ky();
y += ky;
}
setcolor(RGB(50, 80, 80));//图像刷新
setfillcolor(RGB(50, 80, 80));
fillcircle(x, y, 20);
Sleep(20);
setcolor(RGB(150, 150, 90));
setfillcolor(RGB(150, 150, 90));
fillcircle(x, y, 20);
x += kx;
y += ky;
}
closegraph();
return 0;
}
int get_randx()
{
srand((unsigned)time(NULL) * (unsigned)rand());
return rand() % 800;
}
int get_randy()
{
srand((unsigned)time(NULL) + (unsigned)rand());
return rand() % 800;
}
int get_kx()
{
srand((unsigned)time(NULL) + (unsigned)rand());
int k = rand() % 6;
while (k == 0)
k = rand() % 6;
return k;
}
int get_ky()
{
srand((unsigned)time(NULL) + (unsigned)rand());
int k = rand() % 6;
while (k == 0)
k = rand() % 6;
return k;
}
看懂的掌声?