#include <LiquidCrystal_I2C.h>
const int xPixels = 20;
const int yPixels = 4;
LiquidCrystal_I2C lcd(0x27, xPixels, yPixels);
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() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(buttonPinTop, INPUT_PULLUP);
pinMode(buttonPinBottom, INPUT_PULLUP);
}
int last = 0;
int lastChanged = 0;
int i = xPixels - 2;
int posY = random(0, yPixels);
int lastBtn1State = HIGH;
int lastBtn2State = HIGH;
void loop() {
if (i == xPixels - 2) {
posY = random(0, yPixels);
}
if (millis() % del == 0) {
Serial.println(i);
validY();
lcd.clear();
printCar();
lcd.setCursor(i, posY);
lcd.print("<=");
if(y == posY
&& (i == 0 || i == 1 || i == 2))
{
gameOver();
return;
}
last = millis();
i--;
}
int btn1State = digitalRead(buttonPinTop);
if(btn1State != lastBtn1State) {
if (lastBtn1State == LOW) {
moveTop();
}
}
lastBtn1State = btn1State;
int btn2State = digitalRead(buttonPinBottom);
if(btn2State != lastBtn2State) {
if (lastBtn2State == LOW) {
moveBottom();
}
}
lastBtn2State = btn2State;
if (i == 0) {
if(del > 20) {
del -= 3;
}
score++;
i = 18;
}
}
void gameOver()
{
lcd.clear();
char message1[] = "Game over";
// char message2[] = "Click the button";
// char message3[] = "to continue";
char message2[] = "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, yPixels-1);
lcd.print(message2);
lcd.print(score);
while((digitalRead(buttonPinBottom) != LOW)
&& (digitalRead(buttonPinTop) != LOW))
{ }
score = 0;
del = 150;
lcd.clear();
return;
}
int getPosition(char *message)
{
return (yPixels - 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 == yPixels)
{
y = 0;
}
if(y == -1)
{
y = yPixels - 1;
}
}
void printCar()
{
lcd.setCursor(0, y);
lcd.print(car);
}