本文主要是介绍敲代码的第九天:推箱子----使人物移动(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)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!