游戏开发之输入控制类测试代码

/*

 InputManager类的测试程序,其功能为使图象移动、跳动

*/

import java.awt.*;

import java.awt.event.KeyEvent;

import java.swing.ImageIcon;

import com.graphics.*;

import com.input.*;

import com.test.*;

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 run() {

        super.init();

        Window window = screen.getFullScreenWindow();

        inputManager = new InputManager(window);

       createGameAction();

      createSprite();

      paused = false;

}

public void createGameAction() {

  jump = new GameAction("jump",GameAction.DETECT_INITIAL_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);//映射暂停程序

//用空格键使动画跳动

inputManager.mapToKey(jump,VK_SPACE);

//用箭头移动动画

inputManager.mapToKey(moveLeft,KeyEvent.VK_LEFT);

inputManager.mapToKey(moveRight,KeyEvent.VK_RIGHT);

}

/*

 装入图象,生成动画PLAYER幽灵

*/

public void createSprite() {

 bgImage = loadImage(“../images/background.jpg“);

 Image player1 = loadImage(“../iamges/player1.png“);

 Image player2 = loadImage(“../iamges/player2.png“);

 //生成动画

 Aniamtion anim = new Animaiton();

 anim.addFrame(player1,200);

 anim.addFrame(player2,300);

player = new Player(anim);

player.setFloor(screen.getHeight()-player.getHeight());

}

/**

 不管游戏暂停否,检查可能按下的GameAction的输入

*/

public void checkSystemInput() {

    if(pause.isPressed()) {

       pause.setPaused(!isPause());

  }

 if(exit.isPressed()) {

   stop();

}

}

/*

 游戏不暂停下,检查可能按下的输入

*/

public void checkGameInput() {

  float velocityX = 0;

  if(moveLeft.isPressed()) {

    velocityX-=Player.SPEED;

}

if(moveRight.isPressed()) {

 velocityX+=Player.SPEED;

}

player.setVelocityX(velocityX);

if(jump.isPress() && player.getState()!=Player.STATE_JUMPING)

 {

    player.jump();

 }

}

/*

 检查游戏是否暂停

*/

public boolean isPaused() {

   return paused;

 }

/*

  设置游戏为暂停状态

*/

public void setPaused(boolean p ) {

   if (!paused==p) {

    paused = p;

    inputManager.resetAllGameActions();

}

//更新动画

 public void update(long elapsedTime) [

    //不管游戏是否暂停检查可能发生的输入

  checkSystemInput();

  if(!isPaused()) {

     checkGameInpu();

     player.update(elapsedTime);

}

}

/*

 绘制屏幕

 */

 public void draw(Graphics2D g) [

  //画背景

  gdrawImage(bgImage,0,0,null);

 //画幽灵

  g.drawImage(player.getImage(),Math.round(player.getX()),Math.round(player.getY()),null);

}

}

 

 

 

 

 

你可能感兴趣的:(JAVA游戏开发)