diff --git a/include/Bot.hpp b/include/Bot.hpp index 6603b37..82cd52b 100644 --- a/include/Bot.hpp +++ b/include/Bot.hpp @@ -24,14 +24,17 @@ public: if (not target_.has_value() or time_from_target_set_ >= config_.time_between_targets or - (target_.value() - real_pos_).len_sq() < radius * radius) { + (target_.value() - pos).len_sq() < radius * radius) { time_from_target_set_ = 0; - target_ = map_.find_nearest_food(real_pos_); // TODO + target_ = map_.find_nearest_food(pos); } - direction_ = (Vecf(target_.value()) - real_pos_).norm(); - // TODO: manually change direction + // check for case when no food found + if (target_.has_value()) { + direction_ = (Vecf(target_.value()) - real_pos_).norm(); + // TODO: manually change direction + } move(dt); } @@ -54,7 +57,7 @@ private: Vecf real_pos_; Vecf direction_ = {}; - std::optional target_ = {}; + std::optional target_ = {}; float time_from_target_set_ = 0; float move_time_delta_ = 0; }; diff --git a/include/Map.hpp b/include/Map.hpp index c18cc32..db1bf27 100644 --- a/include/Map.hpp +++ b/include/Map.hpp @@ -2,6 +2,7 @@ #include #include +#include #include "Canvas.hpp" #include "Utils.hpp" @@ -61,6 +62,21 @@ public: } } + std::optional find_nearest_food(Veci pos) { + if (food_.empty()) { + return std::nullopt; + } + + Veci target = food_.front().pos; + for (const auto &food : food_) { + if ((pos - food.pos).len_sq() < (pos - target).len_sq()) { + target = food.pos; + } + } + + return target; + } + private: void generate() { ++current_gen_; diff --git a/src/Snake.cpp b/src/Snake.cpp index 0c450bd..fb1f961 100644 --- a/src/Snake.cpp +++ b/src/Snake.cpp @@ -1,6 +1,6 @@ #include "Snake.hpp" -void Worm::add(Veci pos) { +void Snake::add(Veci pos) { this->pos = pos; track_.push_back(pos); if (track_.size() > length) { @@ -8,13 +8,13 @@ void Worm::add(Veci pos) { } } -void Worm::draw(Veci offset) const { +void Snake::draw(Veci offset) const { for (const auto &pos : track_) { paint::circle({{.pos = pos - offset, .color = color}, radius}); } } -bool Worm::touches(const Worm &other) { +bool Snake::touches(const Snake &other) { int dist = radius + other.radius; for (const auto &elem : other.track_) { if ((pos - elem).len_sq() < dist * dist) {