2

I am making an ASCII movement system in ncurses with C. As of now if I press movement buttons character moves just fine (example of movement function):

void hero_move_right(){
  if (allow_move_to(Y, X + 1)){
    mvaddch(Y, X, EMPTY);
    X += 1;
    mvaddch(Y, X, MVRIGHT);
  }
}

Loop in main looks like this:

int input;
  bool key_was_preessed = false;
  do {
    input = getch();
    switch (input){
      case w:
      case W:
        hero_move_up();
        key_was_preessed = true;
        break; 
      case s:
      case S:
        hero_move_down();
        key_was_preessed = true;
        break;
      case d:
      case D:
        hero_move_right();
        key_was_preessed = true;
        break;
      case a:
      case A:
        hero_move_left();
        key_was_preessed = true;
        break;
      /*determines of the game has started*/
      if (key_was_preessed == true){
        mvaddch(((row - MX)/2 + 1), ((col - MY)/2 + 1), EMPTY);
        move(Y, X);
      }
    
    }
 } while ((input != q) && (input != Q));

Right now a player can press or hold keys to move around. Is there a way to detect if the key is on hold? (I tried storing last two pressed buttons in an array and comparing them to each other but this way the player can only move around by constantly pressing different keys. ex: was - w-w-w became - w-s-w-d-w etc.) The idea is to be able to move around by just pressing buttons so that the speed of movement depends on how fast the player can press buttons. You can check the code of the project here: https://github.com/theonlymoby/collector

Thanks for the help!

  • 2
    Assuming you pasted the real code: Please autoindent/autoformat your code and read it through. The problem may become apparent from indentation. Or at least you find *something* to fix. – hyde Jan 12 '22 at 10:23
  • Also, turn on warnings and fix them. There should also be a compiler warning about the issue. – hyde Jan 12 '22 at 10:54
  • 1
    I use gcc compiler. There is no issues. I am just looking for a feature to implement, not a problem to fix. What I described above is an expected ncurses behavior. Thanks for the feedback. – theonlymoby Jan 12 '22 at 11:07
  • You have unreachable code (assuming the code in question matches your real code). Compiler should warn about that. – hyde Jan 12 '22 at 12:28
  • 1
    Adding `-Wall -Wextra` to *gcc* compiler flags should enable a reasonable set of warnings. – hyde Jan 12 '22 at 12:30
  • 1
    Possible duplicate: https://stackoverflow.com/questions/1409216/receiving-key-press-and-key-release-events-in-linux-terminal-applications – hyde Jan 12 '22 at 12:31

0 Answers0