import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
class Snak extends KeyAdapter implements ActionListener
{
JFrame jframe=new JFrame("贪吃蛇");
Panel jpanel=new Panel();
JPanel p=new JPanel();
JLabel jlabel=new JLabel("Level:");
JLabel level=new JLabel("0");
JLabel happy=new JLabel();
JButton start=new JButton("开始");
JTextField scoreJTextField=new JTextField("00000分");
Graphics radomG;
Graphics snakG;
Graphics erasureG;
int areaX;
int areaY;
int x=0;
int y=0;
final int WIDTH=10;
int oldx=0;
int oldy=0;
int key=0;
int oldkey=38;
int xx=0;
int yy=0;
int oldxx=0;
int oldyy=0;
int dx=0;
int dy=0;
int time=5000;//随机产生格子时间差.
int maintime=200;
int lev=0;
boolean flag=false;//是否吃了一格
Vector al=new Vector();
Vector bl=new Vector();
StringBuffer sb=new StringBuffer();
String temp;
StringTokenizer st;
class Draw extends Thread
{
public void run()
{
while(true)
{
xx=(new Random().nextInt(20))*10;
yy=(new Random().nextInt(20))*10;
oldxx=xx;
oldyy=yy;
radomG.fillRect(xx,yy,WIDTH,WIDTH);
try{sleep(time);}catch(Exception e){}
erasureG.fillRect(oldxx,oldyy,WIDTH,WIDTH);
}
}
}
class DrawSnak extends Thread
{
public void run()
{
//产生初始点
x=(new Random().nextInt(20))*10;
y=(new Random().nextInt(20))*10;
//加入AL
sb.append(x+"|"+y);
al.add(sb.toString());
y+=10;
sb.append(x+"|"+y);
al.add(sb.toString());
//
tt: while(true)
{
Iterator it=al.iterator();
int i=0;
//遍历AL
while(it.hasNext())
{
//取出值
i++;
temp=(String)it.next();
st=new StringTokenizer(temp);
x=Integer.parseInt(st.nextToken("|"));
y=Integer.parseInt(st.nextToken("|"));
if(i==1)
{
//暂存
oldx=x;
oldy=y;
//方向移动
switch(oldkey)
{
case 38 :
y-=WIDTH;
if(y-WIDTH==yy&&x==xx)flag=true;
break;
case 40 :
y+=WIDTH;
if(y+WIDTH==yy&&x==xx)flag=true;
break;
case 37 :
x-=WIDTH;
if(x-WIDTH==xx&&y==yy)flag=true;
break;
case 39 :
x+=WIDTH;
if(x+WIDTH==xx&&y==yy)flag=true;
break;
default:
}
radomG=jpanel.getGraphics();
radomG.setColor(Color.RED);
//创建一个蛇线程
DrawSnak snakT=new DrawSnak();
snakT.start();
snakG=jpanel.getGraphics();
snakG.setColor(Color.darkGray);
//创建一个擦除图形
erasureG=jpanel.getGraphics();
erasureG.setColor(Color.CYAN);
jpanel.setFocusable(true);
}
}
public void keyPressed(KeyEvent ke) { key=ke.getKeyCode(); switch(key) { case 38 : if((oldkey==38)||(oldkey==40))break; else { if(dy-WIDTH==yy&&dx==xx)flag=true; oldkey=key; break; } case 40 : if((oldkey==38)||(oldkey==40))break; else { if(dy+WIDTH==yy&&dx==xx)flag=true; oldkey=key; break; } case 37 : if((oldkey==37)||(oldkey==39))break; else { if(dx-WIDTH==xx&&dy==yy)flag=true; oldkey=key; break; } case 39 : if((oldkey==37)||(oldkey==39))break; else { if(dx+WIDTH==xx&&dy==yy)flag=true; oldkey=key; break; } default: } } public static void main(String[] args) { new Snak(); } }