Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if-statements C++

I'm writing a Snake program in C++ (visualisation with JNI) and valid movement buttons are either left (move 90° counter-clockwise) or right (move 90° clockwise).

In every loop of the game loop I retrieve a key event from a GUI interface and move my snake according to that key event, this is how i do this:

if(key_event != NULL){
    if(key_event == LEFT){
        if(moveDirection == UP || moveDirection == DOWN){
            moveDirection = LEFT;
            (moveDirection == UP) ? /*change turn after head*/ : /*change turn after head*/;
        } //else if (moveDir == LEFT || RIGHT)
    } //else if (key_event == RIGHT)
    //...
}

The if with: /*change turn after head*/ is because if the snake is moving down and goes left there is another graphic for the turn then when it's going up and goes left.

This leads to a lot of if-statements and is not very readible, so I'm wondering if there's a general way to solve nested if-statements like this.

EDIT:
key_event and moveDirection are enums.

like image 562
Aerus Avatar asked Dec 02 '25 08:12

Aerus


2 Answers

It feels like Finite State Machine is what you need here. You can define keys as events, snake positions as states and describe transitions from one state into another depending on the event (what key pressed). That will pretty much solve the problem and use transition table instead of nested if statements and make your implementation less error prone. Boost Statechart Library can help you implement it quickly.

I would personally have another function to apply the move.

if(key_event != NULL){
    if(key_event == LEFT){
       moveLeft();
    }
    ...
}

void moveLeft()
{
  switch(moveDirection)
  {
    case UP:
    case DOWN:
      moveDirection = LEFT;
      break;
    case ...
  }
}

I use switch case, in my opinion it is more read-able for this example rather than if.. else if.. else if...

The point is, when you have nested loops, see if you can break some of it into a function to simplify the problem.

I hope this helps.

like image 45
Jón Trausti Arason Avatar answered Dec 03 '25 20:12

Jón Trausti Arason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!