-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSnake.java
80 lines (72 loc) · 1.57 KB
/
Snake.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
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
public class Snake{
//fields
private int x;
private int y;
private String sound;
//constructors
public Snake(){
//x = (int) Math.floor(Math.random()*10);
//y = (int) Math.floor(Math.random()*10);
x = randomInterval(0,9);
y = randomInterval(0,9);
sound = "I'm the snake and I'm standing at ";
}
public Snake(int x0, int y0){
//x in [0;9]
if (x0<0)
x = 0;
else if (x0>9)
x = 9;
else
x = x0;
//y in [0;9]
if (y0<0)
y = 0;
else if (y0>9)
y = 9;
else
y = y0;
sound = "I'm the snake and I'm standing at ";
}
//setters and getters
public void setX(int dx){
x = dx;
}
public void setY(int dy){
y = dy;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
//move random -1, 0 or 1
public void move(){
x = x + randomInterval(-1, 1);
y = y + randomInterval(-1, 1);
//x in [0;9]
if (x<0)
x = 0;
else if (x>9)
x = 9;
//y in [0;9]
if (y<0)
y = 0;
else if (y>9)
y = 9;
}
//tell message
public void tell(){
System.out.println(sound + "(" + x + "," + y + ")");
}
//beg
public void eat(){
System.out.println("I'm hungry not much longer. Slurp!");
}
//random number in [low;high]
public int randomInterval(int low, int high){
int interval = high - low + 1;
return (int) Math.floor(Math.random() * interval) + low;
}
}