-
Notifications
You must be signed in to change notification settings - Fork 0
/
Food.java
50 lines (39 loc) · 998 Bytes
/
Food.java
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
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Food {
private Point pt;
private List<Point> snake;
private int l;
private int w;
public Food(Snake s, int l, int w) {
snake = s.getList();
this.l = l;
this.w = w;
}
//determines the food's point, ensures that it doesn't overlap with snake
public void changePos() {
int x = getRandomX();
int y = getRandomY();
boolean takenX = true;
boolean takenY = true;
ListIterator<Point> it = snake.listIterator();
while (it.hasNext() && !takenX && !takenY) {
Point p = it.next();
if (x != p.getX()) takenX = false;
else x = getRandomX();
if (y != p.getY()) takenY = false;
else y = getRandomY();
}
pt = new Point(x, y);
}
public int getRandomX() {
return (int)(Math.random() * l);
}
public int getRandomY() {
return (int)(Math.random() * w);
}
public Point getPoint() {
return pt;
}
}