-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.cpp
68 lines (57 loc) · 1.57 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
/**
* @file snake.cpp
* @author combofish ([email protected])
* @brief 实现蛇的类。
* @version 0.6
* @date 2021-10-16
*
* @copyright Copyright (c) 2021
*
*/
#include "snake.h"
#include "dot.h"
using namespace snake_game;
Snake::Snake(int n) {
Dot loc(160, 160);
for (int i = 0; i < n; i++) {
_locations.push_back(loc);
loc.set_x(loc.get_x() - grid_width);
}
}
const std::vector<Dot> &Snake::locations() { return _locations; }
const int Snake::length() { return _locations.size(); }
Dot Snake::move(Direction d) {
Dot first_p = _locations.front();
Dot end_p = _locations.back();
first_p.move(d);
_locations.insert(_locations.begin(), first_p);
_locations.pop_back();
return end_p;
}
bool Snake::judge_eat(Direction d, Dot p) {
Dot first_point = _locations.front();
first_point.move(d);
if (first_point == p) {
this->eat(first_point);
return true;
}
return false;
}
inline void Snake::eat(Dot p) { _locations.insert(_locations.cbegin(), p); }
bool Snake::judge_collision(Direction d) {
Dot first_point = _locations.front();
first_point.move(d);
if (first_point.get_x() < 0 ||
first_point.get_x() >= (grid_width_num * grid_width))
return true;
if (first_point.get_y() < 0 ||
first_point.get_y() >= (grid_hight_num * grid_hight))
return true;
/* 排除最后一格。 */
for (int i = 0; i < _locations.size() - 1; i++) {
auto loc = _locations[i];
if (loc == first_point)
return true;
}
return false;
}