#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
int const buttonPinTop = 2;
int const buttonPinBottom = 3;
String const car = "I>>";
String const enemyCar = "<I";
String const spawnedCar = "<";
String const carEnd = "I";
int y = 0;
int del = 150;
int times = 0;
int score = 0;
void setup() {
lcd.init();
lcd.backlight();
pinMode(buttonPinTop, INPUT_PULLUP);
pinMode(buttonPinBottom, INPUT_PULLUP);
}
void loop() {
int posY = random(0, 4);
lcd.setCursor(19, posY);
lcd.print("XX");
for (int i = 18; i >= 0; i--) {
if(digitalRead(buttonPinTop) == LOW)
{
moveTop();
}
if(digitalRead(buttonPinBottom) == LOW)
{
moveBottom();
}
validY();
lcd.clear();
printCar();
lcd.setCursor(i, posY);
lcd.print("<=");
if(y == posY
&& (i == 0 || i == 1 || i == 2))
{
gameOver();
return;
}
delay(del);
}
if(del > 10)
{
del -= 5;
}
score++;
}
void gameOver()
{
lcd.clear();
char message1[] = "Game over";
char message2[] = "Click the button";
char message3[] = "to continue";
char message4[] = "Score: ";
lcd.setCursor(getPosition(message1), 0);
lcd.print(message1);
lcd.setCursor(getPosition(message2), 1);
lcd.print(message2);
lcd.setCursor(getPosition(message3), 2);
lcd.print(message3);
lcd.setCursor(0, 3);
lcd.print(message4);
lcd.print(score);
while((digitalRead(buttonPinBottom) != LOW) && (digitalRead(buttonPinTop) != LOW)){ }
score = 0;
del = 150;
lcd.clear();
return;
}
int getPosition(char *message)
{
return (20 - strlen(message))/2;
}
void moveTop()
{
lcd.setCursor(0, y);
lcd.print(" ");
y--;
}
void moveBottom()
{
lcd.setCursor(0, y);
lcd.print(" ");
y++;
}
void validY()
{
if(y == 4)
{
y = 0;
}
if(y == -1)
{
y = 3;
}
}
void printCar()
{
lcd.setCursor(0, y);
lcd.print(car);
}