I took the liberty to try and tackle this myself.
Solely based on the question text, it's not super clear what kind of game you're trying to do, so I took the approach of a kind of snake game, where the snake will move, whatever the player is doing (or not doing).
I used Sleep to pace the input polling and the redraw rate, and _kbhit() to maybe read a character, and the clock_t/clock() to update the game once per second.
Now I'm not a c programmer, so I don't know if this c code is "elegant" (it's probably not), but it worked on my machine (Windows, Visual Studio).
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <ctype.h>
#include <windows.h>
typedef int BOOL;
#define FALSE ((int)0)
#define TRUE ((int)1)
void ClearScreen()
{
// code here that clears the screen, see https://stackoverflow.com/a/42500322
}
int main( void )
{
BOOL run = TRUE;
clock_t lastTickClock = clock();
int position = 0;
char registeredCommand = 'd'; // Command that will be effective at the next game tick.
while ( run )
{
char currentCharIfAny = 0; // The char that is read this loop.
if ( _kbhit() )
currentCharIfAny = _getch();
if ( currentCharIfAny == 'a' || currentCharIfAny == 'd' )
registeredCommand = currentCharIfAny; // We only respond to 'a' or 'd'.
clock_t newClock = clock();
if ( ( newClock - lastTickClock ) > CLOCKS_PER_SEC )
{
// This is the command handling/the game tick
if ( registeredCommand == 'a' )
position = max( --position, 0 );
else if ( registeredCommand == 'd' )
position = min( ++position, 24 );
lastTickClock = newClock;
}
char buffer[1024];
buffer[0] = 0;
for ( int i = 0; i < position; ++i )
strcat_s( buffer, 1024, " " );
strcat_s( buffer, 1024, "_\n" ); // This underscore represents our "agent" or "game token" or "paddle".
// The following is only for debugging purpose; it prints the character we're currently handling.
if ( currentCharIfAny >= 'a' && currentCharIfAny <= 'z' )
{
char lbuff[2]; lbuff[0] = 0;
sprintf_s( lbuff, 2, "%c", currentCharIfAny );
strcat_s( buffer, 1024, lbuff );
}
ClearScreen();
printf( "%s\n", buffer );
Sleep( 1000 / 60 );
if ( currentCharIfAny == 'q' )
run = FALSE;
}
printf( "\ndone. press a key to quit." );
_getch();
return 0;
}
A couple of things to note:
- there are probably other (better) ways to achieve this: for now, when I refresh (ClearScreen), the screen "flickers" a bit.
- on Windows, the OS will "pace" the repeat rate of the character it sends to the apps, so when you hit d for instance, the program will show that you're hitting d, then it will show that you're hitting no key, then it will show you're hitting d again, until you release the key.
- like your own implementation, it's not portable due to the nature of the functions used.
stdio.hand learn a game development library for input handling and graphics instead. Like SDL, for example. \$\endgroup\$