Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for input for a certain time

Tags:

c++

c

windows

Is there any function that can wait for input until a certain time is reached? I'm making kind of Snake game.

My platform is Windows.

like image 729
Xuicide Avatar asked Oct 05 '22 10:10

Xuicide


2 Answers

For terminal based games you should take a look at ncurses.

 int ch;
 nodelay(stdscr, TRUE);
 for (;;) {
      if ((ch = getch()) == ERR) {
          /* user hasn't responded
           ...
          */
      }
      else {
          /* user has pressed a key ch
           ...
          */
      }
 }

Edit:

See also Is ncurses available for windows?

like image 103
Klas Lindbäck Avatar answered Oct 14 '22 07:10

Klas Lindbäck


I found a solution using kbhit() function of conio.h as follows :-

    int waitSecond =10; /// number of second to wait for user input.
    while(1)
    {

     if(kbhit()) 
      {
       char c=getch();
       break;
      }

     sleep(1000); sleep for 1 sec ;
     --waitSecond;

     if(waitSecond==0)   // wait complete.
     break;  
    }
like image 1
birubisht Avatar answered Oct 14 '22 05:10

birubisht