Input Manager Test : Input « Game « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Game » InputScreenshots 
Input Manager Test

       /*
DEVELOPING GAME IN JAVA 

Caracteristiques

Editeur : NEW RIDERS 
Auteur : BRACKEEN 
Parution : 09 2003 
Pages : 972 
Isbn : 1-59273-005-1 
Reliure : Paperback 
Disponibilite : Disponible a la librairie 
*/


import java.awt.AWTException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.DisplayMode;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * InputManagerTest tests the InputManager with a simple run-and-jump mechanism.
 * The player moves and jumps using the arrow keys and the space bar.
 * <p>
 * Also, InputManagerTest demonstrates pausing a game by not updating the game
 * elements if the game is paused.
 */

public class InputManagerTest extends GameCore {

  public static void main(String[] args) {
    new InputManagerTest().run();
  }

  protected GameAction jump;

  protected GameAction exit;

  protected GameAction moveLeft;

  protected GameAction moveRight;

  protected GameAction pause;

  protected InputManager inputManager;

  private Player player;

  private Image bgImage;

  private boolean paused;

  public void init() {
    super.init();
    Window window = screen.getFullScreenWindow();
    inputManager = new InputManager(window);

    // use these lines for relative mouse mode
    //inputManager.setRelativeMouseMode(true);
    //inputManager.setCursor(InputManager.INVISIBLE_CURSOR);

    createGameActions();
    createSprite();
    paused = false;
  }

  /**
   * Tests whether the game is paused or not.
   */
  public boolean isPaused() {
    return paused;
  }

  /**
   * Sets the paused state.
   */
  public void setPaused(boolean p) {
    if (paused != p) {
      this.paused = p;
      inputManager.resetAllGameActions();
    }
  }

  public void update(long elapsedTime) {
    // check input that can happen whether paused or not
    checkSystemInput();

    if (!isPaused()) {
      // check game input
      checkGameInput();

      // update sprite
      player.update(elapsedTime);
    }
  }

  /**
   * Checks input from GameActions that can be pressed regardless of whether
   * the game is paused or not.
   */
  public void checkSystemInput() {
    if (pause.isPressed()) {
      setPaused(!isPaused());
    }
    if (exit.isPressed()) {
      stop();
    }
  }

  /**
   * Checks input from GameActions that can be pressed only when the game is
   * not paused.
   */
  public void checkGameInput() {
    float velocityX = 0;
    if (moveLeft.isPressed()) {
      velocityX -= Player.SPEED;
    }
    if (moveRight.isPressed()) {
      velocityX += Player.SPEED;
    }
    player.setVelocityX(velocityX);

    if (jump.isPressed() && player.getState() != Player.STATE_JUMPING) {
      player.jump();
    }
  }

  public void draw(Graphics2D g) {
    // draw background
    g.drawImage(bgImage, 00null);

    // draw sprite
    g.drawImage(player.getImage(), Math.round(player.getX()), Math
        .round(player.getY())null);
  }

  /**
   * Creates GameActions and maps them to keys.
   */
  public void createGameActions() {
    jump = new GameAction("jump", GameAction.DETECT_INITAL_PRESS_ONLY);
    exit = new GameAction("exit", GameAction.DETECT_INITAL_PRESS_ONLY);
    moveLeft = new GameAction("moveLeft");
    moveRight = new GameAction("moveRight");
    pause = new GameAction("pause", GameAction.DETECT_INITAL_PRESS_ONLY);

    inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
    inputManager.mapToKey(pause, KeyEvent.VK_P);

    // jump with spacebar or mouse button
    inputManager.mapToKey(jump, KeyEvent.VK_SPACE);
    inputManager.mapToMouse(jump, InputManager.MOUSE_BUTTON_1);

    // move with the arrow keys...
    inputManager.mapToKey(moveLeft, KeyEvent.VK_LEFT);
    inputManager.mapToKey(moveRight, KeyEvent.VK_RIGHT);

    // ... or with A and D.
    inputManager.mapToKey(moveLeft, KeyEvent.VK_A);
    inputManager.mapToKey(moveRight, KeyEvent.VK_D);

    // use these lines to map player movement to the mouse
    //inputManager.mapToMouse(moveLeft,
    //  InputManager.MOUSE_MOVE_LEFT);
    //inputManager.mapToMouse(moveRight,
    //  InputManager.MOUSE_MOVE_RIGHT);

  }

  /**
   * Load images and creates the Player sprite.
   */
  private void createSprite() {
    // load images
    bgImage = loadImage("../images/background.jpg");
    Image player1 = loadImage("../images/player1.png");
    Image player2 = loadImage("../images/player2.png");
    Image player3 = loadImage("../images/player3.png");

    // create animation
    Animation anim = new Animation();
    anim.addFrame(player1, 250);
    anim.addFrame(player2, 150);
    anim.addFrame(player1, 150);
    anim.addFrame(player2, 150);
    anim.addFrame(player3, 200);
    anim.addFrame(player2, 150);

    player = new Player(anim);
    player.setFloorY(screen.getHeight() - player.getHeight());
  }

}

/**
 * The Player extends the Sprite class to add states (STATE_NORMAL or
 * STATE_JUMPING) and gravity.
 */

class Player extends Sprite {

  public static final int STATE_NORMAL = 0;

  public static final int STATE_JUMPING = 1;

  public static final float SPEED = .3f;

  public static final float GRAVITY = .002f;

  private int floorY;

  private int state;

  public Player(Animation anim) {
    super(anim);
    state = STATE_NORMAL;
  }

  /**
   * Gets the state of the Player (either STATE_NORMAL or STATE_JUMPING);
   */
  public int getState() {
    return state;
  }

  /**
   * Sets the state of the Player (either STATE_NORMAL or STATE_JUMPING);
   */
  public void setState(int state) {
    this.state = state;
  }

  /**
   * Sets the location of "floor", where the Player starts and lands after
   * jumping.
   */
  public void setFloorY(int floorY) {
    this.floorY = floorY;
    setY(floorY);
  }

  /**
   * Causes the Player to jump
   */
  public void jump() {
    setVelocityY(-1);
    state = STATE_JUMPING;
  }

  /**
   * Updates the player's positon and animation. Also, sets the Player's state
   * to NORMAL if a jumping Player landed on the floor.
   */
  public void update(long elapsedTime) {
    // set vertical velocity (gravity effect)
    if (getState() == STATE_JUMPING) {
      setVelocityY(getVelocityY() + GRAVITY * elapsedTime);
    }

    // move player
    super.update(elapsedTime);

    // check if player landed on floor
    if (getState() == STATE_JUMPING && getY() >= floorY) {
      setVelocityY(0);
      setY(floorY);
      setState(STATE_NORMAL);
    }

  }
}

/**
 * The GameAction class is an abstract to a user-initiated action, like jumping
 * or moving. GameActions can be mapped to keys or the mouse with the
 * InputManager.
 */

class GameAction {

  /**
   * Normal behavior. The isPressed() method returns true as long as the key
   * is held down.
   */
  public static final int NORMAL = 0;

  /**
   * Initial press behavior. The isPressed() method returns true only after
   * the key is first pressed, and not again until the key is released and
   * pressed again.
   */
  public static final int DETECT_INITAL_PRESS_ONLY = 1;

  private static final int STATE_RELEASED = 0;

  private static final int STATE_PRESSED = 1;

  private static final int STATE_WAITING_FOR_RELEASE = 2;

  private String name;

  private int behavior;

  private int amount;

  private int state;

  /**
   * Create a new GameAction with the NORMAL behavior.
   */
  public GameAction(String name) {
    this(name, NORMAL);
  }

  /**
   * Create a new GameAction with the specified behavior.
   */
  public GameAction(String name, int behavior) {
    this.name = name;
    this.behavior = behavior;
    reset();
  }

  /**
   * Gets the name of this GameAction.
   */
  public String getName() {
    return name;
  }

  /**
   * Resets this GameAction so that it appears like it hasn't been pressed.
   */
  public void reset() {
    state = STATE_RELEASED;
    amount = 0;
  }

  /**
   * Taps this GameAction. Same as calling press() followed by release().
   */
  public synchronized void tap() {
    press();
    release();
  }

  /**
   * Signals that the key was pressed.
   */
  public synchronized void press() {
    press(1);
  }

  /**
   * Signals that the key was pressed a specified number of times, or that the
   * mouse move a spcified distance.
   */
  public synchronized void press(int amount) {
    if (state != STATE_WAITING_FOR_RELEASE) {
      this.amount += amount;
      state = STATE_PRESSED;
    }

  }

  /**
   * Signals that the key was released
   */
  public synchronized void release() {
    state = STATE_RELEASED;
  }

  /**
   * Returns whether the key was pressed or not since last checked.
   */
  public synchronized boolean isPressed() {
    return (getAmount() != 0);
  }

  /**
   * For keys, this is the number of times the key was pressed since it was
   * last checked. For mouse movement, this is the distance moved.
   */
  public synchronized int getAmount() {
    int retVal = amount;
    if (retVal != 0) {
      if (state == STATE_RELEASED) {
        amount = 0;
      else if (behavior == DETECT_INITAL_PRESS_ONLY) {
        state = STATE_WAITING_FOR_RELEASE;
        amount = 0;
      }
    }
    return retVal;
  }
}

/**
 * Simple abstract class used for testing. Subclasses should implement the
 * draw() method.
 */

abstract class GameCore {

  protected static final int FONT_SIZE = 24;

  private static final DisplayMode POSSIBLE_MODES[] {
      new DisplayMode(800600320)new DisplayMode(800600240),
      new DisplayMode(800600160)new DisplayMode(640480320),
      new DisplayMode(640480240)new DisplayMode(640480160) };

  private boolean isRunning;

  protected ScreenManager screen;

  /**
   * Signals the game loop that it's time to quit
   */
  public void stop() {
    isRunning = false;
  }

  /**
   * Calls init() and gameLoop()
   */
  public void run() {
    try {
      init();
      gameLoop();
    finally {
      screen.restoreScreen();
    }
  }

  /**
   * Sets full screen mode and initiates and objects.
   */
  public void init() {
    screen = new ScreenManager();
    DisplayMode displayMode = screen
        .findFirstCompatibleMode(POSSIBLE_MODES);
    screen.setFullScreen(displayMode);

    Window window = screen.getFullScreenWindow();
    window.setFont(new Font("Dialog", Font.PLAIN, FONT_SIZE));
    window.setBackground(Color.blue);
    window.setForeground(Color.white);

    isRunning = true;
  }

  public Image loadImage(String fileName) {
    return new ImageIcon(fileName).getImage();
  }

  /**
   * Runs through the game loop until stop() is called.
   */
  public void gameLoop() {
    long startTime = System.currentTimeMillis();
    long currTime = startTime;

    while (isRunning) {
      long elapsedTime = System.currentTimeMillis() - currTime;
      currTime += elapsedTime;

      // update
      update(elapsedTime);

      // draw the screen
      Graphics2D g = screen.getGraphics();
      draw(g);
      g.dispose();
      screen.update();

      // take a nap
      try {
        Thread.sleep(20);
      catch (InterruptedException ex) {
      }
    }
  }

  /**
   * Updates the state of the game/animation based on the amount of elapsed
   * time that has passed.
   */
  public void update(long elapsedTime) {
    // do nothing
  }

  /**
   * Draws to the screen. Subclasses must override this method.
   */
  public abstract void draw(Graphics2D g);
}

/**
 * The ScreenManager class manages initializing and displaying full screen
 * graphics modes.
 */

class ScreenManager {

  private GraphicsDevice device;

  /**
   * Creates a new ScreenManager object.
   */
  public ScreenManager() {
    GraphicsEnvironment environment = GraphicsEnvironment
        .getLocalGraphicsEnvironment();
    device = environment.getDefaultScreenDevice();
  }

  /**
   * Returns a list of compatible display modes for the default device on the
   * system.
   */
  public DisplayMode[] getCompatibleDisplayModes() {
    return device.getDisplayModes();
  }

  /**
   * Returns the first compatible mode in a list of modes. Returns null if no
   * modes are compatible.
   */
  public DisplayMode findFirstCompatibleMode(DisplayMode modes[]) {
    DisplayMode goodModes[] = device.getDisplayModes();
    for (int i = 0; i < modes.length; i++) {
      for (int j = 0; j < goodModes.length; j++) {
        if (displayModesMatch(modes[i], goodModes[j])) {
          return modes[i];
        }
      }

    }

    return null;
  }

  /**
   * Returns the current display mode.
   */
  public DisplayMode getCurrentDisplayMode() {
    return device.getDisplayMode();
  }

  /**
   * Determines if two display modes "match". Two display modes match if they
   * have the same resolution, bit depth, and refresh rate. The bit depth is
   * ignored if one of the modes has a bit depth of
   * DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one
   * of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN.
   */
  public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2)

  {
    if (mode1.getWidth() != mode2.getWidth()
        || mode1.getHeight() != mode2.getHeight()) {
      return false;
    }

    if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI
        && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI
        && mode1.getBitDepth() != mode2.getBitDepth()) {
      return false;
    }

    if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN
        && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN
        && mode1.getRefreshRate() != mode2.getRefreshRate()) {
      return false;
    }

    return true;
  }

  /**
   * Enters full screen mode and changes the display mode. If the specified
   * display mode is null or not compatible with this device, or if the
   * display mode cannot be changed on this system, the current display mode
   * is used.
   * <p>
   * The display uses a BufferStrategy with 2 buffers.
   */
  public void setFullScreen(DisplayMode displayMode) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(true);
    frame.setIgnoreRepaint(true);
    frame.setResizable(false);

    device.setFullScreenWindow(frame);

    if (displayMode != null && device.isDisplayChangeSupported()) {
      try {
        device.setDisplayMode(displayMode);
      catch (IllegalArgumentException ex) {
      }
      // fix for mac os x
      frame.setSize(displayMode.getWidth(), displayMode.getHeight());
    }
    // avoid potential deadlock in 1.4.1_02
    try {
      EventQueue.invokeAndWait(new Runnable() {
        public void run() {
          frame.createBufferStrategy(2);
        }
      });
    catch (InterruptedException ex) {
      // ignore
    catch (InvocationTargetException ex) {
      // ignore
    }

  }

  /**
   * Gets the graphics context for the display. The ScreenManager uses double
   * buffering, so applications must call update() to show any graphics drawn.
   * <p>
   * The application must dispose of the graphics object.
   */
  public Graphics2D getGraphics() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      BufferStrategy strategy = window.getBufferStrategy();
      return (Graphics2Dstrategy.getDrawGraphics();
    else {
      return null;
    }
  }

  /**
   * Updates the display.
   */
  public void update() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      BufferStrategy strategy = window.getBufferStrategy();
      if (!strategy.contentsLost()) {
        strategy.show();
      }
    }
    // Sync the display on some systems.
    // (on Linux, this fixes event queue problems)
    Toolkit.getDefaultToolkit().sync();
  }

  /**
   * Returns the window currently used in full screen mode. Returns null if
   * the device is not in full screen mode.
   */
  public JFrame getFullScreenWindow() {
    return (JFramedevice.getFullScreenWindow();
  }

  /**
   * Returns the width of the window currently used in full screen mode.
   * Returns 0 if the device is not in full screen mode.
   */
  public int getWidth() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      return window.getWidth();
    else {
      return 0;
    }
  }

  /**
   * Returns the height of the window currently used in full screen mode.
   * Returns 0 if the device is not in full screen mode.
   */
  public int getHeight() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      return window.getHeight();
    else {
      return 0;
    }
  }

  /**
   * Restores the screen's display mode.
   */
  public void restoreScreen() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      window.dispose();
    }
    device.setFullScreenWindow(null);
  }

  /**
   * Creates an image compatible with the current display.
   */
  public BufferedImage createCompatibleImage(int w, int h, int transparancy) {
    Window window = device.getFullScreenWindow();
    if (window != null) {
      GraphicsConfiguration gc = window.getGraphicsConfiguration();
      return gc.createCompatibleImage(w, h, transparancy);
    }
    return null;
  }
}

/**
 * The InputManager manages input of key and mouse events. Events are mapped to
 * GameActions.
 */

class InputManager implements KeyListener, MouseListener, MouseMotionListener,
    MouseWheelListener {
  /**
   * An invisible cursor.
   */
  public static final Cursor INVISIBLE_CURSOR = Toolkit.getDefaultToolkit()
      .createCustomCursor(Toolkit.getDefaultToolkit().getImage(""),
          new Point(00)"invisible");

  // mouse codes
  public static final int MOUSE_MOVE_LEFT = 0;

  public static final int MOUSE_MOVE_RIGHT = 1;

  public static final int MOUSE_MOVE_UP = 2;

  public static final int MOUSE_MOVE_DOWN = 3;

  public static final int MOUSE_WHEEL_UP = 4;

  public static final int MOUSE_WHEEL_DOWN = 5;

  public static final int MOUSE_BUTTON_1 = 6;

  public static final int MOUSE_BUTTON_2 = 7;

  public static final int MOUSE_BUTTON_3 = 8;

  private static final int NUM_MOUSE_CODES = 9;

  // key codes are defined in java.awt.KeyEvent.
  // most of the codes (except for some rare ones like
  // "alt graph") are less than 600.
  private static final int NUM_KEY_CODES = 600;

  private GameAction[] keyActions = new GameAction[NUM_KEY_CODES];

  private GameAction[] mouseActions = new GameAction[NUM_MOUSE_CODES];

  private Point mouseLocation;

  private Point centerLocation;

  private Component comp;

  private Robot robot;

  private boolean isRecentering;

  /**
   * Creates a new InputManager that listens to input from the specified
   * component.