user2229040
user2229040

Reputation: 33

C, ncurses; if statement within while loop not functioning properly

I'm writing a function that draws @ characters onto a console screen, and repeats itself until it draws upon a 'H' which has already been drawn. Basically a "bomb" function. I wrote the function with a while loop so that it may continue to draw the character as long as the space it is drawing upon does not equal 'H'. If it does equal 'H', i've put in an if statement to break the program. However even with the if statement, the program continues to run when it is drawn on an 'H'.

void bomb_until_hit(int home_radius) {
    int x = 0, y = 0;
    while (mvinch(y, x) != 'H') {
        x = get_next_bomb_x();
        y = get_next_bomb_y();
        mvaddch(y, x, '@' );
        refresh();
        sleep(1);
        if (mvinch(y, x) == 'H') {
        break; }
        }
     }

mvinch is a function which basically checks the coordinates for characters before the new character is drawn.

Why is my if statement not working?

Upvotes: 0

Views: 250

Answers (1)

David Schwartz
David Schwartz

Reputation: 182855

Your code draws an @ and then checks for an H (twice). Obviously, it's not going to find an H since it just drew an @.

Let's look at what happens starting from when you move to a new position:

void bomb_until_hit(int home_radius) {
    int x = 0, y = 0;
    while (mvinch(y, x) != 'H') { // 5) Check for an H here
        x = get_next_bomb_x(); // 1) Move to next X
        y = get_next_bomb_y(); // 2) Move to next Y
        mvaddch(y, x, '@' );   // 3) Put an @ here
        refresh();
        sleep(1);
        if (mvinch(y, x) == 'H') { // 4) Check for an H here
        break; }
        }
     }

You need to rearrange the order of your statements so that once you move to a new spot, you check it before you write to it.

Upvotes: 1

Related Questions