Search code examples
cinputheaderdev-c++

C Input getch(), skip when nothing pressed like Snake (game)


I have to program a game in C in the console. For example I want to count something up when I press the space key. But only while I press the key. When I release the key again it should stop counting and start again when I press it again. I want it like snake, I mean it doesn't stop for the input it gets the input when the user pressed it.

I have tried with kbhit, it counts up and when I press something it prints nothing for ever, even if I press a key again.

while (1) {
        h = kbhit();
        fflush(stdin);
        if (h) {

            printf("%d\n", a);
            a += 1;

        } else {
            printf("nothing\n");
        }

    }

I expect nothing nothing nothing presses a key 0 nothing presses key again 1 hold on key 2 3 4

Thanks


Solution

  • From your code, you did not store the key pressed into a variable. Please have a go with this method.

    The first 3 lines shows how to store a keyboard hit variable into h. The rest will be incrementing the a value.

    while (1) {
    
        /* if keyboard hit, get char and store it to h */
        if(kbhit()){
    
            h = getch();
        }
    
        /*** 
            If you would like to control different directions, there are two ways to do this.
            You can do it with if or switch statement.
            Both of the examples are written below.
        ***/
    
        /* --- if statement version --- */
        if(h == 0){
    
            printf("%d\n", a);
            a += 1;
        }
        else{
    
            printf("nothing\n");
        }
    
        /* --- switch statement version --- */
        switch(h)
        {
            case 0:
                printf("%d\n", a);
                a += 1;
            break;
    
            default: printf("nothing\n");
            break;
        }
    }