Xuicide
Xuicide

Reputation: 105

Wait for input for a certain time

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.

Upvotes: 5

Views: 8256

Answers (4)

jave.web
jave.web

Reputation: 15032

Based on @birubisht answer I made a function which is a bit cleaner and uses NON-deprecated versions of kbhit() and getch() - ISO C++'s _kbhit() and _getch().
Function takes: number of seconds to wait for user input
Function returns: _ when user does not put any char, otherwise it returns the inputed char.

/**
  * Gets: number of seconds to wait for user input
  * Returns: '_' if there was no input, otherwise returns the char inputed
**/
char waitForCharInput( int seconds ){
    char c = '_'; //default return
    while( seconds != 0 ) {
        if( _kbhit() ) { //if there is a key in keyboard buffer
            c = _getch(); //get the char
            break; //we got char! No need to wait anymore...
        }

        Sleep(1000); //one second sleep
        --seconds; //countdown a second
    }
    return c;
}

Upvotes: 0

birubisht
birubisht

Reputation: 908

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;  
    }

Upvotes: 1

Rajesh
Rajesh

Reputation: 182

Try with bioskey(), this is an example for that:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <ctype.h>

#define F1_Key 0x3b00
#define F2_Key 0x3c00

int handle_keyevents(){
   int key = bioskey(0);
   if (isalnum(key & 0xFF)){
      printf("'%c' key pressed\n", key);
      return 0;
   }

   switch(key){
      case F1_Key:
         printf("F1 Key Pressed");
         break;
      case F2_Key:
         printf("F2 Key Pressed");
         break;
      default:
         printf("%#02x\n", key);
         break;
   }
   printf("\n");
   return 0;
}


void main(){
   int key;
   printf("Press F10 key to Quit\n");

   while(1){
      key = bioskey(1);
      if(key > 0){
         if(handle_keyevents() < 0)
            break;
      }
   }
}

Upvotes: 0

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

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?

Upvotes: 3

Related Questions