import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Snake extends JFrame
{
int x,y;
int X,Y;
int loc;
int i=20;
static int pointX=20;
static int pointY=20;
ArrayList list;
ArrayList array;
public Snake()
{
Container c=getContentPane();
list=new ArrayList();
array=new ArrayList();
setSize(800,600);
x=300;y=200;
X=20;Y=30;
setLocation(x,y);
show();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void drawSnake()
{
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
loc=e.getKeyCode();
}
});
while(true){
if(X+i<750)
{
if(loc==40){list.clear();list.add(new MySnake(X+i,y));}
else
{
list.clear();
list.add(new MySnake(X+i,Y));
i=i+20;
}
try
{
Thread.sleep(300);
repaint();
}
catch (Exception e)
{
return;
}
}
else
{
JOptionPane.showMessageDialog(this,"you arg lose","error message",1);
System.exit(0);
}
}
}
public void paint(Graphics g)
{
super.paint(g);
Iterator it=list.iterator();
while(it.hasNext())
{
MySnake snake=(MySnake)it.next();
snake.drawMe(g);
}
}
public static void main(String args[])
{
Snake s=new Snake();
s.drawSnake();
}
}
class MySnake
{
int X,Y;
static int pointX=22;
static int pointY=44;
int j=0;
public MySnake(int X,int Y)
{
this.X=X;this.Y=Y;
}
public void drawMe(Graphics g)
{
g.setColor(Color.red);
g.fillRect(X,Y+pointY*j,20,20);
g.fillRect(X+pointX,Y+pointY*j,20,20);
g.fillRect(X+pointY,Y+pointY*j,20,20);
}
};
在这里我点了向下的键,为什么整个蛇都往下跑了啊?