贪吃蛇 蛇的代码
import java.awt.Point;
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.List;
import javax.swing.JButton;
/**
* 蛇
* @download
* @author Administrator
*/
public class She implements Runnable{
public She(Map map){
this.map=map;
JButton jl = new JButton();
jl.setBounds(0, 200, 5, 5);
this.body.add(jl);
this.add();
this.add();
this.add();
this.add();
}
// 身体
public List body = new ArrayList();
// 方向
private String fangXiang = "右";
/**
* 当前位置
*/
private Point touWZ;
/**
* 前一个位置
*/
private Point qianWZ;
public boolean bool=true;
/**
* 前进
*/
public void run() {
while(bool){
if(map.foods==null){return;}
qianWZ = new Point();
JButton tou = body.get(0);
// 得到当前位置
touWZ = tou.getLocation();
// 存储前一位置
qianWZ.x = touWZ.x;
qianWZ.y = touWZ.y;
// 改变头的位置
touGB(tou);
// 身体其他部位根上来
for (int i = 1; i < body.size(); i++) {
// 当前位置
touWZ = body.get(i).getLocation();
// 放到前一位置
body.get(i).setLocation(qianWZ);
// 还原前一位置
qianWZ.x = touWZ.x;
qianWZ.y = touWZ.y;
}
//看看有没东西吃
chi(lookFood());
//add();
iszq();
try {
Thread.sleep(120);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Map map;
/**
* 看看有没食物
* @param foods
* @return
*/
public List lookFood(){
return map.getFoods();
}
/**
* 改变头的位置
*/
public void touGB(JButton tou) {
if (fangXiang.equals("上")) {
touWZ.y = touWZ.y + 5;
} else if (fangXiang.equals("下")) {
touWZ.y = touWZ.y - 5;
} else if (fangXiang.equals("左")) {
touWZ.x = touWZ.x - 5;
} else if (fangXiang.equals("右")) {
touWZ.x = touWZ.x + 5;
}
// 改变头的位置
tou.setLocation(touWZ);
}
/**
* 改变头的方向
*/
public void gbFangXiang(KeyEvent e) {
if (e.getKeyCode() == 38&&(!fangXiang.equals("上"))) {
fangXiang="下";
}
if (e.getKeyCode() == 40&&(!fangXiang.equals("下"))) {
fangXiang="上";
}
if (e.getKeyCode() == 37&&(!fangXiang.equals("右"))) {
fangXiang="左";
}
if (e.getKeyCode() == 39&&(!fangXiang.equals("左"))) {
fangXiang="右";
}
}
/**
* 生长
*/
public void add(){
JButton myjl=body.get(body.size()-1);
JButton jl=new JButton();
jl.setBounds(myjl.getX(),myjl.getY(), myjl.getWidth(),myjl.getHeight());
body.add(jl);
//将新增的加入到map
map.add(jl);
}
/**
* 吃东西
*/
public void chi(List foodList){
if(foodList==null){return;}
for(int i=0;imap.getWidth()||tou.getY()<0||tou.getY()>map.get
Height()){
map.gameover();
return ;
}else{
for(int i=1;i