Sleep () in ncurses application

I am trying to make text animation for an application created in ncurses.

The user presses a key, selects a direction, and the object in the text grid must move from one grid cell to the next in this direction, waiting 500 ms before it moves. The code I use

while (!checkcollisions(pos_f, input)) { // Checks if it can move to next grid pos_f = moveobject(pos_f, input, ".."); // Moves object to next cell usleep(50000); } 

But when I execute it, instead of moving, waiting and moving again, it waits for a long time, and the object suddenly appears in the last cell of the grid, without showing animation.

Is this because of how ncurses work? I have already tried using other solutions, such as the select () lock function.

+4
source share
3 answers

You need to call refresh() (before usleep ).


Update: new code segments with codes (in a few comments) indicate a real problem that is the same in ncurses-refresh : mixing stdscr (implied by the following two calls) and getch and refresh with newwin and wrefresh .
Update 2: using the full code, as well as some hacks, I got it to work (for some value, "work", I obviously do not call printmap () correctly, and I compiled a dummy file "map").

Without looking carefully, I just changed all occurrences of getch() to wgetch(win.window) , all mvprintw turned to mvwprintw (to use the same window) and deleted at least one unnecessary getch / wgetch. Then the essence of the problem:

  while (!checkcollisions(pos_f, input)) { - pos_f = moveobject(pos_f, input, ".."); - // sleep + wrefresh(win.window) doesn't work, neither does refresh() + struct position new_pos = moveobject(pos_f, input, ".."); + printmap(pos_f, new_pos); + pos_f = new_pos; + wrefresh(win.window); + fflush(stdout); + usleep(50000); } 

The above printmap call printmap definitely wrong, but you still need to do something in the loop to change what was in win.window (or stdscr or some other window you put or something else); and then you need to force it to update and force output to stdout using fflush(stdout) before going to bed.

+7
source

See accepted answer here . You force everything to lock with getch, after getch is unlocked with a readable key, everything will move as you expect.

Your loop should look something like this using the code from the link ...

  while (! kbhit ())
 {
      sleep (500);  // You get to determine how long to sleep here ...
 }

 input = getch ();

 // Your old logic, roughly, goes here.
+1
source

Try something like

 while (!checkcollisions(pos_f, input)) { // Checks if it can move to next grid pos_f = moveobject(pos_f, input, ".."); // Moves object to next cell refresh(); napms(200); } 
0
source

Source: https://habr.com/ru/post/1402054/


All Articles