1

How do i make the program to recognize the certain keys I press? To understand the context: I want to make a game in C (very basic game), so in order to move the object, I want to pres (W A S D),I know how to move it, but I don't know how to make the program understand that I want to do a certain action, when one of those keys are pressed. For example:

if( key == "A"){
x++
}

I know it dose not work like that, but something at least similar.

alk
  • 69,737
  • 10
  • 105
  • 255
DanielRO
  • 43
  • 1
  • 5

3 Answers3

1

You can include conio.h (on Windows) or ncurses.h libraries (on Linux) and using functions like getch() for return a char that is pressed by the user. Then you can check if the char is what you want.

tuzzo
  • 75
  • 1
  • 1
  • 10
1

You can use kbhit included in conio.h as mentioned in the comments above.A simple example is shown below.

#include <conio.h>

int main()
{
    char ch;

    if (kbhit()) {

            // Stores the pressed key in ch
            ch = getch();
            printf("%c was pressed.\n", ch)

            //do something..

    }
    return 0;
}

I think this link will be helpful to you.

Kishor
  • 450
  • 8
  • 11
1
#include <stdio.h>
#include <conio.h> /* getch() and kbhit() */

int main()
{
    char c;

    for(;;){
        if(kbhit()){
            c = getch();
            if(c == 'c')
            {
                printf("%c\n", c);

               // more code here..
            }
         }
    }
    return 0;
}

as the above answer, but the code must be in infinite loop to scan whenever a key is pressed. and the code will only check if the key 'c' is pressed. you can easily remove the if condition and make it more generalized :)

Jay Joshi
  • 868
  • 8
  • 24