forked from udacity/CppND-Capstone-Snake-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.cpp
79 lines (67 loc) · 1.86 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
#include "snake.h"
#include <cmath>
#include <iostream>
void Snake::Update() {
SDL_Point prev_cell{
static_cast<int>(head_x),
static_cast<int>(
head_y)}; // We first capture the head's cell before updating.
UpdateHead();
SDL_Point current_cell{
static_cast<int>(head_x),
static_cast<int>(head_y)}; // Capture the head's cell after updating.
// Update all of the body vector items if the snake head has moved to a new
// cell.
if (current_cell.x != prev_cell.x || current_cell.y != prev_cell.y) {
UpdateBody(current_cell, prev_cell);
}
}
void Snake::UpdateHead() {
switch (direction) {
case Direction::kUp:
head_y -= speed;
break;
case Direction::kDown:
head_y += speed;
break;
case Direction::kLeft:
head_x -= speed;
break;
case Direction::kRight:
head_x += speed;
break;
}
// Wrap the Snake around to the beginning if going off of the screen.
head_x = fmod(head_x + grid_width, grid_width);
head_y = fmod(head_y + grid_height, grid_height);
}
void Snake::UpdateBody(SDL_Point ¤t_head_cell, SDL_Point &prev_head_cell) {
// Add previous head location to vector
body.push_back(prev_head_cell);
if (!growing) {
// Remove the tail from the vector.
body.erase(body.begin());
} else {
growing = false;
size++;
}
// Check if the snake has died.
for (auto const &item : body) {
if (current_head_cell.x == item.x && current_head_cell.y == item.y) {
alive = false;
}
}
}
void Snake::GrowBody() { growing = true; }
// Inefficient method to check if cell is occupied by snake.
bool Snake::SnakeCell(int x, int y) {
if (x == static_cast<int>(head_x) && y == static_cast<int>(head_y)) {
return true;
}
for (auto const &item : body) {
if (x == item.x && y == item.y) {
return true;
}
}
return false;
}