-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnake.cpp
122 lines (103 loc) · 2.05 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* snake.cpp
* snake
*
* Created by Mathieu Allaire on 11-01-23.
* Copyright 2011 mathieuallaire.ca. All rights reserved.
*
*/
#include <SFML/Graphics.hpp>
#include "snake.h"
#include "block.h"
using namespace std;
Snake::Snake(sf::RenderWindow &App)
{
_app = &App;
_direction = RIGHT;
// Draws the initial snake
_snake.push_front(Block(25,0));
_snake.push_front(Block(50,0));
}
void Snake::move(int newDirection)
{
shrink();
if(newDirection == UP)
{
if(_direction != DOWN)
{
_snake.push_front(Block(_snake.front().getX(), _snake.front().getY() - 25));
_direction = UP;
}
else
{
_snake.push_front(Block(_snake.front().getX(), _snake.front().getY() + 25));
}
}
else if(newDirection == RIGHT)
{
if(_direction != LEFT)
{
_snake.push_front(Block(_snake.front().getX() + 25, _snake.front().getY()));
_direction = RIGHT;
}
else
{
_snake.push_front(Block(_snake.front().getX() - 25, _snake.front().getY()));
}
}
else if(newDirection == DOWN)
{
if(_direction != UP)
{
_snake.push_front(Block(_snake.front().getX(), _snake.front().getY() + 25));
_direction = DOWN;
}
else
{
_snake.push_front(Block(_snake.front().getX(), _snake.front().getY() - 25));
}
}
else if(newDirection == LEFT)
{
if(_direction != RIGHT)
{
_snake.push_front(Block(_snake.front().getX() - 25, _snake.front().getY()));
_direction = LEFT;
}
else
{
_snake.push_front(Block(_snake.front().getX() + 25, _snake.front().getY()));
}
}
}
void Snake::draw()
{
for(list<Block>::iterator it = _snake.begin(); it != _snake.end(); it++)
{
float x = it->getX();
float y = it->getY();
sf::Shape block = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Red);
block.Move(x, y);
_app->Draw(block);
}
}
void Snake::grow()
{
_snake.push_back(Block(_snake.back().getX(), _snake.back().getY()));
}
void Snake::shrink()
{
_snake.pop_back();
}
list<Block> Snake::getBlocks()
{
return _snake;
}
int Snake::getX()
{
return _snake.front().getX();
}
int Snake::getY()
{
return _snake.front().getY();
}