-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake.vala
63 lines (62 loc) · 1.66 KB
/
Snake.vala
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
namespace Snake {
public class Snake : Figure {
private Direction direction;
public Snake (Point tail, int length, Direction _direction) {
direction = _direction;
p_list = new GenericArray<Point?> ();
for (var i = 0; i < length; i++) {
var p = new Point.copy (tail);
p.move (i, direction);
p_list.add (p);
}
}
public void move () {
p_list.remove_index (0);
var head = new Point.copy (p_list[p_list.length - 1]);
head.move (1, direction);
p_list.add (head);
}
public bool eat_food (Point food) {
bool is_eaten;
var head = p_list[p_list.length - 1];
if (head.is_match (food)) {
food.symb = head.symb;
food.move (1, direction);
p_list.add (food);
is_eaten = true;
} else {
is_eaten = false;
}
return is_eaten;
}
public void key_handle (Gdk.EventKey key) {
Direction direction_new;
switch (key.keyval) {
case Gdk.Key.Right:
direction_new = Direction.RIGHT;
break;
case Gdk.Key.Left:
direction_new = Direction.LEFT;
break;
case Gdk.Key.Up:
direction_new = Direction.UP;
break;
case Gdk.Key.Down:
direction_new = Direction.DOWN;
break;
default:
direction_new = direction;
break;
}
if (direction == Direction.LEFT && direction_new != Direction.RIGHT) {
direction = direction_new;
} else if (direction == Direction.RIGHT && direction_new != Direction.LEFT) {
direction = direction_new;
} else if (direction == Direction.UP && direction_new != Direction.DOWN) {
direction = direction_new;
} else if (direction == Direction.DOWN && direction_new != Direction.UP) {
direction = direction_new;
}
}
}
}