ncurses:箭头键不起作用

问题描述 投票:0回答:2

我正在尝试编写蛇形克隆,并且我刚刚开始编写代码,但是在使键盘正常工作时遇到了一些问题。单击箭头键时似乎没有收到信号。这是我的代码

#include <iostream>
#include <unistd.h>
#include <ncurses.h>

struct Snake{
    int x, y;
    char s = 'O'; // logo
} snake;

int main()
{

    initscr();
    noecho();
    curs_set(0);
    keypad(stdscr, true);
    nodelay(stdscr, true);
    start_color();
    init_pair(1, COLOR_MAGENTA, COLOR_BLACK );
    attron(COLOR_PAIR(1));
    int HEIGHT, WIDTH;

    getmaxyx(stdscr, HEIGHT, WIDTH);

    for (int x = 0; x < WIDTH-1; x++)
        mvaddch(0, x, '*');

    for (int y = 0; y < HEIGHT-2; y++)
        mvaddch(y, WIDTH-1, '*');

    for (int x = 0; x < WIDTH-1; x++)
        mvaddch(HEIGHT-2, x, '*');

    for (int y = 0; y < HEIGHT-2; y++)
        mvaddch(y, 0, '*');


    snake.x = WIDTH/2;
    snake.y = HEIGHT/2;
    mvaddch(snake.y, snake.x, snake.s);
    refresh();


    char key;
    while((key = getch()) != 'q')
    {
        mvaddch(snake.y, snake.x, ' ');
        switch(key)
        {
        case KEY_RIGHT:
            snake.x +=1;    
            break;

        case KEY_LEFT:
            snake.x -=1;    
            break;

        case KEY_UP:
            snake.y -=1;    
            break;

        case KEY_DOWN:
            snake.y +=1; 
            break;
        }

        mvaddch(snake.y, snake.x, snake.s);

        usleep(100000);
        refresh();
    }

    getch();
    erase();
    endwin();
}
c++ ncurses arrow-keys
2个回答
1
投票

使用wchar_t代替char存储箭头代码。

查看:char vs wchar_t when to use which data type

底线是保证char足够用于ASCII字符集的空间,因为它的数量接近256位。但是Unicode编码需要的空间超出char所不能承受的范围。


0
投票

char不足以容纳KEY_RIGHT,因为它是在char范围内以after开头的一组字符中的一部分。

同样,wchar_t足够大,但是(如参考手册所述,intint是给定示例的正确类型,正如编译器会告诉您的(在询问时)。

([chtypechtype的大小也不相同,但是出于实际目的,curses库使用的任何int都适合chtype。]

© www.soinside.com 2019 - 2024. All rights reserved.