求一个c++绘制风车的类,要求使用Graphics库
时间: 2024-02-25 15:55:33 浏览: 91
好的,以下是一个简单的使用Graphics库绘制风车的C++类:
```c++
#include <graphics.h>
class Windmill {
public:
Windmill(int x, int y, int size, int speed) :
m_x(x), m_y(y), m_size(size), m_speed(speed)
{}
void draw() {
setcolor(YELLOW);
circle(m_x, m_y, m_size); // 绘制风车的圆心
// 绘制风车的四个叶片
int x1 = m_x - m_size / 2, y1 = m_y;
int x2 = m_x + m_size / 2, y2 = m_y;
int x3 = m_x, y3 = m_y - m_size / 2;
int x4 = m_x, y4 = m_y + m_size / 2;
setfillstyle(SOLID_FILL, RED);
fillellipse(x1, y1, m_size / 4, m_size / 2);
fillellipse(x2, y2, m_size / 4, m_size / 2);
fillellipse(x3, y3, m_size / 2, m_size / 4);
fillellipse(x4, y4, m_size / 2, m_size / 4);
}
void rotate() {
// 旋转叶片
int x1 = m_x - m_size / 2, y1 = m_y;
int x2 = m_x + m_size / 2, y2 = m_y;
int x3 = m_x, y3 = m_y - m_size / 2;
int x4 = m_x, y4 = m_y + m_size / 2;
setfillstyle(SOLID_FILL, BLACK);
fillellipse(x1, y1, m_size / 4, m_size / 2);
fillellipse(x2, y2, m_size / 4, m_size / 2);
fillellipse(x3, y3, m_size / 2, m_size / 4);
fillellipse(x4, y4, m_size / 2, m_size / 4);
// 更新角度
m_angle += m_speed;
if (m_angle >= 360) m_angle -= 360;
// 旋转坐标
int x1_new = m_x + (x1 - m_x) * cos(m_angle * PI / 180) - (y1 - m_y) * sin(m_angle * PI / 180);
int y1_new = m_y + (x1 - m_x) * sin(m_angle * PI / 180) + (y1 - m_y) * cos(m_angle * PI / 180);
int x2_new = m_x + (x2 - m_x) * cos(m_angle * PI / 180) - (y2 - m_y) * sin(m_angle * PI / 180);
int y2_new = m_y + (x2 - m_x) * sin(m_angle * PI / 180) + (y2 - m_y) * cos(m_angle * PI / 180);
int x3_new = m_x + (x3 - m_x) * cos(m_angle * PI / 180) - (y3 - m_y) * sin(m_angle * PI / 180);
int y3_new = m_y + (x3 - m_x) * sin(m_angle * PI / 180) + (y3 - m_y) * cos(m_angle * PI / 180);
int x4_new = m_x + (x4 - m_x) * cos(m_angle * PI / 180) - (y4 - m_y) * sin(m_angle * PI / 180);
int y4_new = m_y + (x4 - m_x) * sin(m_angle * PI / 180) + (y4 - m_y) * cos(m_angle * PI / 180);
// 绘制旋转后的叶片
setfillstyle(SOLID_FILL, RED);
fillellipse(x1_new, y1_new, m_size / 4, m_size / 2);
fillellipse(x2_new, y2_new, m_size / 4, m_size / 2);
fillellipse(x3_new, y3_new, m_size / 2, m_size / 4);
fillellipse(x4_new, y4_new, m_size / 2, m_size / 4);
}
private:
int m_x; // 风车的圆心x坐标
int m_y; // 风车的圆心y坐标
int m_size; // 风车的大小
int m_speed; // 风车的旋转速度
int m_angle = 0; // 风车叶片的旋转角度,初始为0度
};
```
使用示例:
```c++
int main() {
initwindow(640, 480, "Windmill");
Windmill windmill(320, 240, 100, 5);
while (true) {
windmill.rotate();
delay(50);
}
closegraph();
return 0;
}
```
这个类会在窗口中绘制一个风车,不断旋转风车的叶片。你可以根据需要调整风车的大小和旋转速度。请注意,在使用Graphics库时,需要在程序中调用`initwindow`和`closegraph`函数来初始化和关闭窗口。
阅读全文