简体   繁体   English

C++ | 如何使用 Linux 从箭头键获取输入

[英]C++ | How to get input from the arrow keys with Linux

I'm super new to C++ and was wanting to add arrow key functionality to my snake game.我是 C++ 的超级新手,想在我的贪吃蛇游戏中添加箭头键功能。 I've been scouring the Inte.net trying to find a way to do this without "conio.h" as I am using Linux. How would I go about doing this and can I get some example code?我一直在搜索 Inte.net,试图找到一种无需“conio.h”即可执行此操作的方法,因为我正在使用 Linux。我 go 如何执行此操作,我能否获得一些示例代码?

Thank you!谢谢!

You'd be best off using ncurses - just google for some tutorials to get yourself started.您最好不要使用ncurses - 只需谷歌搜索一些教程即可开始使用。 It can do simple things like clear the screen, get the terminal dimensions, position the cursor at arbitrary coordinates, write text in arbitrary colours, and yes - read characters from the keyboard without waiting for enter to be pressed.它可以做一些简单的事情,比如清除屏幕、获取终端尺寸、任意坐标处的 position cursor、以任意颜色书写文本,是的——从键盘读取字符而无需等待按下回车键。 Enjoy your project!享受你的项目!

Try out:试用:

#include <ncurses.h>

int main(){
    int ch;

    initscr();
    raw();
    keypad(stdscr, TRUE);
    noecho();


    while ((ch = getch()) != '#') {
        switch(ch) {
            case KEY_UP: printw("\nUp");
            break;

            case KEY_DOWN: printw("\nDown");
            break;

            case KEY_LEFT: printw("\nLeft");
            break;

            case KEY_RIGHT: printw("\nRight");
            break;

            default: printw("%c", ch);
        }
    }
    refresh();
    getch();
    endwin();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM