Search code examples
c++windows-7timercountdown

C++ Game countdown timer


I would like to ask how can I make a console game when I need the user to input some string within a period of time? (I've tried to use Sleep function but it will make the screen freeze for a period of time which I don't want to)

Example : A Pop Quiz


Solution

  • I think this can be done without multithreading (A very simple version of a timer)

    You can try to write something like this and modify it to serve your needs:

    Please note that the code is not complete. You need to edit it so it match your needs. However, this should give you an idea.

    int main() 
    {   
       time_t begin, end;
       char input;
       bool flag = true;
       begin = time();
       while (flag) 
       {
          if(kbhit()) 
             ch = getch();
          end = time();
          if(difftime(end, begin) > NEEDED_TIME_IN_SECONDS) 
            flag = false;  //The user didn't enter it in within the wanted period of time
        }
    }
    

    Some documentations:

    • double difftime(time_t time2, time_t time1) Return difference between two times Calculates the difference in seconds between time1 and time2.
    • getch() Prompts the user to press a character and that character is not printed on screen.
    • kbhit() It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed.