pitrix/src/effect_snake.cpp

65 lines
1.6 KiB
C++

#include "effect_snake.h"
#include "functions.h"
SnakeEffect::SnakeEffect() {
this->coords = {0, 0};
this->window = new Window(0, 0, LED_WIDTH, LED_HEIGHT-6);
}
SnakeEffect::~SnakeEffect() {
delete window;
}
void SnakeEffect::loop() {
if (run++ % EFFECT_SNAKE_SLOWDOWN == 0) { // Change the coordinates only on every n-th run.
if (random8(EFFECT_SNAKE_DIRECTION_CHANGE)==0 || is_turn_needed()) turn_random();
this->coords = update_position(this->coords, this->direction);
}
window->fadeToBlackBy(2);
CRGB color(CHSV(hue, 200, 255));
window->setPixel(this->coords.x, this->coords.y, &color);
hue++;
}
void SnakeEffect::turn_random() {
if ((random8() & 1) == 0) {
turn_right() || turn_left();
} else {
turn_left() || turn_right();
}
}
bool SnakeEffect::turn_left() {
if (!is_direction_okay(this->direction - 1)) return false;
this->direction--;
return true;
}
bool SnakeEffect::turn_right() {
if (!is_direction_okay(this->direction + 1)) return false;
this->direction++;
return true;
}
bool SnakeEffect::is_turn_needed() {
return !is_direction_okay(this->direction);
}
bool SnakeEffect::is_direction_okay(uint8_t dir) {
Coords c = update_position(this->coords, dir);
return c.x<window->width && c.y<window->height;
}
Coords SnakeEffect::update_position(Coords original, uint8_t direction) {
direction = direction % 4;
if (direction == 0) original.y--;
else if (direction == 1) original.x++;
else if (direction == 2) original.y++;
else if (direction == 3) original.x--;
return original;
}
boolean SnakeEffect::can_be_shown_with_clock() { return true; }