
|
Real time key-pressSome of you, for example those who are doing pong or snake, might be interested
in having your program react to key-presses in real-time, and not waiting for the user
to press Enter every time a key is input. The example program below may help in this:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main() {
int ch;
initscr();
cbreak();
noecho();
refresh();
ch = getch();
while (ch != 'q') {
system("clear");
if (ch == 'a')
printf("Left arrow pressed\n\r");
if (ch == 'd')
printf("Right arrow pressed\n\r");
if (ch == 'w')
printf("Up arrow pressed\n\r");
if (ch == 's')
printf("Down arrow pressed\n\r");
refresh();
ch = getch();
}
printf("Program terminated.\n\r");
return 0;
}
When you run this program, you basically have the keys w, a, s, d as up, left, down,
right. When you press one of those keys, it prints the corresponding message. When
you press q, it quits.Some things to pay attention to when doing this:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||