编程语言
首页 > 编程语言> > 敲代码的第九天:推箱子----使人物移动(java)

敲代码的第九天:推箱子----使人物移动(java)

作者:互联网

接前篇
for (int i = 1; i <= 10; i++) {
            panel.add(walls[index]);
            walls[index++].setBounds(0, i * 48, 48, 48);

            panel.add(walls[index]);
            walls[index++].setBounds(21 * 48, i * 48, 48, 48);
        }
        //添加事件(匿名内部类,事件处理)
        gameFrame.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }
            @Override
            public void keyPressed(KeyEvent e) {
                //System.out.println("键盘每按    一次,此方法被调用一次");
                int keyCode = e.getKeyCode();
                //System.out.println(keyCode);
                int x = 0, y = 0;
                String imgPath = "workerDown3.png";
                if (keyCode == 37 || keyCode == 65) {
                    x = -48;
                    imgPath = "workerLeft3.png";
                } else if(keyCode == 38 || keyCode == 87) {
                    y = -48;
                    imgPath = "workerUp3.png";
                } else if(keyCode == 39 || keyCode == 68) {
                    x = 48;
                    imgPath = "workerRight3.png";
                } else if(keyCode == 40 || keyCode == 83) {
                    y = 48;
                }
                for (int i = 1; i <= 48 ; i++) {
                    worker.setBounds(worker.getBounds().x + x/48, worker.getBounds().y + y/48, 48, 48);
                }

                ImageIcon workerImg = new ImageIcon("imgs/" + imgPath);
                worker.setIcon(workerImg);

            }
            @Override
            public void keyReleased(KeyEvent e) {}
        });
        //窗体可见放置在最后
        gameFrame.setVisible(true);
    }
}



标签:接前,第九天,java,箱子,int,----
来源: https://blog.csdn.net/qq_58131187/article/details/120856001