-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.cpp
98 lines (90 loc) · 2.14 KB
/
snake.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
#include "snake.h"
#include <ncurses.h>
void Snake::Init() {
for (auto& point: body) {
point.Clear();
point.Circle();
}
}
void Snake::Move(Food& nfood) {
switch(direction) {
case KEY_DOWN:
body.emplace_front(body.front().getX() + 1, body.front().getY());
break;
case KEY_UP:
body.emplace_front(body.front().getX() - 1, body.front().getY());
break;
case KEY_RIGHT:
body.emplace_front(body.front().getX(), body.front().getY() + 2);
break;
case KEY_LEFT:
body.emplace_front(body.front().getX(), body.front().getY() - 2);
break;
default:
break;
}
body.back().Clear();
body.front().Circle();
if (nfood.x != body.front().getX() || nfood.y != body.front().getY()) {
body.pop_back();
} else {
nfood.RandomNum(this);
}
}
int Snake::ChangeDirection(int ch) {
switch (ch) {
case KEY_UP:
if (direction != KEY_DOWN) {
direction = ch;
}
return 2;
case KEY_DOWN:
if (direction != KEY_UP) {
direction = ch;
}
return 2;
case KEY_RIGHT:
if (direction != KEY_LEFT) {
direction = ch;
}
return 2;
case KEY_LEFT:
if (direction != KEY_RIGHT) {
direction = ch;
}
return 2;
case ERR:
return 2;
case 27:
return 0;
default:
return 1;
}
}
int Snake::getLength() {
return body.size();
}
bool Snake::HitSelf() {
for (auto& point: body) {
if (&point == &body.front()) continue;
if (point.getX() == body.front().getX()
&& point.getY() == body.front().getY()
) {
return false;
}
}
return true;
}
bool Snake::HitEdge() {
if (Head().getX() < 23
&& Head().getX() > 0
&& Head().getY() < 46
&& Head().getY() > 1
) {
return true;
}
return false;
}
Point Snake::Head() {
return body.front();
}