需要帮助创建打字速度游戏与时间

时间:2017-03-23 10:43:48

标签: c++

所以我对C ++很陌生,我正在为学校制作游戏,你必须在一段时间之前输入一个单词,而你只有3个生命。在这种情况下,4秒。我在制作计时器时遇到问题,并在输入正确答案时停止计时器。这就是我现在所拥有的:

string wordsOne [10];    
int life = 3;
int duration;

reset2:
duration = 0;

cout << "Type 'HACK'\n";

while (wordsOne[0] != "hack") {
    sleep(1);
    ++duration;

    if (duration == 4) {
        --life;
        cout << "You have " << life << " lives left!\n";

        if (life >= 1) {
            sleep(1);
            goto reset2;
        }

        else if (life < 1) {
            lost();
        }
    }
}

getline (cin, wordsOne[0]);

if (wordsOne[0] == "hack") {
    cout << "SUCCESS\n";
}

我知道我知道,我不应该使用goto,但这是我能想到的最简单的事情。感谢。

1 个答案:

答案 0 :(得分:0)

您尝试的问题是您将计时器运行完成,然后然后尝试输入值。如果你使用线程,你只能将这样的程序逻辑分开,我希望你不要在意我强调你 尚未准备好进行线程化。

好消息:它比这更简单。您只需在输入前加上时间戳,然后再加上时间戳。然后你可以计算出已经过了多少时间。不需要让它变得复杂。

下面的代码演示了这一点,但并未直接解决您的问题。程序逻辑的其余部分取决于你。

#include <iostream>
#include <chrono>

int main()
{
    const std::string target = "hack";
    const std::chrono::milliseconds time_limit( 4000 );

    std::cout << "Type '" << target << "' - you can't lose" << std::endl;
    std::string input;

    auto time_begin = std::chrono::steady_clock::now();
    getline( std::cin, input );
    auto time_end = std::chrono::steady_clock::now();

    auto elapsed_milli = std::chrono::duration_cast<std::chrono::milliseconds>(
        time_end - time_begin );

    if( input == target && elapsed_milli <= time_limit )
    {
        std::cout << "u winnar" << std::endl;
    }
    return 0;
}