-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snakegame-demo1
116 lines (104 loc) · 3.32 KB
/
Snakegame-demo1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<Snake>
package SnakeGame;
import java.util.LinkedList;
/**
* 创建snake类表示蛇,一条蛇有多个节点适用LinkedList集合存储Node节点,蛇生成的时候有六个节点
*/
public class Snake {
// 蛇身
private LinkedList<Node> body;
// 蛇的运动方向,默认向左
private Direction direction=Direction.LEFT;
// 蛇是否存货
private boolean isLiving=true;
// 构造方法,在创建Snake对象时执行
public Snake() {
// 初始化蛇身
initSnake();
}
//初始化蛇身体
private void initSnake() {
// 创建集合
body=new LinkedList<>();
// 创建n个节点添加到集合中
body.add(new Node(16,20));
body.add(new Node(17,20));
body.add(new Node(18,20));
body.add(new Node(19,20));
body.add(new Node(20,20));
body.add(new Node(21,20));
}
// 蛇会沿着蛇头的方向移动
// 控制蛇移动就是在蛇头运动方向添加一个节点,然后把蛇尾的节点删除
public void move(){
if (isLiving)
{
// 获取蛇头
Node head=body.getFirst();
switch (direction){
case UP:
// 在蛇头的上边添加节点
body.addFirst(new Node(head.getX(),head.getY()-1));
break;
case DOWN:
body.addFirst(new Node(head.getX(),head.getY()+1));
break;
case LEFT:
body.addFirst(new Node(head.getX()-1,head.getY()));
break;
case RIGHT:
body.addFirst(new Node(head.getX()+1,head.getY()));
break;
}
// 删除最后的节点
body.removeLast();
// 判断蛇是否撞墙
head=body.getFirst();
if (head.getX()<0||head.getY()<0||head.getX()>=40||head.getY()>=40)
{
isLiving=false;
}
// 判断蛇是否碰到自己的身体
for (int i=1; i<body.size();i++)
{
Node node = body.get(i);
if (head.getX()==node.getX()&&head.getY()==node.getY())
{
isLiving=false;
}
}
}
}
public LinkedList<Node> getBody() {
return body;
}
public void setBody(LinkedList<Node> body) {
this.body = body;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
// 吃食物:沿着蛇头的移动方向添加一个节点
public void eat(Node food) {
// 获取蛇头
Node head=body.getFirst();
switch (direction){
case UP:
// 在蛇头的上边添加节点
body.addFirst(new Node(head.getX(),head.getY()-1));
break;
case DOWN:
body.addFirst(new Node(head.getX(),head.getY()+1));
break;
case LEFT:
body.addFirst(new Node(head.getX()-1,head.getY()));
break;
case RIGHT:
body.addFirst(new Node(head.getX()+1,head.getY()));
break;
}
}
}