我编写了一些代码,使用我的数字JPanel
,Wall
,Player
和Road
制作迷宫并填充Gate
。我想通过按键 W , A , S , D 来移动播放器。
框架被绘制但玩家没有移动:
Sprite[][] spr = fr.read();
int x1 = fr.row;
int y1 = fr.col;
fr.close();
GameFrame gf = new GameFrame(spr, x1, y1);
x1 = (x1 * 20) + 30;
y1 = (y1 * 20);
JFrame frame = new JFrame();
frame.setTitle("Lab");
frame.setSize(new Dimension(y1, x1));
frame.setPreferredSize(new Dimension(y1, x1));
frame.addKeyListener(gf);
frame.setFocusable(true);
frame.add(gf);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
public void paint(Graphics g) {
int a13 = 5;
int a14 = 5;
Player pl = new Player();
super.paintComponent(g);
for (int i = 0; i < i1; i++) {
for (int i0 = 0; i0 < i2; i0++) {
Sprite currentSpr1 = sprites[i][i0];
X = currentSpr1.setXCoord(i);
Y = currentSpr1.setYCoord(i0);
H = currentSpr1.setHeight();
W = currentSpr1.setWidth();
if (currentSpr1 == pl) {
addKeyListener(this);
}
currentSpr1.YourPaint(g, X, Y, H, W);
}
}
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_W) {
Y = Y - 20;
System.out.print("lol");
repaint();
}
if (c == KeyEvent.VK_S) {
Y = Y + 20;
//repaint();
}
if (c == KeyEvent.VK_D) {
X = X + 20;
//repaint();
}
if (c == KeyEvent.VK_A) {
X = X - 20;
//repaint();
}
//if (sprite instanceof Wall){
//}*/
}
答案 0 :(得分:0)
嗯,您的代码有点难以理解,但首先是:
在您的keyPressed方法中,您需要递增X或Y,但在您的更新方法中,您需要重置X和Y,因此这将无效。
那是什么样的gf?是上面的课吗?你应该添加&#34;这个&#34;作为一个keylistener。