主要用了这个类:import .*;import .*;@SuppressWarnings("serial")public class MainClass extends JFrame {ControlSnake control;Toolkit kit;Dimension dimen;public static void main(String[] args) {new MainClass("my snake");}public MainClass(String s) {super(s);control = new ControlSnake();(true);kit = ();dimen = ();add(control);setLayout(new BorderLayout());setLocation( / 3, / 3);// (FWIDTH, FHEIGHT);setDefaultCloseOperation();setResizable(false);setVisible(true);}public static final int FWIDTH = 315;public static final int FHEIGHT = 380;}import .*;import .*;import .*;import .*;import ;import ;@SuppressWarnings("serial")public class ControlSnake extends JPanel implements ActionListener {Random rand;ArrayList list, listBody;String str, str1;static boolean key;int x, y, dx, dy, fx, fy, flag;int snakeBody;int speed;public ControlSnake() {snakeBody = 1;str = "上下左右方向键控制 P键暂停...";str1 = "现在的长度为:" + snakeBody;key = true;flag = 1;speed = 700;rand = new Random();list = new ArrayList();listBody = new ArrayList();x = 5;y = 5;(new Point(x, y));((0));dx = 10;dy = 0;fx = (30) * 10 + 5;// 2fy = (30) * 10 + 5;// 2setBackground();setSize(new Dimension(318, 380));final Timer time = new Timer(speed, this);();addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {if (() == 37) {dx = -10;dy = 0;} else if (() == 38) {dx = 0;dy = -10;} else if (() == 39) {dx = 10;dy = 0;} else if (() == 40) {dx = 0;dy = 10;} else if (() == 80) {if (flag % 2 == 1) {();}if (flag % 2 == 0) {();}flag++;}}});}public void paint(Graphics g) {();(0, 0, 400, 400);();(3, 3, 305, 3);(3, 3, 3, 305);(305, 3, 305, 305);(3, 305, 305, 305);();for (int i = 0; i < (); i++) {((i).x, (i).y, 9, 9);}(x, y, 9, 9);();(fx, fy, 9, 9);();str1 = "现在的长度为:" + snakeBody;(str, 10, 320);(str1, 10, 335);}public void actionPerformed(ActionEvent e) {x += dx;y += dy;if (makeOut() == false) {(null, "重新开始......");speed = 700;snakeBody = 1;x = 5;y = 5;();(new Point(x, y));();((0));dx = 10;dy = 0;}addPoint(x, y);if (x == fx && y == fy) {speed = (int) (speed * );//速度增加参数if (speed < 200) {speed = 100;}fx = (30) * 10 + 5;// 2fy = (30) * 10 + 5;// 2snakeBody++;// 2} // 2repaint();}public void addPoint(int xx, int yy) {// 动态的记录最新发生的50步以内的移动过的坐标// 并画出最新的snakeBodyif (() < 100) {//蛇身长度最长为(new Point(xx, yy));} else {(0);(new Point(xx, yy));}if (snakeBody == 1) {(0);(0, (() - 1));} else {();if (() < snakeBody) {for (int i = () - 1; i > 0; i--) {((i));}} else {for (int i = () - 1; () < snakeBody; i--) {((i));}}}}public boolean makeOut() {if ((x < 3 || y < 3) || (x > 305 || y > 305)) {return false;}for (int i = 0; i < () - 1; i++) {for (int j = i + 1; j < (); j++) {if ((i).equals((j))) {return false;}}}return true;}}