cprintingncursesusleep

how to print two things simultaneously with ncurses


I'm making a game in ncurses similar to space invaders.

Thus far I've gotten movement and shooting down but I've run into an issue.

When the player fires a laser I am using a usleep call to delay the laser moving across the screen so that it doesn't just show up from one end of the screen to the other.

The problem with using usleep to delay the laser means that the player cannot move around while the laser is travelling across the screen until the loop exits.

My question is, is there another way to print the laser moving across the screen while at the same time moving the player/cursor with user input?

When the user presses the 'f' key the following code moves the line (laser) across the screen. However the user cannot move again until after the laser has left the screen:

void combat(int y, int x)
{
    do
    {
        mvprintw(y -1, x, "|");
        refresh();
        y--;
        usleep(50000);
        mvprintw(y , x, " ");   
    }
    while(y>0);
}

Solution

  • I've actually found a decent solution to my own problem so I'll leave this here in case anyone has a similar issue in the future.

    When my program enters the combat function it also enters into nodelay mode making a non blocking getch(). As the function cycles through sleeps the user can enter a character at any time causing the ship to move and since it is in no delay mode the getch() does not block the sleep function from executing if the user chooses to stay still.

    The combat function which executes when the user presses 'f':

    void combat(int y, int x)
    {
    int input;
    int y2 = y;
    int x2 = x;
    do
    {
        mvprintw(y2 -1, x2+1, "|");
        refresh();
        y2--;
        mvprintw(y2 , x2+1, " ");
        usleep(50000);
        nodelay(stdscr, TRUE);
        input = getch();
    
        switch(input)
        {
            case 'w':
            mvprintw(y, x,"   ");
            y--;
            mvprintw(y, x,"^V^");
            break;
    
            case 'a':
            mvprintw(y, x+2," ");
            x--;
            mvprintw(y, x,"^V^");
            break;
    
            case 's':
            mvprintw(y, x,"   ");
            y++;
            mvprintw(y, x,"^V^");
            break;
    
            case 'd':
            mvprintw(y, x," ");
            x++;
            mvprintw(y, x,"^V^");
            break;
    
        }
    
    }
    while(y2>0);
    movement(y,x);
    

    }