手把手一步一步教你使用Java开发一个大型街机动作闯关类游戏07游戏输入管理

简介: 手把手一步一步教你使用Java开发一个大型街机动作闯关类游戏07游戏输入管理

项目源码


项目源码


输入管理

package managers;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputManager implements KeyListener {
    private static InputManager singleton = null;
    protected InputManager() {
    }
    public static InputManager getInstance() {
         if(singleton==null) {
              singleton = new InputManager();
         }
         return singleton;
    }
    private int[] keys = new int[256];
    private boolean[] key_state_up = new boolean[256];
    private boolean[] key_state_down = new boolean[256];
    private boolean keyPressed = false;
    private boolean keyReleased = false; 
    private char keyChar;
    @Override
    public void keyTyped(KeyEvent e) {
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() >= 0 && e.getKeyCode() < 256 ) {
            keys[e.getKeyCode()] = (int) System.currentTimeMillis();
            key_state_down[e.getKeyCode()] = true;
            key_state_up[e.getKeyCode()] = false;
            keyPressed = true;
            keyReleased = false;
        }
    }
    public char getKeyChar(){
        return keyChar;
    }
    public void keyReleased(KeyEvent e) {
        if( e.getKeyCode() >= 0 && e.getKeyCode() < 256 ) {
            keys[e.getKeyCode()] = 0;
            key_state_up[e.getKeyCode()] = true;
            key_state_down[e.getKeyCode()] = false;
            keyChar = e.getKeyChar();
            keyPressed = false;
            keyReleased = true;
        }
    }
    public boolean isKeyDown( int key ) {
        return key_state_down[key];
    }
    public boolean isKeyUp( int key ) {
        return key_state_up[key];
    }
    public boolean isAnyKeyDown() {
        return keyPressed;
    }
    public boolean isAnyKeyUp() {
        return keyReleased;
    }
    public void update() {
        key_state_up = new boolean[256];
        keyReleased = false;
    }
}

InputManager类实现KeyListener接口,监听keyPressed键按下事件和keyReleased键释放事件。

接下来我们在game主循环中就可以调用isKeyDown和isKeyUp方法来查询是否某个键被按下或释放。并且我们在每一次游戏循环中

都需要调用update方法重新分配key_state_up数组,这样可以保证每次循环最多检测到一次isKeyUp。

下面是一个测试类。


InputManager测试类

package main;
import managers.InputManager;
import java.awt.*;
import java.awt.event.*;
/**
 * This is just a simple test example for the input manager snippet. It is
 * just a simple frame and a threaded loop that runs about every 16 milliseconds
 * or so which is 62.5 times per second.
 */
public class InputManagerTest extends Frame implements Runnable {
    // The test input manager
    private final InputManager input;
    // Used to only start the looping thread once.
    private boolean             isTestLoopRunning   = false;
    /**
     * Add the InputManager as the KeyListener to the Frame.
     */
    public InputManagerTest() {
        input = InputManager.getInstance();
        this.addKeyListener(input);
        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent e) {
                startTestLoop();
            }
        });
    }
    /**
     * Starts a new thread using this class as the Runnable instance for that
     * thread.
     */
    public void startTestLoop() {
        //only want to run once.
        if (!isTestLoopRunning) {
            (new Thread(this)).start();
            isTestLoopRunning = true;
        }
    }
    /**
     * The meat of the test to check and make sure the input manager is working
     * correctly.
     */
    @Override
    public void run() {
        System.out.println("Start Test Loop");
        //use this to test how many times the loop detects a key is down
        int count = 0;
        //run while the frame is showing
        while (this.isShowing()) {
            // run test cases
            if (input.isAnyKeyDown()) {
                System.out.println("Some key is down");
            }
            if (input.isAnyKeyUp()) {
                System.out.println("Some key is up");
            }
            if(input.isKeyDown(KeyEvent.VK_SPACE)) {
                ++count;
                System.out.println("Spacebar is down");
            }
            if(input.isKeyUp(KeyEvent.VK_SPACE)) {
                System.out.println("Spacebar is up");
                System.out.format("Spacebar detected down %d times\n", count);
                count = 0; //reset the counter
            }
            input.update();
            try {
                Thread.sleep(16);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // just do a constant 16 milliseconds
        }
        System.out.println("End Test Loop");
    }
    /**
     * Main method to use to run the test from, it creates a basic awt frame and
     * displays the frame.
     * 
     * @param args Command line arguments.
     */
    public static void main(String[] args) {
        final Frame frame = new InputManagerTest(); //create our test class.
        // set a default size for the window, basically just give it some area.
        frame.setSize(640, 480);
        frame.setLocationRelativeTo(null); // centers window on screen
        // Need to add this to handle window closing events with the awt Frame.
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                frame.setVisible(false);
                frame.dispose();
                System.exit(0);
            }
        });
        // show the frame
        frame.setVisible(true);
    }
}

该类不详细解释了,执行InputManagerTest,按一下空格键,得到以下输出:

Start Test Loop
Some key is down
Spacebar is down
Some key is down
Spacebar is down
Some key is down
Spacebar is down
Some key is down
Spacebar is down
Some key is down
Spacebar is down
Some key is down
Spacebar is down
Some key is up
Spacebar is up
Spacebar detected down 6 times
End Test Loop
Process finished with exit code 0

为什么检测到多次isKeyDown事件,而只有一次isKeyUp事件?

注意上面

input.update();


每次循环我们都会调用InputManager的update方法,重新分配key_state_up数组。

我们按下空格键这个短暂的时间,主循环循环了多次,但因为每次我们都重新分配了key_state_up数组,

故检测到多次isKeyDown事件,而只有一次isKeyUp事件。


目录
相关文章
|
20小时前
|
消息中间件 Java 中间件
如何在Java项目中实现分布式事务管理
如何在Java项目中实现分布式事务管理
|
20小时前
|
存储 安全 Java
基于Java的区块链数字身份认证系统设计与开发
基于Java的区块链数字身份认证系统设计与开发
|
23小时前
|
Java
类信息的“隐形守护者”:JAVA反射技术全揭秘
【7月更文挑战第1天】Java反射技术是动态获取类信息并操作对象的强大工具。它基于Class对象,允许在运行时创建对象、调用方法和改变字段。例如,通过`Class.forName()`动态实例化对象,`getMethod()`调用方法。然而,反射可能破坏封装,影响性能,并需处理异常,故使用时需谨慎。它是Java灵活性的关键,常见于框架设计中。
6 0
|
23小时前
|
消息中间件 监控 Java
Java中的微服务架构:设计、部署与管理
Java中的微服务架构:设计、部署与管理
|
1天前
|
Java 容器
Java中使用Optional类的建议
Java中使用Optional类的建议
|
1天前
|
存储 安全 Java
Java详解 : 单列集合 | 双列集合 | Collections类
Java详解 : 单列集合 | 双列集合 | Collections类
|
1天前
|
Java 索引
Java实现扑克牌游戏 | 随机发牌 ( 过程拆分详解+完整代码 )
Java实现扑克牌游戏 | 随机发牌 ( 过程拆分详解+完整代码 )
|
1天前
|
Java
Java中的Object类 ( 详解toString方法 | equals方法 )
Java中的Object类 ( 详解toString方法 | equals方法 )
|
1天前
|
安全 Java 索引
带你快速掌握Java中的String类和StringBuffer类(详解常用方法 | 区别 )
带你快速掌握Java中的String类和StringBuffer类(详解常用方法 | 区别 )
|
1天前
|
Java 索引
Java中的Arrays类
Java中的Arrays类