#include <LedControl.h>
// MAX7219 Pins: DIN, CLK, CS (LOAD)
LedControl lc = LedControl(11, 13, 10, 1);
// Joystick Pins
const int VRx = A0;
const int VRy = A1;
const int SW = 2;
// Controlled dot position
int playerX = 3;
int playerY = 3;
// Random dot position
int foodX = 5;
int foodY = 5;
// Timing
unsigned long lastMoveTime = 0;
unsigned long lastBlinkTime = 0;
const int moveDelay = 150;
const int blinkDelay = 500;
// Dead zone for joystick
const int deadZone = 100;
// Blink state
bool foodVisible = true;
void setup() {
lc.shutdown(0, false);
lc.setIntensity(0, 8);
lc.clearDisplay(0);
pinMode(VRx, INPUT);
pinMode(VRy, INPUT);
pinMode(SW, INPUT_PULLUP);
randomSeed(analogRead(0)); // Seed random for food
spawnFood();
}
void loop() {
// Handle joystick movement
if (millis() - lastMoveTime > moveDelay) {
int xVal = analogRead(VRx);
int yVal = analogRead(VRy);
if (xVal < (512 - deadZone)) playerX--;
else if (xVal > (512 + deadZone)) playerX++;
if (yVal < (512 - deadZone)) playerY++;
else if (yVal > (512 + deadZone)) playerY--;
// Wrap around edges
playerX = (playerX + 8) % 8;
playerY = (playerY + 8) % 8;
lastMoveTime = millis();
}
// Handle blinking of food
if (millis() - lastBlinkTime > blinkDelay) {
foodVisible = !foodVisible;
lastBlinkTime = millis();
}
// Check collision
if (playerX == foodX && playerY == foodY) {
spawnFood();
foodVisible = true;
delay(200); // Prevent rapid re-collection
}
// Draw everything
lc.clearDisplay(0);
lc.setLed(0, playerY, playerX, true); // Controlled dot
if (foodVisible) {
lc.setLed(0, foodY, foodX, true); // Blinking dot
}
delay(10); // Small delay to avoid flickering
}
void spawnFood() {
do {
foodX = random(0, 8);
foodY = random(0, 8);
} while (foodX == playerX && foodY == playerY); // Don't spawn on player
}