File size: 1,430 Bytes
8be366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
Created for Milestone 2

Group 12

Jonathan Mayer 66268081
Brian Lam 62101239
Yu Koizumi 000975171
Tommy Wong 71659011
*/

#include "Snake.hpp"

Snake::Snake(Coord starting_pos, Board* board)
{
	Node* n = new Node{nullptr, starting_pos};
	head = n;
	tail = n;
	length = 1;
	direction = RIGHT;
	this->board = board;
}

Snake::~Snake()
{
	Node* current = tail;
	Node* del = current;
	while(current != nullptr)
	{
		del = current;
		current = current->next;
		delete del;
	}
}

void Snake::update()
{
	head->next = new Node{nullptr, head->value + direction};
	head = head->next;
	int x = head->value.x;
	int y = head->value.y;
	if(x >= 0 &&y >= 0 && x < board->getLength() && y < board->getWidth())
	{
		if(board->getItem(x, y) == food) // Check for food
	  	{
			length++;
			board->setItem(x, y, empty);
			board->addItem(food);
			return;
		}
	}
	Node* temp = tail;
	tail = tail->next;
	oldTail = temp->value;
	delete temp;
}

void Snake::changeDirection(Coord direction)
{
	if(direction != -this->direction || length == 1)
		this->direction = direction;
}

Coord Snake::getHead()
{
	return head->value;
}

Coord Snake::getOldTail()
{
	return oldTail;
}

int Snake::getLength()
{
	return length;
}

std::vector<Coord> Snake::getSnakePosition()
{
	std::vector<Coord> snakeCoords{};
	Node* current = tail;
	while(current != nullptr)
	{
		snakeCoords.push_back(current->value);
		current = current->next;
	}
	return snakeCoords;
}