#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD(0x27, 20, 2);

int level, pause = 400, p = 0;
byte d, x, y, i;
byte ember[8] = {0B11111, 0B10101, 0B11111, 0B00100, 0B01110, 0B10101, 0B00100, 0B01010};
byte tuske[8] = {0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b10101, 0b10101, 0b11111};
byte ko[8] = {0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01110, 0b11111, 0b10101};
byte repulo[8] = {0b00000, 0b00000, 0b00011, 0b01100, 0b10111, 0b01100, 0b00011, 0b00000};

void setup() {
  pinMode(10, OUTPUT);
  pinMode(A1, INPUT_PULLUP);
  LCD.init();
  LCD.backlight();
  for (i = 0; i < 4; i++) LCD.createChar(i, i == 0 ? ember : i == 1 ? tuske : i == 2 ? ko : repulo);
  LCD.setCursor(6, 0);
  LCD.print("MENJ!");
  delay(400);
  tone(10, 600);
  delay(100);
  noTone(10);
  LCD.clear();
  level = 0;
}

void loop() {
  if(level == 0) {
    LCD.clear();
    LCD.setCursor(6, 0);
    LCD.print("MENJ!");
    delay(400);
    tone(10, 600);
    delay(100);
    noTone(10);
    LCD.clear();
    level = 1;
  }

  x = 15, y = 1, i = random(1, 4), d = 1;
  if (i == 3) y = 0;
  while (x > 0) {
    LCD.clear();
    LCD.setCursor(0, 0);
    LCD.print(level);
    d = digitalRead(A1);
    if (d == LOW) d = 1;
    else d = 0;
    LCD.setCursor(4, d);
    LCD.print(char(0));
    LCD.setCursor(x, y);
    tone(10, 50);
    LCD.print(char(i));
    noTone(10);
    if (x == 4 && y == d) {
      gameOver();
      break;
    }
    if (d == 0) { tone(10, 200); delay(100); noTone(10); }
    else delay(100);
    delay(pause);
    x--, p++;
    if (p > 4) p = 0;
  }
  level++, pause -= 20;
  if (pause < 0) pause = 0;
  tone(10, 800);
  delay(20);
}

void gameOver() {
  for (byte j = 0; j < 3; j++) {
    tone(10, 50);
    delay(100);
    noTone(10);
    delay(100);
    tone(10, 20);
    delay(300);
    noTone(10);
  }
  LCD.clear();
  for (byte j = 0; j < 2; j++) {
    LCD.setCursor(3, 0);
    LCD.print("VESZTETTEL!");
    delay(600);
    LCD.clear();
    delay(400);
  }
  LCD.setCursor(4, 1);
  LCD.print("LEVEL: ");
  LCD.print(level);
  delay(400);
  LCD.clear();
  LCD.setCursor(6, 0);
  LCD.print("MENJ!");
  delay(400);
  tone(10, 600);
  delay(100);
  noTone(10);
  LCD.clear();
  level = 0, pause = 400, p = 0, y = 1, x = 0;
}