I am making a Snake game with the Arduino Uno using a MAX7219 8x8 LED module and two buttons, and the wiring is correct. The game is not complete and I have not added the ability to eat fruit. You can only move the snake and change the length in the code.
The issue I have is that when the snake is longer than 2 segments and I press a button to move, it forms a rectangle with the segments as it moves along until it is in a straight line configuration.
Here is my code:
#include <LedControl.h> // library for LED module control
LedControl lc = LedControl(11, 13, 12, 1); // object to control the MAX7219 8x8 LED module (pin 11 = DIN, 12 = CS, 13 = CLK, 1 means only one module is being used)
const int rightPin = 6; // Pin for right button
const int leftPin = 7; // Pin for left button
const int MAX = 10; // Maximum snake length
int dir = 1; // direction to move in (1 = left, 2 = up, 3 = right, 4 = down)
int snakeX[MAX] = {4, 5, 6}; // snake segment X-coordinate values
int snakeY[MAX] = {4, 4, 4}; // snake segment Y-coordinate values
int snakeLen = 3; // length of the snake
void setup() {
lc.shutdown(0, false); // set up the LED module
lc.setIntensity(0, 5);
lc.clearDisplay(0);
pinMode(rightPin, INPUT_PULLUP);
pinMode(leftPin, INPUT_PULLUP);
start();
}
void loop() {
if (snakeX[0] > 7 || snakeX[0] < 0 || snakeY[0] > 7 || snakeY[0] < 0) start(); // checks if the snake's head is out of bounds
buttonRead();
snakeStep();
drawSnake();
delay(300);
lc.clearDisplay(0); // reset the LEDs
}
void start() { // restart the game
lc.clearDisplay(0);
snakeX[0] = 4;
snakeY[0] = 4;
delay(1000);
}
void buttonRead() { // read button inputs
if (digitalRead(rightPin) == LOW) {
dir++; // right button moves direction clockwise
if (dir == 5) dir = 1;
}
else if (digitalRead(leftPin) == LOW) {
dir--; // left button moves direction counterclockwise
if (dir == 0) dir = 4;
}
}
void snakeStep() { // move the snake segments without drawing them
for (int i = snakeLen - 1; i > 0; i--) { // shifts all the snake segments over
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (dir) { // change the X,Y values of the snake's head based on the direction
case 1: // left
snakeX[0]--;
break;
case 2: // up
snakeY[0]++;
break;
case 3: // right
snakeX[0]++;
break;
case 4: // down
snakeY[0]--;
break;
}
}
void drawSnake() { // draws the snake
for (int x = 0; x < snakeLen; x++) {
for (int y = 0; y < snakeLen; y++) {
lc.setLed(0, snakeX[x], snakeY[y], true); // turn on the LED at x, y
}
}
}
Please let me know how I can fix the issue described above.