-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.cpp
99 lines (88 loc) · 1.9 KB
/
segment.cpp
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
#include "segment.h"
Segment::Segment(int y, int x): row(y), col(x) {
next = nullptr;
prev = nullptr;
dir = Direction::right;
}
Segment::Segment(Segment *s) {
next = nullptr;
prev = s;
}
Segment::~Segment() {
if (next) {
delete next;
}
}
void Segment::move() {
/*
call this function on the last element.
sets row and col to that of previous, then recurses
on previous until head is reached
*/
if (!prev) {
// Is the head, move in direction dir;
switch (dir) {
case Direction::up:
row--;
break;
case Direction::down:
row++;
break;
case Direction::right:
col++;
break;
case Direction::left:
col--;
break;
}
return;
}
row = prev->row;
col = prev->col;
return prev->move();
}
Segment *Segment::grow() {
/*
call this function on any segment
faster if called on last
*/
if (next)
return next->grow();
next = new Segment(this);
return next;
}
bool Segment::up() {
if (prev)
return prev->up();
if (dir == Direction::up || dir == Direction::down)
return false;
dir = Direction::up;
return true;
}
bool Segment::down() {
if (prev)
return prev->down();
if (dir == Direction::down || dir == Direction::up)
return false;
dir = Direction::down;
return true;
}
bool Segment::left() {
if (prev)
return prev->left();
if (dir == Direction::left || dir == Direction::right)
return false;
dir = Direction::left;
return true;
}
bool Segment::right() {
if (prev)
return prev->right();
if (dir == Direction::right || dir == Direction::left)
return false;
dir = Direction::right;
return true;
}
Segment *Segment::getNext() {
return next;
}