如何减慢可视化算法

问题描述

我正在使用 C++ 在 SFML 中创建一个排序可视化应用程序。 我遇到了排序循环延迟的问题。 我制作了两个“按钮”,一个用于排序,另一个用于在向量中混洗数据,一切正常,我只是无法延迟工作,我试图将 sf::Time 与 sf::Clock 和sf::sleep,两者都失败了。

更新循环(这里添加了计时器,所以用户不能每秒点击 100 次,这真的不是一个很酷的应用程序,它只是为了简单的可视化)

void App::update() {


this->pollEvents();
this->updateMousePos();
this->shuffleButton->update(this->mousePosView);
if (shuffleButton->ispressed()) {
    this->time = this->clock.getelapsedtime();
    if (time.asSeconds() >= 0.5) {
        this->shuffle();
        clock.restart();
    }
}
this->bubbleSortButton->update(this->mousePosView);
if (bubbleSortButton->ispressed()) {
    this->time = this->clock.getelapsedtime();
    if (time.asSeconds() >= 0.5) {
        this->bubbleSort();
        clock.restart();
    }
  }
}

和排序算法(条形以正确的方式排序,可视化效果很好,显然它太快了)

void App::bubbleSort(){
int size = this->bars.size();
do {
    for (size_t i = 0; i < size - 1; i++) {
        if (this->bars[i].getGlobalBounds().height > this->bars[i + 1].getGlobalBounds().height) {
                int x = this->bars[i].getPosition().x;
                int xS = this->bars[i + 1].getPosition().x;
                this->bars[i].setPosition(xS,700);
                this->bars[i + 1].setPosition(x,700);
                std::swap(this->bars[i],this->bars[i + 1]);
        }
    }
    --size;
  } while (size > 1);
}

我以前从未在 SFML 中要求过解决方案,因此如果没有提供足够的代码,我深表歉意,我期待添加您需要的任何内容

解决方法

您忘记在按下按钮后将时间重置为零。

if (shuffleButton->isPressed()) {
    this->time = this->clock.getElapsedTime();

    if (time.asSeconds() >= 0.5) {
        this->shuffle();
        clock.restart();
        time = 0; 
    }
}

另外,正如另一位用户所指出的,理想情况下,您应该逐步解决,并让算法在每个循环中暂停,如下所示:

sf::Time time = sf::milliseconds(sleepForInMiliseconds);
sf::sleep(time);

其中 sleepForInMiliseconds 是您首选的步进延迟的整数。有趣的是,我正在从事完全相同的项目,因此我也可以帮助解决任何其他问题。