我正在尝试制作 Snake 游戏。但我无法移动一个矩形框(即蛇)。很抱歉提出这样的问题!但我是java初学者,我不知道我的代码中的问题出在哪里。
class Snakexx extends JPanel implements ActionListener , KeyListener{
public static int a,b,x,y;
public int fooda,foodb;
Random rnd ;
Timer t = new Timer(1,this);
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==e.VK_UP)
{
x=0;
y=-1;
}
if(e.getKeyCode()==e.VK_LEFT)
{
x=-1;
y=0;
}
if(e.getKeyCode()==e.VK_DOWN)
{
x=0;
y=1;
}
if(e.getKeyCode()==e.VK_RIGHT)
{
x=1;
y=0;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent f){}
protected Snakexx(){
rnd = new Random();
fooda=rnd.nextInt(1300);
foodb=rnd.nextInt(300);
a=20;
b=20;
t.start();
addKeyListener(this);
setFocusable(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(a,b,10,10) ;
g.fillRect(fooda,foodb,10,10) ;
}
public void actionPerformed(ActionEvent e){
a+=x;
b+=y;
Graphics gr;
gr= new Snakexx().getGraphics();
gr.fillRect(a,b,10,10) ;
}
}
public class Snake2{
public static void main(String args[])
{
Snakexx abcd = new Snakexx();
JFrame jfrm = new JFrame("Snake Game");
jfrm.setSize(1300, 650);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
jfrm.add(abcd);
}
}