用C语言写个会动的爱心
时间: 2023-07-04 13:11:02 浏览: 58
这里是用C语言和图形库graphics.h实现一个简单的会动的爱心的示例代码。具体实现方式如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <math.h>
#include <time.h>
// 设置窗口大小
#define W 800
#define H 600
// 设置心形大小
#define a 150
#define b 150
// 设置步长
#define delta 0.01
// 画出一个点
void drawPoint(int x, int y, int color)
{
setcolor(color);
putpixel(x, y, color);
}
// 画出一个心形
void drawHeart()
{
int x, y;
double theta;
for (theta = 0.0; theta <= 2 * M_PI; theta += delta) {
x = a * pow(sin(theta), 3) + W / 2;
y = b * pow(cos(theta), 3) + H / 2;
drawPoint(x, y, RED);
}
}
// 主函数
int main()
{
int gd = DETECT, gm, color;
initgraph(&gd, &gm, NULL);
setbkcolor(BLACK);
cleardevice();
drawHeart();
int x = W / 2, y = H / 2;
int dx = 2, dy = 2;
while (1) {
x += dx;
y += dy;
if (x > W || x < 0) {
dx = -dx;
}
if (y > H || y < 0) {
dy = -dy;
}
cleardevice();
drawHeart();
setcolor(YELLOW);
settextstyle(3, 0, 6);
outtextxy(W / 2 - 100, 50, "Happy Valentine's Day!");
setcolor(WHITE);
settextstyle(3, 0, 2);
outtextxy(W / 2 - 60, H - 50, "by AI Assistant");
setcolor(GREEN);
settextstyle(3, 0, 2);
outtextxy(W / 2 - 100, H - 20, "Press any key to exit...");
setcolor(RED);
setfillstyle(SOLID_FILL, RED);
fillellipse(x, y, 20, 20);
delay(50);
if (kbhit()) {
break;
}
}
closegraph();
return 0;
}
```
运行上述代码后,会显示出一个会动的爱心,爱心会在窗口中上下左右移动,同时还有一些文字和一个跳动的小圆点。按任意键退出程序。