-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.cpp
More file actions
77 lines (66 loc) · 1.54 KB
/
Snake.cpp
File metadata and controls
77 lines (66 loc) · 1.54 KB
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
#include "Snake.h"
#include "Game.h"
#include <iostream>
Snake::Snake(Game& _game, Position start): head(new SnakeNode(start)), tail(head), game(_game), cherry(0)
{
game.snakeMoveTo(start);
}
Snake::~Snake()
{
for (SnakeNode* p = tail; p != nullptr; )
{
SnakeNode* nextNode = p->next;
delete p;
p = nextNode;
}
}
vector<Position> Snake::getPositions() const
{
vector<Position> res;
for (SnakeNode* p = tail; p != nullptr; p = p->next)
res.push_back(p->position);
return res;
}
void Snake::growAtFront(Position newPosition)
{
head->next = new SnakeNode(newPosition);
head = head->next;
}
void Snake::slideTo(Position newPosition)
{
if (tail->next == nullptr) { // snake has only one node
tail->position = newPosition;
}
else {
SnakeNode* oldTailNode = tail;
//cut the old tail off the snake
tail = tail->next;
oldTailNode->next = nullptr;
// move it to the head of the snake
oldTailNode->position = newPosition;
head->next = oldTailNode;
head = oldTailNode;
}
}
void Snake::eatCherry()
{
cherry++;
}
void Snake::move(Direction direction)
{
Position newPosition = head->position.move(direction);
game.snakeMoveTo(newPosition);
if (game.isGameOver()) return;
if (cherry > 0) {
cherry--;
growAtFront(newPosition);
}
else {
game.snakeLeave(tail->position);
slideTo(newPosition);
}
}
bool Snake::checkPosition(Position pos)
{
return false;
}