package jbrickbreaker.controller;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import jbrickbreaker.UserPreferences;
import jbrickbreaker.model.Ball;
import jbrickbreaker.model.Game;
import jbrickbreaker.model.Pad;
import jbrickbreaker.view.GameView;
/**
* This class control all the action made by the player with the keyboard.
*
* Date: 18 Dec 2010 Time: 10:03:17
*
* @author Maxime Reymond
*/
public class KeyboardController extends KeyAdapter {
private Game game;
private GameView gameView;
public int keyLeft = UserPreferences.getKey(UserPreferences.KEY_LEFT);
public int keyRight = UserPreferences.getKey(UserPreferences.KEY_RIGHT);
public int keyEject = UserPreferences.getKey(UserPreferences.KEY_EJECT);
public int keyPause = UserPreferences.getKey(UserPreferences.KEY_PAUSE);
enum Direction {
LEFT, RIGHT, UNDEF
}
private Direction lastDirection;
public KeyboardController(Game game, GameView gameView) {
this.game = game;
this.gameView = gameView;
lastDirection = Direction.UNDEF;
}
private void manageCumulativeSpeed(Direction dir) {
Pad pad = Pad.getInstance();
if (lastDirection == dir) {
pad.increaseCumulativeSpeed();
} else {
pad.resetCumulativeSpeed();
lastDirection = dir;
}
}
@Override
public void keyPressed(KeyEvent e) {
Pad pad = Pad.getInstance();
if (e.getKeyCode() == keyLeft && !gameView.isPaused()) {
if (game.getPadXPos() - game.getPadSpeedX() <= 0)
game.setPadXPos(0);
else {
game.addToPadXPos(-game.getPadSpeedX());
if (pad.isStuck()) {
for (Ball b : game.getBalls()) {
if (game.checkCollisionPad(b)) {
b.setX(b.x - game.getPadSpeedX());
}
}
}
}
manageCumulativeSpeed(Direction.LEFT);
gameView.repaint();
} else if (e.getKeyCode() == keyRight && !gameView.isPaused()) {
if ((game.getPadXPos() + Pad.getInstance().getWidth() + game
.getPadSpeedX()) >= gameView.getWidth())
game.setPadXPos(gameView.getWidth()
- Pad.getInstance().getWidth() - 2);
else {
game.addToPadXPos(game.getPadSpeedX());
if (pad.isStuck()) {
for (Ball b : game.getBalls()) {
if (game.checkCollisionPad(b)) {
b.setX(b.x + game.getPadSpeedX());
}
}
}
}
manageCumulativeSpeed(Direction.RIGHT);
gameView.repaint();
} else if (e.getKeyCode() == keyEject && !gameView.isPaused()) {
if (game.collision)
game.unstuckBalls();
if(gameView.isDisplayingStartHelp())
gameView.setDisplayStartHelp(false);
pad.resetCumulativeSpeed();
lastDirection = Direction.UNDEF;
} else if (e.getKeyCode() == keyPause) {
final boolean isPaused = gameView.isPaused();
gameView.setPaused(!isPaused);
}
}
}