画面来源于 EasyX的官网,但那个朋友写的代码看不懂(现在不知道能不能看懂. . .)所以我就自己写了一下,结果代码量比它的要少很多 . . .
这个程序是去年刚开学的时候写的,效率可能会低那么一点,因为当时就会 C 和 EasyX,还有略懂一点 C++,希望您喜欢 ^ _ ^
我们可以准备一首好听的音乐,效果如下所示(gif文件播放不了音乐):
代码如下所示:
#include <graphics.h>
#include <ctime>
#include <cstdlib>
#include <mmsystem.h>
#pragma comment(lib,"winmm")
class Ob_Fam
{
struct coord_ch
{
int x;
int y;
int sj;
};
struct Coord
{
int x;
int y;
coord_ch ch[12];
};
static const int RAIN_NUM = 500;
Coord rain[RAIN_NUM];
static const int WIDTH = 640;
static const int HEIGHT = 480;
static const int WID = 120; //房子的宽度 相同宽度 便于计算
static const int HOUSE_NUM = 30;
Coord house[HOUSE_NUM];
public:
void InitGra();
Ob_Fam() {}
~Ob_Fam() {}
void RunDownRain(); //开始 下雨
void DrawHouse();
};
int main()
{
DWORD t1 = timeGetTime(), tt1;
DWORD t2 = timeGetTime(), tt2;
srand((unsigned)time(nullptr));
Ob_Fam myFam;
myFam.InitGra();
while (1)
{
BeginBatchDraw();
tt1 = timeGetTime();
if (tt1 - t1 > 20) //下雨
{
myFam.RunDownRain();
t1 = tt1;
}
tt2 = timeGetTime();
if (tt2 - t2 > 40)
{
cleardevice();
myFam.DrawHouse();
t2 = tt2;
}
EndBatchDraw();
}
return 0;
}
void Ob_Fam::InitGra()
{
initgraph(WIDTH, HEIGHT);
setbkcolor(RGB(75, 75, 75));
cleardevice();
mciSendString("play bj.mp3 repeat", 0, 0, 0);
for (int i = 0; i < RAIN_NUM; i++)
{
rain[i].x = rand() % (WIDTH + 400) - 200;
rain[i].y = rand() % HEIGHT;
}
for (int i = 0; i < HOUSE_NUM; i++)
{
house[i].x = rand() % (WIDTH - WID);
house[i].y = rand() % 250 + 200;
for (int j = 0; j < 12; j++)
{
house[i].ch[j].x = house[i].x + 10 + (j % 2) * 55;
house[i].ch[j].y = house[i].y + 10 + (j / 2) * 55;
house[i].ch[j].sj = rand() % 12;
}
}
setlinecolor(RGB(50, 50, 50));
}
void Ob_Fam::RunDownRain()
{
for (int i = 0; i < RAIN_NUM; i++)
{
putpixel(rain[i].x, rain[i].y, WHITE);
rain[i].x += 2;
rain[i].y += 4;
if (rain[i].y > HEIGHT)
{
rain[i].x = rand() % (WIDTH + 400) - 200;
rain[i].y = -10;
}
}
}
void Ob_Fam::DrawHouse()
{
for (int i = 0; i < HOUSE_NUM; i++)
{
setfillcolor(RGB(40, 40, 40));
fillrectangle(house[i].x, house[i].y, house[i].x + WID, HEIGHT);
house[i].x -= 5;
for (int j = 0; j < 12; j++)
{
setfillcolor(RGB(50, 50, 50));
if (house[i].ch[j].sj > 6)
{
if (house[i].ch[j].sj > 9)
setfillcolor(RGB(255, 255, 220));
else
setfillcolor(YELLOW);
}
fillrectangle(house[i].ch[j].x, house[i].ch[j].y, house[i].ch[j].x + 45, house[i].ch[j].y + 45);
house[i].ch[j].x -= 5;
}
if (house[i].x < -WID)
{
house[i].x = WIDTH + rand() % 100;
house[i].y = rand() % 250 + 200;
for (int j = 0; j < 12; j++)
{
house[i].ch[j].x = house[i].x + 10 + (j % 2) * 55;
house[i].ch[j].y = house[i].y + 10 + (j / 2) * 55;
house[i].ch[j].sj = rand() % 12;
}
}
}
}