简体   繁体   中英

I can't make my function calculate how much time has passed and print stuff accordingly

bool IsGameEnded()
{
    static int i = 0;

    i++;
    if (i == 10)
        return true;
    return false;
}

int main()
{

   bool GameEnd = false;
   
   float ElapsedTime = 0;
   while(!GameEnd)
   {
       chrono::steady_clock::time_point StartingTime = chrono::steady_clock::now();

       

       if (ElapsedTime > 10)
       {
           ElapsedTime = 0;
           draw();
       }

       GameEnd = IsGameEnded();
      
       chrono::steady_clock::time_point EndingTime = chrono::steady_clock::now();
       ElapsedTime = ElapsedTime + chrono::duration_cast<chrono::milliseconds>(EndingTime - StartingTime).count();
   }

   return 0;
}

I wan't to make a snake game. It will be based on time. For example screen will update every 5 seconds or so. For that I used chrono library. I am not used to this trying o learn it so I might have missed something obvious. But the problem is main function doesn't get get into the if block. So it draws nothing to the console.

I tried debugging (with running line by line). It is not actually like a running program becasue time intervals get long but it enters if block every time. Also if I make the if condition 2 nanoseconds it also works but since cout function can not print so fast I need it to be a lot longer than that. While Debugging I also realised that "StartingTime" and "EndingTime" variables don't get initiated (unless I directly stop on them). The interesting part is If ı add cout after if block, after a while program starts entering the If block.

When you do:

chrono::duration_cast<chrono::milliseconds>(EndingTime - StartingTime).count();

not enough time has passed, and the count of milliseconds always returns 0. This means you always add 0 to ElapsedTime and it never crosses 10.

One fix is to use a smaller resolution:

chrono::duration_cast<chrono::nanoseconds>(EndingTime - StartingTime).count();

as you mentioned in the question, and adjust the if condition appropriately.

However, the best fix would be to change ElapsedTime from a float to a chrono::duration (of the appropriate unit) since that is the unit that the variable represents. This would let you avoid having to do .count() on the duration as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM