Is there an alternative to getch(); which won'

2019-09-15 19:05发布

I'm writing a game currently in ncurses and I have a ship that is controlled by the user and an 'automated' that moves slowly down the lines to kill you. However, I'm using a while loop containing everything and each time I use getch() the loop pauses and waits for input, meaning that the enemy only moves after input from the user.

        c=getch(); //causes a pause until a button is pressed before the next action

        if(c==97) //if a is pressed, move position of '*' left
        {
            dir=-1;

        }

        if(c==100) //if d is pressed, move position of '*' right
        {
            dir=1;

        }

2条回答
欢心
2楼-- · 2019-09-15 19:20

Since you're using curses, just call nodelay or halfdelay or timeout to make getch non-blocking, or have it return after a short wait if no key has been pressed. See the inopts(3ncurses) man page.

查看更多
贪生不怕死
3楼-- · 2019-09-15 19:22

Use poll on the input file descriptor (0, aka STDIN_FILENO) to determine whether there's input pending before you call getch. Normally you would poll with a nonzero timeout and then the call doubles as the timing for your game's loop so it runs at a fixed tick rate you control rather than as many iterations per second as the cpu/system load allow.

查看更多
登录 后发表回答