我正在编写一个类似蛇的小游戏,并且正在实现键事件侦听器,因此它会在按下箭头键时进行侦听,它会增加或减少框架中椭圆的位置。下面是我的代码,你认为发生了什么?我尝试在谷歌上搜索可能的解决方案,但结果却是空的。
package snakegame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
/**
*
* @author PlaixHax0r
*/
public class SnakeGame extends JFrame{
int x, y;
public class ActionListener extends KeyAdapter{
public void KeyPressed(KeyEvent a){
int KeyCode = a.getKeyCode();
if(KeyCode == KeyEvent.VK_RIGHT){
x++;
}
if(KeyCode == KeyEvent.VK_LEFT){
x--;
}
if(KeyCode == KeyEvent.VK_DOWN){
y++;
}
if(KeyCode == KeyEvent.VK_UP){
y--;
}
}
public void KeyReleased(KeyEvent a){
}
}
public SnakeGame(){
addKeyListener(new ActionListener());
setTitle("Snake 1.0");
setVisible(true);
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
x=150;
y=150;
}
public void paint(Graphics g){
g.drawString("Welcome to Snake Empire", 180, 50);
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
new SnakeGame();
}
}