实现效果如图:
1、星空
2、下雪
代码如下:
-1-星空
#include<graphics.h>
#include<time.h>
#include<conio.h>
#define MAXSTAR 800 //星星最大值
#define WIDTH 640 //图表宽度
#define HEIGHT 480 //图表高度
//星星封装结构体
struct STAR
{
int x, y;
double step;//用于星星移动速度
int color;
};
STAR star[MAXSTAR];
//星星初始化
void InitStart(int i)
{
star[i].x = 0;
star[i].y = rand() % HEIGHT;
star[i].step = (rand()% 5000) / 1000.0 + 1;
star[i].color = (int)(star[i].step * 255 / 6.0 + 0.5);//速度越快,星星越亮
star[i].color = RGB(star[i].color, star[i].color, star[i].color);
}
//星星移动
void MoveStar(int i)
{
putpixel(star[i].x, star[i].y, 0);
star[i].x += star[i].step;
if (star[i].x >= WIDTH)
InitStart(i);
putpixel(star[i].x, star[i].y, star[i].color);
}
int main(void)
{
srand((unsigned)time(NULL));//播种随机种子
initgraph(WIDTH, HEIGHT);//初始化图形
for (int i = 0; i < MAXSTAR; i++)//遍历初始全部星星
{
InitStart(i);
star[i].x = rand() % WIDTH;
}
//星星移动
while (!_kbhit())//按任意键退出
{
for (int i = 0; i < MAXSTAR; i++)
MoveStar(i);
Sleep(20);
}
system("pause");
closegraph();
return 0;
}
-2-下雪
#include<graphics.h>
#include<conio.h>
#include<time.h>
#define MAXSNOW 500
#define WIDTH 840
#define HEIGHT 620
struct SNOW
{
int x, y;
char color;
};
SNOW snow[MAXSNOW];
void initSNOW(int i)
{
snow[i].x = rand() % WIDTH;
snow[i].y = 0;
snow[i].color = RGB(225, 225, 225);
}
void moveSNOW(int i)
{
putpixel(snow[i].x, snow[i].y, 0);
snow[i].y += rand() % 10;
if (snow[i].y > HEIGHT)
initSNOW(i);
putpixel(snow[i].x, snow[i].y, WHITE);
}
int main(void)
{
srand((unsigned)time(NULL));
initgraph(WIDTH, HEIGHT);
for (int i = 0; i < MAXSNOW; i++)
{
initSNOW(i);
snow[i].y = rand() % HEIGHT;
}
while (!_kbhit())
{
for (int i = 0; i < MAXSNOW; i++)
{
moveSNOW(i);
}
Sleep(20);
}
system("pause");
closegraph();
return 0;
}