Getch()与Linux C ++中的显示功能不兼容 [英] Getch() incompatible with display function in linux c++

查看:78
本文介绍了Getch()与Linux C ++中的显示功能不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个班级制作2D地牢爬虫类游戏.我正在尝试接收用户输入,而不需要按下Enter键.具体来说,我想使用w a s d作为方向键在2D数组中移动.

I am making a 2D dungeon crawler type game for a class. I am trying to receive user input without requiring the enter key to be pressed. Specifically, I want to use w a s d as directional keys to move around a 2D array.

我曾经尝试使用ncurses库,但目前它与我的显示功能搞混了(我相信使用endl时会如此).

I've tried using the ncurses library but it currently messes with my display function (I believe when using endl).

通常我的木板显示如下:
xxx
xxx
xxx

Normally my board displayed will look like:
xxx
xxx
xxx

但是当使用ncurses库中的getch()时,我的面板看起来像:
xxx
...... xxx
............ xxx

But when using getch() from the ncurses library my board looks like:
xxx
......xxx
............xxx

有没有一种方法可以使用curses库中的getch()而不干扰我的打印功能?

Is there a way to use getch() from the curses library without it interfering with my print function?

void ParkBoard::print() {
displayMessage();
for (int i = 0; i < getSize(); i++) {
    cout << " ";
    for (int j = 0; j < getSize(); j++) {
        if (j == 0) {
            parkBoard[i][j]->display();
        }
        else {
            cout << " ";
            parkBoard[i][j]->display();
        }
    }
    cout << endl;
}

推荐答案

ncurses希望它可以完全控制显示终端.您正在使用ncurses进行输入,但仍将输出喷出到std::cout.

ncurses expects that it has full control over the display terminal. You are using ncurses for input, but still spewing output to std::cout.

这行不通.至少并非没有重大的黑客攻击.

This is not going to work. At least not without major hacking.

ncurses是一项全有或全无的交易.您可以使用ncurses进行输入和终端输出,或者完全使用其他方法.

ncurses is an all or nothing deal. Either you use ncurses for input, and for terminal output, or use something else entirely.

但是有一个更简单的解决方案,因为您要做的就是无需按下回车键即可接收用户输入":

But there's a much easier solution, since all you're trying to do is "receive user input without requiring the enter key to be pressed":

  1. 只需将文件描述符0置于非阻塞模式,并使用read()从fd 0读取(因为std::cin从非阻塞文件描述符读取时将需要太多保姆).
  1. Just put file descriptor 0 in non-blocking mode, and read from fd 0 using read() (since std::cin will require too much babysitting when it's reading from a non-blocking file descriptor).

请参见 fcntl(2)手册页,并进行搜索对于O_NONBLOCK.然后:

See the fcntl(2) manual page, and search for O_NONBLOCK. Then:

  1. 通过关闭ICANON标志将终端置于非规范模式.请参见 termios(3)手册页. ncurses就是这样做的,以访问原始的击键.
  1. Put the terminal in non-canonical mode by turning off the ICANON flag. See the termios(3) manual page. This is what ncurses does, to get access to the raw keystrokes.

如果程序中止,您需要做一些工作以将终端恢复到规范模式,以便以理智"的终端模式返回外壳.

You will need to do a little bit of work to restore the terminal to canonical mode, if the program is aborted, in order to get back to the shell in "sane" terminal mode.

这篇关于Getch()与Linux C ++中的显示功能不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆