楼主,不好意思啊.我把你的代码当中的蛇给抽出来了......
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Snake extends JFrame
{
private int sleep=400;
public int loc;
private MySnake ms;
public Snake()
{
Container c=getContentPane();
ms=new MySnake();
setSize(800,600);
setLocation(400,300);
show();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(sleep);
}
catch (Exception e)
{
return;
}
repaint();
}
}
}).start();
}
public void paint(Graphics g)
{
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
loc=e.getKeyCode();
}
});
super.paint(g);
ms.move(loc);
ms.drawMe(g);
}
public static void main(String args[])
{
new Snake();
}
}
class MySnake
{
private ArrayList list,array;
private Rectangle rec;
private int block=20;
private int bolckSpace=2;
private int j=0;
public MySnake()
{
list=new ArrayList();
array=new ArrayList();
list.add(new Rectangle(10,20,20,20));
list.add(new Rectangle(10+22,20,20,20));
list.add(new Rectangle(10+44,20,20,20));
}
public void move(int x)
{
if(x==40)
{
rec=(Rectangle)list.get(0);
Rectangle rec1=new Rectangle(rec.x,rec.y+(block+bolckSpace),rec.width,rec.height);
list.add(j,rec1);
}
else if(x==38)
{
rec=(Rectangle)list.get(0);
Rectangle rec1=new Rectangle(rec.x,rec.y-(block+bolckSpace),rec.width,rec.height);
list.add(j,rec1);
}
else if(x==37)
{
rec=(Rectangle)list.get(0);
Rectangle rec1=new Rectangle(rec.x-(block+bolckSpace),rec.y,rec.width,rec.height);
list.add(j,rec1);
}
else if(x==39)
{
rec=(Rectangle)list.get(0);
Rectangle rec1=new Rectangle(rec.x+(block+bolckSpace),rec.y,rec.width,rec.height);
list.add(j,rec1);
}
if(isEat())
{
}
else
list.remove(list.size()-1);
}
public boolean isEat()
{
return false;
}
public void drawMe(Graphics g)
{
g.setColor(Color.RED);
for(int i=0;i<list.size();i++)
{
rec=(Rectangle)list.get(i);
g.fillRect(rec.x,rec.y,rec.width,rec.height);
}
list.remove(list.size()-1);
}
};
在这句代码上:list.remove(list.size()-1);如果不用键盘控制的话,这条蛇会自动的消亡......
因为我没有1.5版本......所以我自己把你的程序抽来改去...不好意思啊.....
我不知道楼主的蛇会不会自动的消亡呢?还是用什么方法给控制了节奏.......请楼主指教下.....