-
Notifications
You must be signed in to change notification settings - Fork 0
/
foodmodel.cpp
91 lines (81 loc) · 2.28 KB
/
foodmodel.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
#include "foodmodel.hpp"
#include "regularfood.hpp"
#include "superfood.hpp"
#include "meatfood.hpp"
#include "random.hpp"
#include <ctime>
FoodModel::FoodModel(const stf::Vec2d &mapSize, const size_t activeFoodCount)
: m_mapSize(mapSize),
m_possibleFoodCount(activeFoodCount)
{
m_food.resize(mapSize.x * mapSize.y, nullptr);
size_t i = 0;
while(i++ < activeFoodCount) {
m_food[i] = new RegularFood({2,2}, mapSize-2);
}
}
FoodModel::~FoodModel() {
for(size_t i = 0; i < m_food.size(); ++i) {
delete m_food[i];
}
}
const std::vector<Food *> FoodModel::getPossibleFood() const {
std::vector<Food *> possibleFood;
for(size_t i = 0; i < m_food.size(); ++i) {
if(m_food.at(i) != nullptr) {
possibleFood.push_back(m_food.at(i));
}
}
return possibleFood;
}
Food *FoodModel::nearestFood(const stf::Vec2d &pos) const {
std::vector<Food *> possibleFood = getPossibleFood();
if(possibleFood.size() == 0)
return nullptr;
Food* nearFood = possibleFood.front();
for(auto food : possibleFood) {
if(pos.diff(nearFood->pos()) > pos.diff(food->pos())) {
nearFood = food;
}
}
return nearFood;
}
void FoodModel::onUpdate()
{
if(stf::Random(time(0)).getNum(0,15) == 0) {
pasteFood<SuperFood>({ {2,2}, m_mapSize-2 });
} else {
pasteFood<RegularFood>({ {2,2}, m_mapSize-2 });
}
}
void FoodModel::remove(const Food *food) {
for(size_t i = 0; i < m_food.size(); ++i) {
if(food == m_food[i] && food != nullptr) {
delete m_food[i];
m_food[i] = nullptr;
--m_possibleFoodCount;
}
}
}
void FoodModel::reset()
{
for(size_t i = 0; i < m_food.size(); ++i) {
delete m_food[i];
m_food[i] = nullptr;
}
size_t i = 0;
while(i++ < food_model_settings::DEF_ACTIVE_FOOD_COUNT) {
m_food[i] = new RegularFood({2,2}, m_mapSize-2);
}
}
void FoodModel::pasteFoodFromDeadSnake(const std::vector<stf::Vec2d> &snakeBody) {
m_possibleFoodCount += snakeBody.size();
for(auto s : snakeBody) {
for(size_t i = 0; i < m_food.size(); ++i) {
if(m_food[i] == nullptr) {
m_food[i] = new MeatFood(s);
break;
}
}
}
}