#include <MD_MAX72xx.h>
#include <ezButton.h>
const byte cs_pin = 10;
const byte max_dev = 1;
const byte hpin = A0;
const byte vpin = A1;
ezButton button(8);
MD_MAX72XX matrix = MD_MAX72XX(MD_MAX72XX::PAROLA_HW, cs_pin, max_dev);
int snake_x[64] = { 3 };
int snake_y[64] = { 3 };
int head_x = 4;
int head_y = 3;
int snake_len = 1;
int food_x = random(8);
int food_y = random(8);
long int currentTime, prevTime = 0;
int threshold = 100;
String direction = "", prev_direction = "";
int max_x = 7, max_y = 7;
int game_state = 0;
void setup() {
Serial.begin(9600);
button.setDebounceTime(25);
matrix.begin();
matrix.clear();
showMsg("Welcome");
delay(100);
}
void loop() {
if (game_state == 0) {
check_direction();
food_eat_check();
currentTime = millis();
if (currentTime - prevTime >= threshold) {
prevTime = currentTime;
matrix.clear();
move_sprite();
update_snake();
draw_sprites();
}
collision_check();
} else if (game_state == 1) {
showMsg("You Win");
restart();
} else if (game_state == 2) {
showMsg("Game Over");
restart();
}
}
void restart() {
while (1) {
button.loop();
if (button.isPressed()) {
snake_len = 1;
head_x = 4;
head_y = 3;
threshold = 100;
direction, prev_direction = "";
for (int i = 0; i < 64; i++) {
snake_x[i], snake_y[i] = 0;
}
game_state = 0;
break;
}
}
}
void animate() {
int i = 0;
while (i < 3) {
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
matrix.setPoint(x, y, true);
}
}
delay(50);
matrix.clear();
delay(50);
i++;
}
}
void showMsg(char msg[]) {
animate();
int i = 0;
while (msg[i] != '\0') {
matrix.setChar(6, msg[i]);
delay(50);
matrix.clear();
delay(50);
i++;
}
}
void window_check() {
if (head_x > max_x) head_x = 0;
else if (head_x < 0) head_x = max_x;
else if (head_y > max_y) head_y = 0;
else if (head_y < 0) head_y = max_y;
}
void check_direction() {
if (analogRead(hpin) > 512 && prev_direction != "right")
direction = "left";
else if (analogRead(hpin) < 512 && prev_direction != "left")
direction = "right";
else if (analogRead(vpin) > 512 && prev_direction != "down")
direction = "up";
else if (analogRead(vpin) < 512 && prev_direction != "up")
direction = "down";
prev_direction = direction;
}
void move_sprite() {
if (direction == "left") head_x++;
else if (direction == "right") head_x--;
else if (direction == "up") head_y--;
else if (direction == "down") head_y++;
window_check();
}
void draw_sprites() {
matrix.setPoint(food_y, food_x, true);
for (int i = 0; i < snake_len; i++) {
matrix.setPoint(snake_y[i], snake_x[i], true);
}
}
void collision_check() {
for (int i = 1; i < snake_len; i++) {
if (snake_x[i] == head_x && snake_y[i] == head_y) {
game_state = 2;
}
}
}
void food_eat_check() {
if (food_x == head_x && food_y == head_y) {
food_x = random(8);
food_y = random(8);
snake_len++;
if (snake_len > 15) {
game_state = 1;
}
}
}
void update_snake() {
for (int i = snake_len; i >= 0; i--) {
if (i != 0) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
} else {
snake_x[i] = head_x;
snake_y[i] = head_y;
}
}
}