(VIDEO) Troubleshoot “Ghosting” of LEDs in Snake Game
“Setup”
Latest Arduino IDE
Arduino Uno
SK6812 NeoPixel RGB LEDs
I am trying to recreate “snake game” but sometimes when the snake eats the fruit, LEDs light up that should not light up. I cannot tell why. Also, something is wrong with my makeFruit() function because it generates “fruit” on LEDs that are already taken by the snake.
Any help/feedback is very appreciated.
Thanks,
https://github.com/JendoRiot/SnakeGame/blob/master/FullCode
Your fruitspaceavailable is one source of problems - you don’t need the nested for loops over the game area in there, it would be enough to do:
boolean fruitSpaceAvailable( int a, int b) {
If(a == HEAD_POSITION_X && b == HEAD_POSITION_Y) { return false; }
for(int i = 0; i < SNAKE_BODY_LENGTH; i++) {
If( a == SNAKE_BODY_X[i] && b == SNAKE_BODY_Y[i]) {
return false;
}
}
return true;
}
Also, at the beginning of your logic function, you should always move snake body length + 1 elements, to account for the possibility that the snake might get 1 longer. Also you can simplify the logic greatly by going backwards:
for( int x = SNAKE_BODY_LENGTH; x > 0; x—) {
SNAKE_BODY_X[x] = SNAKE_BODY_X[x-1];
SNAKE_BODY_Y[x] = SNAKE_BODY_Y[x-1];
}
SNAKE_BODY_X[0] = HEAD_POSITION_X;
SNAKE_BODY_Y[0] = HEAD_POSITION_Y;
Finally, in your draw function, you don’t need the for loops over the game area - you can just set the leds directly:
void Draw() {
leds[XY0(HEAD_POSITION_X, HEAD_POSITION_Y)] = CRGB::SNAKE_HEAD_COLOR; // sets LED for HEAD
leds[XY0(fruitX, fruitY)] = CRGB::FRUIT_COLOR; // sets LED for Fruit
for (int k = 0; k < SNAKE_BODY_LENGTH; k++)
{
leds[XY0(SNAKE_BODY_X[k], SNAKE_BODY_Y[k])] = CRGB::SNAKE_BODY_COLOR; // sets LEDs for Snake Body
}
FastLED.show();
So your comments fixed my issues!!! Thank you! I still don’t understand where the “ghost” LEDs were coming from but I appreciate it greatly!!! Thank you very much @Daniel_Garcia
@Daniel_Garcia “at the beginning of your logic function, you should always move snake body length + 1 elements, to account for the possibility that the snake might get 1 longer”
Can you elaborate? I don’t understand the possibility of the snake getting 1 longer.