#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
int Screen_width = 128;
int Screen_ht = 64;
int reset = -1;
int address = 0x3C;
int a = 64; int b = 32; //centre for ball
int x = 55; int y = 60; //for paddle
int x_speed = 1; int y_speed = 1; //Speed of ball
int score = 0;
int m,n;
Adafruit_SSD1306 display(Screen_width,Screen_ht,&Wire,reset);

void setup(){
  pinMode(16,INPUT_PULLDOWN);
  pinMode(18,INPUT_PULLDOWN);
  pinMode(19,OUTPUT);
  Serial.begin(9600);
  if(!display.begin(SSD1306_SWITCHCAPVCC,address)){
    Serial.println("display not connected");
    for(;;);
  }
  display.clearDisplay();
}

void loop(){
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(115,1);
  display.print(score);
  m = digitalRead(18);
  if(m==1 && x+20 <= 127){
    x=x+3.5;
    Serial.println("Right");
  }
  n = digitalRead(16);
  if(n==1 && x>=1){
    x=x-3.5;
    Serial.println("Left");
  }
  //BOUNDARY CONDITIONS
  if(2<a<125&& 0<b){
    x_speed=x_speed;
    y_speed=y_speed;
  }
  if(a==125||a==2){
    x_speed=-x_speed;
    y_speed=-y_speed;
  }
  if(b==2){
    y_speed=-y_speed;
    x_speed=x_speed;
  }
  if(x<=a && a<=x+20 && b+2==59){
    y_speed=-y_speed;
    x_speed=x_speed;
    score=score+1;
    digitalWrite(19,HIGH);
    delay(20);
    digitalWrite(19,LOW);
  }
  a=a+x_speed;
  b=b+y_speed;
  display.fillCircle(a,b,2,WHITE);
  display.fillRect(x,y,20,4,WHITE);

  display.display();
  display.clearDisplay();

  if(b>=61){
    digitalWrite(19,HIGH);
    delay(1000);
    digitalWrite(19,LOW);
    display.clearDisplay();
    display.setTextSize(1);
    display.setTextColor(WHITE);
    display.setCursor(25,25);
    display.print("Score");
    display.print(score);
    display.display();
    delay(2000);
    display.clearDisplay();
    a=64;
    b=32;
    x=55;
    y=60;
    score = 0;
  }
}