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;
int loc;
int i=20;
int j=0;
static int pointX=20;
static int pointY=20;
ArrayList list;
ArrayList array;
Thread th;
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);
}
}
}
public void paint(Graphics g)
{
super.paint(g);
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(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);
}
};
重新改了一下.终于可以用键盘顺利地控制那条蛇了,不过我怎么越看越别扭啊!总感觉少了点什么!!!!
请各位老兄指教下哈!!!!!!
----------------解决方案--------------------------------------------------------
我还是写过一个这个游戏.....
不过我想写的是网络对站版的....可是数据传输始终有错....也许我们还有共同语言...
欢迎和我交流...http://3w.skyapi.com
我的BLOG
[此贴子已经被作者于2006-6-25 5:18:43编辑过]
----------------解决方案--------------------------------------------------------
楼上的,你是不是学生呢?我也用JAVA写了几个小东西.不知道你是否想要.虽然都很简单.
还有你的蛇我没看到啊
----------------解决方案--------------------------------------------------------