-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.cpp
108 lines (89 loc) · 1.55 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
#include <SDL2/SDL.h>
#include <iostream>
#include "snake.h"
#include "fruit.h"
Snake::Snake()
{
for (int i = 0; i < _size; i++)
{
_body.emplace_back();
_body.back().color = 0xffffffff;
}
}
void Snake::draw(SDL_Rect *rect, SDL_Surface *surface)
{
if (_body.size() < 1)
{
return;
}
for (Cell cell : _body)
{
rect->x = cell.x;
rect->y = cell.y;
SDL_FillRect(surface, rect, 0xffffffff);
}
}
void Snake::update(float delta)
{
if (_body.empty())
{
state = DEAD;
return;
}
if (_x + CELL_SIZE > SCREEN_SIZE) _x = 0;
if (_y + CELL_SIZE > SCREEN_SIZE) _y = 0;
if (_x < 0) _x = SCREEN_SIZE - CELL_SIZE;
if (_y < 0) _y = SCREEN_SIZE - CELL_SIZE;
for (int i = _size - 1; i > 0; i--)
{
if (_body[0].x == _body[i].x && _body[0].y == _body[i].y)
{
//state = DEAD;
//return;
}
_body[i].x = _body[i - 1].x;
_body[i].y = _body[i - 1].y;
}
_body[0].x = _x;
_body[0].y = _y;
}
void Snake::move_to(int x, int y)
{
_x = x;
_y = y;
}
void Snake::move(float delta)
{
_x += direction_x * CELL_SIZE;
_y += direction_y * CELL_SIZE;
}
const int Snake::get_speed()
{
return _speed;
}
void Snake::set_speed(int new_speed)
{
_speed = new_speed;
}
void Snake::grow(int n)
{
for (int i = 0; i < n; i++)
{
//Cell new_cell;
//new_cell.color = color;
_body.emplace_back();
}
_size += n;
}
void Snake::shrink(int n)
{
for (int i = 0; i < n; i++)
{
_body.pop_back();
}
_size -= n;
}
void Snake::restart()
{
state = ALIVE;
}