#include <LedControl.h>
#define DATA_IN 2
#define CLK 3
#define CS 4
LedControl lc = LedControl(DATA_IN, CLK, CS, 1);
const int joystickX = A0; // Joystick X-axis
const int joystickY = A1; // Joystick Y-axis
const int gridSize = 8; // 8x8 grid size
int snakeX[gridSize * gridSize]; // Snake X positions
int snakeY[gridSize * gridSize]; // Snake Y positions
int snakeLength = 1; // Initial snake length
int foodX, foodY; // Food position
int dirX = 0, dirY = 1; // Initial direction
void setup() {
lc.shutdown(0, false); // Wake up the MAX72XX
lc.setIntensity(0, 8); // Set brightness level (0 is min, 15 is max)
lc.clearDisplay(0); // Clear display register
randomSeed(analogRead(0)); // Seed for random food placement
placeFood();
}
void loop() {
readJoystick();
moveSnake();
// Draw snake
lc.clearDisplay(0);
for (int i = 0; i < snakeLength; i++) {
lc.setLed(0, snakeY[i], snakeX[i], true);
}
// Draw food
lc.setLed(0, foodY, foodX, true);
// Check for collision with food
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
placeFood();
}
delay(200); // Adjust speed
}
void readJoystick() {
int x = analogRead(joystickX);
int y = analogRead(joystickY);
if (x < 100) dirX = -1, dirY = 0; // Left
else if (x > 900) dirX = 1, dirY = 0; // Right
else if (y < 100) dirX = 0, dirY = 1; // Up (changed direction here)
else if (y > 900) dirX = 0, dirY = -1; // Down (changed direction here)
}
void moveSnake() {
for (int i = snakeLength; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] += dirX;
snakeY[0] += dirY;
// Check for wall collision
if (snakeX[0] < 0) snakeX[0] = gridSize - 1;
if (snakeX[0] >= gridSize) snakeX[0] = 0;
if (snakeY[0] < 0) snakeY[0] = gridSize - 1;
if (snakeY[0] >= gridSize) snakeY[0] = 0;
// Check for self-collision
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
snakeLength = 1; // Reset game on collision
}
}
}
void placeFood() {
foodX = random(0, gridSize);
foodY = random(0, gridSize);
}