所以我想尝试制作像Snake这样的游戏,但我遇到了一些问题。 我想使用while循环重复moveup类中的if语句,但是 当我尝试使用KeyListener来监听向上按下向上箭头键以打破while循环时,它就像只循环一次(向上移动5个像素)。循环应该让蛇继续上升而不必多次点击,但它只移动五(我设置的值)像素。这是代码:
public class Snake extends JFrame implements KeyListener {
int ballX = 50;
int ballY = 50;
int playerX = 250;
int playerY = 250;
boolean up = false;
boolean right = false;
boolean down = false;
boolean left = true;
class DrawPane extends JPanel {
public void paintComponent(Graphics gc) {
Random rand = new Random();
int dotsX = rand.nextInt(500) + 1;
int dotsY = rand.nextInt(500) + 1;
Graphics g = this.getGraphics();
setVisible(true);
super.paintComponents(gc);
gc.setColor(Color.BLUE);
gc.fillRect(ballX, ballY, 10, 10);
gc.setColor(Color.RED);
gc.fillRect(playerX, playerY, 10, 10);
}
}
public Snake(String title) {
super(title);
JFrame frame = new JFrame();
setContentPane(new DrawPane());
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setSize(500, 500);
this.setBackground(Color.YELLOW);
this.setResizable(false);
this.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_UP) {
up = true;
right = false;
down = false;
left = false;
moveup(e);
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
up = false;
right = false;
down = true;
left = false;
movedown(e);
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
up = false;
right = true;
down = false;
left = false;
moveright(e);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
up = false;
right = false;
down = false;
left = true;
moveleft(e);
}
}
public void moveup(KeyEvent e) {
while (up) {
if (playerX < 500 || playerX > 0) {
playerX = playerX + 5;
repaint();
if (e.getKeyChar() == KeyEvent.VK_UP)
break;
}
}
}
public void moveright(KeyEvent e) {
if (playerX < 500 || playerX > 0) {
playerX = playerX + 5;
repaint();
// moveright();
}
}
public void movedown(KeyEvent e) {
if (playerY < 500 || playerY > 0) {
playerY = playerY + 5;
repaint();
// movedown();
}
}
public void moveleft(KeyEvent e) {
if (playerX < 500 || playerX > 0) {
playerX = playerX - 5;
repaint();
// moveleft();
}
}
public void snakePanel() {
JPanel panel1 = new JPanel();
panel1.setBackground(Color.red);
}
public void ActionListener() {
}
public static void main(String[] args) {
Snake r = new Snake("Snake");
}
}
答案 0 :(得分:2)
它永远不会因为休息而循环。你有效地说:
if keycode is up
loop
move up
break if keycode is up // Will always be true
更重要的是,你不应该像这样在事件处理程序中循环。事件处理程序应该快速执行并返回,否则您将阻止事件线程。应该使用计时器充当心跳并定期更新位置/重新绘制。
答案 1 :(得分:0)
请记住,您不希望将来使用Swing进行更高级的游戏。
---快速解决方案:
删除你的while()。 KeyListener接口允许您抽象&#34;的概念,当按下此键时,执行此操作&#34;。相反,当您实现界面时,您会说:&#34;只要按下此键,就执行此操作&#34;。这是一个事件。
这是您的工作代码: