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,canGo,canRun;
int loc;
int i=20;
int j=0;
static int pointX=20;
static int pointY=20;
ArrayList list;
ArrayList array;
Thread th;
MySnake ms=new MySnake();
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);
}
canGo();
}
}
public void canGo()
{
canGo=(int)(Math.random()*350);
canRun=(int)(Math.random()*250);
}
public void paint(Graphics g)
{
super.paint(g);
ms.drawFood(g,canGo,canRun);
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()
{
}
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);
}
public void drawFood(Graphics g,int foodX,int foodY)
{
g.setColor(Color.red);
g.fillRect(foodX,foodY,20,20);
}
};
请教蛇的走动和事物的出现问题!!!!!!希望各位老兄指教!!!!