#include <MD_MAX72xx.h>
#include <ezButton.h>
const byte hpin = A0;
const byte vpin = A1;
const byte cs_pin = 10;
const byte max_dev = 1;
MD_MAX72XX matrix = MD_MAX72XX(MD_MAX72XX::PAROLA_HW, cs_pin, max_dev);
ezButton btn(8);
byte player_x = 0;
byte direction = "";
byte obj_y = 0;
byte obj1_x = 0;
byte obj2_x = 0;
byte obj3_x = 0;
long int current_time, prev_obstacle_move, prev_player_move = 0;
short threshold = 400;
bool game_end = false;
void setup() {
Serial.begin(9600);
btn.setDebounceTime(25);
matrix.begin();
matrix.clear();
generate_obstacle();
}
void loop() {
if (!game_end) {
current_time = millis();
check_direction();
if (current_time - prev_player_move >= 150) {
prev_player_move = current_time;
matrix.clear();
move_sprite();
matrix.setPoint(7, player_x, true);
matrix.setPoint(obj_y, obj1_x, true);
matrix.setPoint(obj_y, obj2_x, true);
matrix.setPoint(obj_y, obj3_x, true);
}
if (current_time - prev_obstacle_move >= threshold) {
prev_obstacle_move = current_time;
obj_y++;
if (obj_y > 7) {
generate_obstacle();
threshold -= 10;
if (threshold < 150) threshold = 150;
}
}
if (obj_y == 7 && (player_x == obj1_x || player_x == obj2_x || player_x == obj3_x)) {
game_end = true;
}
}
else if (game_end) {
show_msg("GAME OVER");
while (1) {
btn.loop();
if (btn.isPressed()) {
game_end = false;
obj_y = 8;
player_x = 0;
threshold = 400;
break;
}
}
}
}
void check_direction() {
if (analogRead(hpin) > 512) direction = 1;
else if (analogRead(hpin) < 512) direction = -1;
else direction = 0;
}
void move_sprite() {
player_x += direction;
constrain(player_x, 0, 7);
}
void generate_obstacle() {
obj_y = 0;
while (true) {
obj1_x = random(0, 8);
obj2_x = random(0, 8);
obj3_x = random(0, 8);
if (obj1_x != obj2_x && obj2_x != obj3_x && obj3_x != obj1_x) break;
}
}
void show_msg (char msg[]) {
for (byte i = 0; i < 6; i++) {
for (byte x = 0; x < 8; x++) {
for (byte y = 0; y < 8; y++) {
matrix.setPoint(y, x, (i % 2 == 0));
}
}
delay(500);
}
for (byte i = 0; msg[i] != '\0'; i++) {
matrix.setChar(6, msg[i]);
delay(500);
matrix.clear();
delay(500);
}
}