如何修改使用 SFML 绘制垂直线的函数以自动将它们隔开?

问题描述 投票:0回答:1

我正在使用 SFML 开发一个排序算法可视化项目。我创建了一个由

sf::RectangleShape 
对象组成的向量,表示要排序的垂直线。

std::vector <sf::RectangleShape> lineVector;
int xpos = 100;

int N;
std::cout << "Enter the size of the vector to be sorted: ";
std::cin >> N;

srand(time(0));

for (int i = 1; i <= N; i++) {
    int randomNum = rand() % N + 1;
    sf::RectangleShape line = plot(randomNum, xpos, 200);
    lineVector.push_back(line);
    xpos += 5;
}

我使用

rand
生成从 1 到 N 的随机数,
randomNum
,因此每条线都有一个随机高度,使用
plot()
辅助函数(位于其自己的 .h 文件中,请参阅如下),然后将其附加到未排序的
lineVector

sf::RectangleShape plot(int height, int x, int y) { //Returns a single drawn line
    sf::RectangleShape line(sf::Vector2f(height, 1));
    line.setPosition(x, y - height);
    line.rotate(90);
    
    return line;
}

我的目标是修改

plot
以自行在行之间插入空格,而不需要使用
xpos
进行硬编码和更新行的位置。

plot
接受三个参数; a
height
表示线条的长度(在输入时听起来应该将其更改为长度),以及它在窗口内的
x
y
坐标。最初,我尝试使用
int space
变量作为第四个参数,该变量作为偏移量添加到
x
位置。另外,我在 main.cpp 中尝试了一个
const int space
变量,但没有成功。

c++ sfml
1个回答
0
投票

一种选择是将绘图函数传递给 lineVector,然后让它将新线定位在 lineVector.size() * 5 处。或者你可以只传递它 lineVector.size() 并将其定位在当时的位置 5。 ...

sf::RectangleShape plot(int height, std::vector<sf::RectangleShape> lines, int y) { //Returns a single drawn line
    sf::RectangleShape line(sf::Vector2f(height, 1));
    line.setPosition(lines.size() * 5, y - height);
    line.rotate(90);
    
    return line;
}

然后

std::vector <sf::RectangleShape> lineVector;

int N;
std::cout << "Enter the size of the vector to be sorted: ";
std::cin >> N;

srand(time(0));

for (int i = 1; i <= N; i++) {
    int randomNum = rand() % N + 1;
    sf::RectangleShape line = plot(randomNum, lineVector, 200);
    lineVector.push_back(line);
}

为了进一步简化您的代码,您可以使绘图函数自动将新行添加到 lineVector...

void plot(int height, std::vector<sf::RectangleShape>& lines, int y) { 
    sf::RectangleShape line(sf::Vector2f(height, 1));
    line.setPosition(lines.size() * 5, y - height);
    line.rotate(90);
    
    lines.push_back(line);
}

然后...

std::vector <sf::RectangleShape> lineVector;

int N;
std::cout << "Enter the size of the vector to be sorted: ";
std::cin >> N;

srand(time(0));

for (int i = 1; i <= N; i++) {
    int randomNum = rand() % N + 1;
    sf::RectangleShape line = plot(randomNum, lineVector, 200);
}
© www.soinside.com 2019 - 2024. All rights reserved.