import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
public class Snake {
private LinkedList<Node> list=new LinkedList<>();
private Node n = new Node(20, 30, Direction.Left);
private long lastTime;
private boolean isDead=false;
private Node head=null;
private Yard y;
float speed=2;
//构造器
public Snake(Yard y){
for(int i=0;i<2;i++) {
list.addFirst(n);
}
this.y = y;
if(list!=null){
head=list.getFirst();
}
}
//行走时在头部创建一个方块对象
public void addToHead(){
Node node=null;
switch(head.dir) {
case Left:
node = new Node(head.row, head.col - 1, head.dir);
break;
case Up:
node = new Node(head.row - 1, head.col, head.dir);
break;
case Right:
node = new Node(head.row, head.col + 1, head.dir);
break;
case Down:
node = new Node(head.row + 1, head.col, head.dir);
break;
}
list.addFirst(node);
head=list.getFirst();
}
//行走时把后面的尾巴删除
private void deleteFromTail(){
if(list.size()==0) return;
list.removeLast();
}
//检测贪吃蛇是否撞到了墙或是否撞到了自己如果撞到了就会gameOver
private void checkDead(){
//是否撞墙
if(head.row < 3 || head.col <1 || head.row > Config.ROWS-1 || head.col >Config.COLS-2) {
y.stop();
isDead=true;
}
//是否撞了自己
for(Node n:list){
if(head.row==n.row&&head.col==n.col){
if(n==list.getFirst()) continue;
y.stop();
isDead=true;
}
}
}
//以上三个方法组合成了蛇的移动的方法
//贪吃蛇移动的方法
private void move(){
long current = System.currentTimeMillis();
if (current - lastTime < 1000/speed) {
return ;
}
else {
lastTime = current;
}
checkDead();
if(!isDead) {
addToHead();
deleteFromTail();
}
}
//画蛇
public void draw(Graphics g){
if(list.size()==0) return;
move();
for(Node n: list){
n.draw(g);
}
}
//返回蛇头部的小方块
private Rectangle getRect() {
return new Rectangle(Config.BLOCK_SIZE * head.col, Config.BLOCK_SIZE * head.row, head.w, head.h);
}
//蛇吃蛋的方法
public void eat(Egg e){
if(this.getRect().intersects(e.getRect())){
e.reAppear();
this.addToHead();
//吃掉之后加分数
y.setScore(y.getScore()+5);
this.speed= (float) (speed+0.5);
}
}
//通过键盘来控制蛇的方向
public void keyPressed(KeyEvent e){
int key=e.getKeyCode();
switch(key) {
case KeyEvent.VK_LEFT :
if(head.dir != Direction.Right)
head.dir = Direction.Left;
break;
case KeyEvent.VK_UP :
if(head.dir != Direction.Down)
head.dir = Direction.Up;
break;
case KeyEvent.VK_RIGHT :
if(head.dir != Direction.Left)
head.dir = Direction.Right;
break;
case KeyEvent.VK_DOWN :
if(head.dir != Direction.Up)
head.dir = Direction.Down;
break;
}
}
}
最近下载更多
jiemomo LV12
2023年10月19日
baihaushu LV1
2023年6月13日
493240689 LV3
2023年5月11日
不正经的90后程序猿 LV1
2022年12月23日
微信网友_6258245891903488 LV7
2022年12月12日
neverthepoint LV1
2022年11月22日
小野猪ayu LV1
2022年10月25日
的还是看哈 LV3
2022年6月10日
bigtreemin LV6
2022年5月21日
小明pussabcd LV1
2022年5月16日
最近浏览更多
我真没招了 LV1
11月21日
鲁一宇 LV5
2024年12月24日
13133117021 LV5
2024年12月23日
MQ-EQW
2024年12月20日
暂无贡献等级
LeeLeo
2024年12月4日
暂无贡献等级
hoictas LV2
2024年11月26日
1220261962d
2024年10月15日
暂无贡献等级
三角阀 LV4
2024年7月13日
zr20050503 LV2
2024年6月27日
long123_356 LV8
2024年6月22日

