完全自己写的小程序,主要难点在控制蛇身的运动上,已经较好的解决,不完善的地方是没有进行画面双缓冲,但刷新频率较低,所以闪烁现象较不明显。

  界面如下:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
public class SnakeClient extends Frame {
/**
* 贪吃蛇主客户端
* 蛇头可动,鸡蛋随机出现
* 0.4蛇身跟随着运动
*/
private static final long serialVersionUID = 1L;
private static int WIDTH=406,HEIGHT=428;
List<Snake> snakes=new ArrayList<Snake>();
List<Egg> eggs=new ArrayList<Egg>();
Snake s=new Snake(3,25,true,0,this);
Snake body1=new Snake(3,45,false,1,this);
Snake body2=new Snake(3,65,false,2,this);
boolean eat=false;
Egg e=new Egg();
public static void main(String []args){
SnakeClient sc=new SnakeClient();
sc.launchFrame();
}
void launchFrame(){
this.setBounds(100, 100, WIDTH, HEIGHT);
this.setVisible(true);
this.setResizable(false);
this.addWindowListener(new WinCloseMonitor());
//      bug2 :忘记加入监听,导致方向不能控制
this.addKeyListener(new KeyMonitor());
new Thread(new MyThread()).start();
snakes.add(s);
eggs.add(e);
}
class WinCloseMonitor extends WindowAdapter{
//      bug1 错把windowClosing 写成WindowClosing
//      以后重写函数时注意复制或利用Eclipse的重写功能
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
public void paint(Graphics g){
for(int i=0;i<snakes.size();i++){
Snake sn=snakes.get(i);
if(s.hitSnake(sn)&&!sn.head){
snakes.removeAll(snakes);
return;
}
sn.draw(g);
if(sn.eatEgg(e)) eat=true;
}
if(eat){
snakes.add(new Snake(snakes.get(snakes.size()-1).oldX,snakes.get(snakes.size()-1).oldY,
false,snakes.size(),this));
eat=false;
eggs.remove(e);
e=new Egg();
eggs.add(e);
}
e.draw(g);
}
class MyThread implements Runnable{
@Override
public void run() {
while(true){
repaint();
try {
Thread.sleep(350);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class KeyMonitor extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
s.keyPressed(e);
}
}
}