Is there an alternative to getch(); which won't pause the program?

亡梦爱人 提交于 2019-12-12 04:45:33

问题


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;

        }

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/44052176/is-there-an-alternative-to-getch-which-wont-pause-the-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!