How to handle multiple conditionals (if and if if followed) in Java and how to compress them?

Asked

Viewed 571 times

2

Currently I have a small group of classes that implement a game of Snake with two players.

I am implementing the movements as the keystrokes, currently the code is like this:

    // #----- Classe anônima para lidar com os movimentos -----#

    private class Key implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_RIGHT) {
                p1.getSnake().setDirection(new Right()); //se a tecla foi seta a direita p1 move
            } else if (key == KeyEvent.VK_D) {
                p2.getSnake().setDirection(new Right()); //se a tecla foi "d" o p2 move
            }
            if (key == KeyEvent.VK_LEFT) {
                p1.getSnake().setDirection(new Left());
            } else if (key == KeyEvent.VK_A) {
                p2.getSnake().setDirection(new Left());
            }
            if (key == KeyEvent.VK_UP) {
                p1.getSnake().setDirection(new Up());
            } else if (key == KeyEvent.VK_W) {
                p2.getSnake().setDirection(new Up());
            }
            if (key == KeyEvent.VK_DOWN) {
                p1.getSnake().setDirection(new Down());
            } else if (key == KeyEvent.VK_S) {
                p2.getSnake().setDirection(new Down());
            }
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
    }

The method keyPressed() has 4 if followed by else if, the code gets hard to read and Maven complains that it’s not the right way to program, and gives me checkstyle Violation.

I don’t have much programming experience yet, and I don’t know how to rewrite that piece of code more efficiently.

How I could improve reading and understanding of the method KeyPressed()?

2 answers

3


There are 4 different actions, so at least 4 ifs must be used. Each action happens with two different conditions, so there is no reason to have two ifs, just concatenate the two conditions creating a larger and complete condition. To concatenate conditional expressions and create another one is used && (an E) or || (an OR). You can still use more operands but those are the main ones. In case you want one OR the other, then that’s what will be used. Something like this:

if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D) p1.getSnake().setDirection(new Right());

I put in the Github for future reference.

Do the same with others. You can use the else if to improve performance. Because if it goes into the first one it doesn’t need to go into the others, then it can make a single block, something like that:

else if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A) p1.getSnake().setDirection(new Left());

-1

You can create a value key object where the key is the Keycode of the button pressed and the value can be a function that arrow the direction.

I did the example in js, because it is more practical and you can visualize here.

You can replicate it in the overwhelming majority of languages, so don’t worry about it, the important thing is the concept.

class Snake {
  up() {
    console.log('cima')
  }

  down() {
    console.log('baixo')
  }

  left() {
    console.log('esquerda')
  }

  right() {
    console.log('direita')
  }
}

const moves = {
  ['w']: (snake) => snake.up(),
  ['a']: (snake) => snake.left(),
  ['s']: (snake) => snake.down(),
  ['d']: (snake) => snake.right(),
  ['ArrowUp']: (snake) => snake.up(),
  ['ArrowLeft']: (snake) => snake.left(),
  ['ArrowDown']: (snake) => snake.down(),
  ['ArrowRight']: (snake) => snake.right()
}

document.addEventListener('keydown', (event) => {
  const mySnake = new Snake()
  // 0 if's (pelo menos explicitamente)
  moves[event.key](mySnake)
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.