import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Snake extends JFrame implements Runnable
{
boolean bool=false;
int x,y;
int X,Y;
int loc;
int i=20;
int j=0;
static int pointX=20;
static int pointY=20;
ArrayList list;
ArrayList array;
Thread th;
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();
th=new Thread(this);
th.start();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void run()
{
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
loc=e.getKeyCode();
}
});
while(true){
list.clear();
list.add(new MySnake(X+i,Y+j));
if(loc==39){i=i+20;bool=false;}
if(loc==37){i=i-20;;bool=false;}
if(loc==40){j=j+20;;bool=true;}
if(loc==38){j=j-20;;bool=true;}
try
{
Thread.sleep(300);
repaint();
}
catch (Exception e)
{
return;
}
if(X+i>740||X+i<0||Y+j>550||Y+j<0)
{
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();
if(bool==false)
snake.drawMe(g);
if(bool==true)
snake.drawHe(g);
}
}
public static void main(String args[])
{
new Snake();
}
}
class MySnake
{
int X,Y;
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,20,20);
g.fillRect(X+22,Y,20,20);
g.fillRect(X+44,Y,20,20);
}
public void drawHe(Graphics g)
{
g.setColor(Color.red);
g.fillRect(X,Y,20,20);
g.fillRect(X,Y+22,20,20);
g.fillRect(X,Y+44,20,20);
}
};
重新改了一下.终于可以用键盘顺利地控制那条蛇了,不过我怎么越看越别扭啊!总感觉少了点什么!!!!
请各位老兄指教下哈!!!!!!