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()
?