cpp使用graphics绘制指定数量的随机位置的矩形
时间: 2024-02-05 15:12:30 浏览: 24
使用graphics库绘制随机位置的矩形,可以按照以下步骤进行:
1. 引入graphics库,并初始化窗口
```cpp
#include <graphics.h>
#include <stdlib.h>
#include <time.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
srand(time(NULL)); // 设置随机种子
// ...
closegraph();
return 0;
}
```
2. 定义变量存储矩形数量和窗口大小
```cpp
int rect_num = 20; // 矩形数量
int win_width = getmaxx(); // 窗口宽度
int win_height = getmaxy(); // 窗口高度
```
3. 循环绘制随机位置的矩形
```cpp
for (int i = 0; i < rect_num; i++) {
int x = rand() % win_width; // 随机生成矩形左上角x坐标
int y = rand() % win_height; // 随机生成矩形左上角y坐标
int w = rand() % 50 + 10; // 随机生成矩形宽度
int h = rand() % 50 + 10; // 随机生成矩形高度
setfillstyle(rand() % 13 + 1, rand() % 15 + 1); // 随机设置矩形填充颜色和边框颜色
bar(x, y, x + w, y + h); // 绘制矩形
}
```
完整代码如下:
```cpp
#include <graphics.h>
#include <stdlib.h>
#include <time.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
srand(time(NULL)); // 设置随机种子
int rect_num = 20; // 矩形数量
int win_width = getmaxx(); // 窗口宽度
int win_height = getmaxy(); // 窗口高度
for (int i = 0; i < rect_num; i++) {
int x = rand() % win_width; // 随机生成矩形左上角x坐标
int y = rand() % win_height; // 随机生成矩形左上角y坐标
int w = rand() % 50 + 10; // 随机生成矩形宽度
int h = rand() % 50 + 10; // 随机生成矩形高度
setfillstyle(rand() % 13 + 1, rand() % 15 + 1); // 随机设置矩形填充颜色和边框颜色
bar(x, y, x + w, y + h); // 绘制矩形
}
getch(); // 等待用户按键
closegraph();
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)