键盘动作监听器

发布于 2024-11-27 06:42:13 字数 4153 浏览 0 评论 0原文

我试图让我的游戏中的太空飞船(PlayerShip.gif)在按下相应的键时向左、向右、向上和向下移动。我知道我需要一个键盘监听器,但我在弄清楚它去哪里以及它实际上是如何实现时遇到问题。我的代码如下。

public class GamePanel extends JPanel implements KeyListener {

    Timer timer1;
    Timer timer2;
    ArrayList<Ships> ship;
    int x;
    int y;
    double speed;
    int size;
    int shipxCoord;
    int shipyCoord;
    int shipHeight;
    int shipWidth;
    int shipRise;
    int shipRun;
    boolean left = false;
    boolean right = false;
    boolean up = false;
    boolean down = false;
    Image enemyShip1;
    Image enemyShip2;
    Image playerShip;
    ImageIcon ic = new ImageIcon("Ship.gif");
    ImageIcon ic2 = new ImageIcon("Ship2.gif");
    int width = ic.getIconWidth();
    int height = ic.getIconHeight();
    Image background = Toolkit.getDefaultToolkit().createImage("background.jpg");

    public GamePanel(int size, double speed) {
        super();

        x = 450;
        y = 510;
        ship = new ArrayList<Ships>();
        // call timer for 1st type of enemy Ship with a delay of 5 seconds between ships
        enemy1Timer(5);
        // call timer for 2nd type of enemy Ship with a delay of 3 seconds between ships
        enemy2Timer(3);
        this.size = size;
        this.speed = speed;
        enemyShip1 = new ImageIcon("ship.gif").getImage();
        enemyShip2 = new ImageIcon("ship2.gif").getImage();
        playerShip = new ImageIcon("playerShip.gif").getImage();
        //  this.add(image);
    } // end constructor

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(background, 0, 0, null);
        for (Ships s : ship) {
            s.paintComponent(g);
        }

        g.drawImage(playerShip, x, y, this);

        //g.drawImage(enemyShip2,x,y,this);
    }// end method paintComponent

    public void move() {
        for (Ships s : ship) {
            s.moveship(this);
            // s.detectCollision(ship);
        }
        if (left) {
            x -= speed;
        }
        if (right) {
            x += speed;
        }
        if (up) {
            y -= speed;
        }
        if (down) {
            y += speed;
        }

        if (x > getWidth() - size) {
            x = getWidth() - size;
        }

        if (x < 0) {
            x = 0;
        }

        if (y > getHeight() - size) {
            y = getHeight() - size;
        }
        if (y < 0) {
            y = 0;
        }
    }// end method move

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
            left = true;

        }
        if (e.getKeyCode() == e.VK_RIGHT) {
            right = true;
        }
        if (e.getKeyCode() == e.VK_UP) {
            up = true;
        }
        if (e.getKeyCode() == e.VK_DOWN) {
            down = true;
        }

    } // end method keyPressed

    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
            left = false;
        }
        if (e.getKeyCode() == e.VK_RIGHT) {
            right = false;
        }
        if (e.getKeyCode() == e.VK_UP) {
            up = false;
        }
        if (e.getKeyCode() == e.VK_DOWN) {
            down = false;
        }
    }

    public void enemy1Timer(int seconds) {
        timer1 = new Timer();
        timer1.schedule(new ShipSwarm1(), 1000, seconds * 1000);
    }// end method enemy1Timer

    class ShipSwarm1 extends TimerTask {

        public void run() {
            for (int Wave = 1; Wave > 0; Wave--) {
                Ships enemy = new Ships(ic, enemyShip1);
                ship.add(enemy);
            }// end for
        }// end method run
    }// end class Enemy1Swarm

    public void enemy2Timer(int seconds) {
        timer2 = new Timer();
        timer2.schedule(new ShipSwarm2(), 3000, seconds * 1000);
    }// end method enemy1Timer

    class ShipSwarm2 extends TimerTask {

        public void run() {
            for (int Wave = 1; Wave > 0; Wave--) {
                Ships enemy = new Ships(ic2, enemyShip2);
                ship.add(enemy);
            }// end for
        }// end method run
    }
}

I am trying to make a space ship (PlayerShip.gif) in my game move left, right, up, and down when the coresponding keys are pressed. I know i need an keyboardListener but im having issues figuring out where it goes and how it is actually implimented. my code is as follows.

public class GamePanel extends JPanel implements KeyListener {

    Timer timer1;
    Timer timer2;
    ArrayList<Ships> ship;
    int x;
    int y;
    double speed;
    int size;
    int shipxCoord;
    int shipyCoord;
    int shipHeight;
    int shipWidth;
    int shipRise;
    int shipRun;
    boolean left = false;
    boolean right = false;
    boolean up = false;
    boolean down = false;
    Image enemyShip1;
    Image enemyShip2;
    Image playerShip;
    ImageIcon ic = new ImageIcon("Ship.gif");
    ImageIcon ic2 = new ImageIcon("Ship2.gif");
    int width = ic.getIconWidth();
    int height = ic.getIconHeight();
    Image background = Toolkit.getDefaultToolkit().createImage("background.jpg");

    public GamePanel(int size, double speed) {
        super();

        x = 450;
        y = 510;
        ship = new ArrayList<Ships>();
        // call timer for 1st type of enemy Ship with a delay of 5 seconds between ships
        enemy1Timer(5);
        // call timer for 2nd type of enemy Ship with a delay of 3 seconds between ships
        enemy2Timer(3);
        this.size = size;
        this.speed = speed;
        enemyShip1 = new ImageIcon("ship.gif").getImage();
        enemyShip2 = new ImageIcon("ship2.gif").getImage();
        playerShip = new ImageIcon("playerShip.gif").getImage();
        //  this.add(image);
    } // end constructor

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(background, 0, 0, null);
        for (Ships s : ship) {
            s.paintComponent(g);
        }

        g.drawImage(playerShip, x, y, this);

        //g.drawImage(enemyShip2,x,y,this);
    }// end method paintComponent

    public void move() {
        for (Ships s : ship) {
            s.moveship(this);
            // s.detectCollision(ship);
        }
        if (left) {
            x -= speed;
        }
        if (right) {
            x += speed;
        }
        if (up) {
            y -= speed;
        }
        if (down) {
            y += speed;
        }

        if (x > getWidth() - size) {
            x = getWidth() - size;
        }

        if (x < 0) {
            x = 0;
        }

        if (y > getHeight() - size) {
            y = getHeight() - size;
        }
        if (y < 0) {
            y = 0;
        }
    }// end method move

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
            left = true;

        }
        if (e.getKeyCode() == e.VK_RIGHT) {
            right = true;
        }
        if (e.getKeyCode() == e.VK_UP) {
            up = true;
        }
        if (e.getKeyCode() == e.VK_DOWN) {
            down = true;
        }

    } // end method keyPressed

    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
            left = false;
        }
        if (e.getKeyCode() == e.VK_RIGHT) {
            right = false;
        }
        if (e.getKeyCode() == e.VK_UP) {
            up = false;
        }
        if (e.getKeyCode() == e.VK_DOWN) {
            down = false;
        }
    }

    public void enemy1Timer(int seconds) {
        timer1 = new Timer();
        timer1.schedule(new ShipSwarm1(), 1000, seconds * 1000);
    }// end method enemy1Timer

    class ShipSwarm1 extends TimerTask {

        public void run() {
            for (int Wave = 1; Wave > 0; Wave--) {
                Ships enemy = new Ships(ic, enemyShip1);
                ship.add(enemy);
            }// end for
        }// end method run
    }// end class Enemy1Swarm

    public void enemy2Timer(int seconds) {
        timer2 = new Timer();
        timer2.schedule(new ShipSwarm2(), 3000, seconds * 1000);
    }// end method enemy1Timer

    class ShipSwarm2 extends TimerTask {

        public void run() {
            for (int Wave = 1; Wave > 0; Wave--) {
                Ships enemy = new Ships(ic2, enemyShip2);
                ship.add(enemy);
            }// end for
        }// end method run
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧街凉风 2024-12-04 06:42:13

看一下这个链接,了解已实施的游戏在 Java 中,它完全符合您的要求。按键 - 上、左、右和下键。

这是著名的 15 场游戏

在此处输入图像描述

摘录,

private void processKeys(){
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
        new KeyEventDispatcher()  { 
            public boolean dispatchKeyEvent(KeyEvent e){
                if(e.getID() == KeyEvent.KEY_PRESSED){
                    handleKeyPress(e.getKeyCode());
                    if(areThingsInPlace() && !dialogShown){
                        dialogShown = true;
                        JOptionPane.showMessageDialog(null,"Congratulations!!! YOU WIN!!");
                        System.exit(1);
                    }
                }
                return false;
            } 
    });
}

用于处理箭头键的 handleKeyPress() 方法

private void handleKeyPress(int keyCode) {
    int emptyIndex = findEmptyIndex();
    int x = emptyIndex/SIZE;
    int y = emptyIndex%SIZE;

    switch (keyCode) {
    case 37://LEFT KEY
        if(y==SIZE-1) return;
        doSwap(x,y,x,y+1);
        break;
    case 38://UP KEY
        if(x==SIZE-1) return;
        doSwap(x,y,x+1,y);
        break;
    case 39://RIGHT KEY
        if(y==0) return;
        doSwap(x,y,x,y-1);
        break;
    case 40://DOWN KEY
        if(x==0) return;
        doSwap(x,y,x-1,y);
        break;
    }
}

Take a look at this link for a game impelemented in Java and it does exactly what you are looking for. Key presses - up left right and down keys.

Its the famous 15-game

enter image description here

An excerpt from that,

private void processKeys(){
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
        new KeyEventDispatcher()  { 
            public boolean dispatchKeyEvent(KeyEvent e){
                if(e.getID() == KeyEvent.KEY_PRESSED){
                    handleKeyPress(e.getKeyCode());
                    if(areThingsInPlace() && !dialogShown){
                        dialogShown = true;
                        JOptionPane.showMessageDialog(null,"Congratulations!!! YOU WIN!!");
                        System.exit(1);
                    }
                }
                return false;
            } 
    });
}

The handleKeyPress() method for handling the arrow keys

private void handleKeyPress(int keyCode) {
    int emptyIndex = findEmptyIndex();
    int x = emptyIndex/SIZE;
    int y = emptyIndex%SIZE;

    switch (keyCode) {
    case 37://LEFT KEY
        if(y==SIZE-1) return;
        doSwap(x,y,x,y+1);
        break;
    case 38://UP KEY
        if(x==SIZE-1) return;
        doSwap(x,y,x+1,y);
        break;
    case 39://RIGHT KEY
        if(y==0) return;
        doSwap(x,y,x,y-1);
        break;
    case 40://DOWN KEY
        if(x==0) return;
        doSwap(x,y,x-1,y);
        break;
    }
}
夏末的微笑 2024-12-04 06:42:13

还可以考虑添加对所有八个(半)基本方向的控制,如本游戏所示。为了获得更大的灵活性,请考虑操作键绑定,讨论<一个href="http://sites.google.com/site/drjohnbmatthews/keypad-panel" rel="nofollow">此处。

Also consider adding conrol over all eight (semi-) cardinal directions, as shown in this game. For greater flexibility, consider actions and key bindings, discussed here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文