带有 ncurses 的 WASD 移动(不知道为什么它不起作用)

WASD movement with ncurses (Not sure why it doesnt work)

我想用我刚刚在 ncurses 中学到的知识创建一个程序。有了它,用户应该能够使用 WASD 在屏幕上用 # 绘图。这是我做的代码:

#include<stdio.h>
#include<ncurses.h>

int main (void)
{
        initscr();
        noecho();
        int coord_x = 10;
        int coord_y = 10;
        char direccion;
        mvwprintw(stdscr,coord_y,coord_x,"#");
        while (1)
        {
                refresh();
                direccion = getchar();
                switch (direccion)
                {
                  case 'w':
                        coord_y -= 1;
                  case 's':
                        coord_y += 1;
                  case 'a':
                        coord_x -= 1;
                  case 'd':
                        coord_x += 1;
                  case 'q':
                        break;
                  default:
                        continue;
                }
                if (coord_x == -1 && coord_y == -1) { coord_y += 1;coord_x += 1;}
                mvwprintw(stdscr,coord_y,coord_x,"#");
                if (direccion == 'q') {break;}
        }
        endwin();
        return 0;
}

但我不太确定为什么 # 既不向上也不向左移动。我认为问题出在这部分:

direccion = getchar();
                switch (direccion)
                {
                  case 'w':
                        coord_y -= 1;
                  case 's':
                        coord_y += 1;
                  case 'a':
                        coord_x -= 1;
                  case 'd':
                        coord_x += 1;
                  case 'q':
                        break;
                  default:
                        continue;
                }

但是我真的不确定,你知道为什么它不起作用吗?

编辑:感谢大家,现在我意识到我只是愚蠢而忘记了如何使用开关

您需要在 switch 语句中的每个赋值后添加 breaks:

switch (direccion) {
case 'w':
    coord_y -= 1;
    break; /* <-- here */
case 's':
    coord_y += 1;
    break; /* <-- here */
case 'a':
    coord_x -= 1;
    break; /* <-- here */
case 'd':
    coord_x += 1;
    break; /* <-- here */
case 'q':
    break;
default:
    continue;
}

case 的默认行为是 "fall through" 到下一个,所以如果你按 w 它将执行所有 coord_xcoord_y 项作业,而不仅仅是您想要的作业。