1
\$\begingroup\$

I'm trying to make a game using C++ (in Visual Studio 2015). I want to make the game run for X minutes and then end. I have a function play() that calls all other functions required and I need to make play() run for 2min. I've tried putting play() in loops that run for some time, but none of them work. I am not able to find any other question that addresses the problem I'm facing and so any help would be appreciated.

| improve this question | | | | |
\$\endgroup\$
  • \$\begingroup\$ Could you show us what's in play() and how it is called? \$\endgroup\$ – Vaillancourt Nov 14 '17 at 2:31
  • 1
    \$\begingroup\$ It's also helpful, when describing attempts that didn't work, to specify in what particular way they didn't work. Compiler errors, never stopping the game at all, stopping the game too early / too late, re-starting the game instead of stopping it, preventing the game from running normally, crashing the game/computer, catching fire... all of these are possible failure modes, and each one tells a different story about what might be going wrong. ;) \$\endgroup\$ – DMGregory Nov 14 '17 at 2:39
2
\$\begingroup\$

If you record the time once at the start of your game:

time_t startTimeSeconds = time(NULL); // must include 'ctime'

Every update (game loop iteration) you can check to see if the elapsed time has exceeded two minutes:

if (time(NULL) - startTimeSeconds >= 120) // two minutes
    stopGame();
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ In case the time function does not give enough precision, consider using QueryPerformanceCounter. Follow this link for a nice example. \$\endgroup\$ – Bert Nov 14 '17 at 7:15
0
\$\begingroup\$

Your play() function not necessary should not be executed in the loop. Instead, you can use this function, to loop your game. Here is some minimal example, how you can use it:

#include <chrono>

void play()
{
    // record the time, as soon you entered the function
    auto startTime = std::chrono::system_clock::now(); 

    while(!isGameOver())
    {
        // here you can paste your time consuming game logic
        //  i.e. function calls

        auto endTime = std::chrono::system_clock::now();
        // check, if two minutes are over
        if (endTime - startTime > std::chrono::minutes(2))
            gameOver(); /* in this function paste your 'end of the game'-logic */ 
    }
}

The main advantage in using std::chrono instead of ctime is that your time-checking calls are less cryptic, therefore better understandable, especially in initialization part.

Compare auto time = std::chrono::system_clock::now() and time_t startTimeSeconds = time(NULL);

| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.