#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#define BTN_UP 2
#define BTN_DOWN 3
int paddleHeight = 12;
int paddleWidth = 2;
int playerY = 26;
int enemyY = 26;
int ballX = 64;
int ballY = 32;
int ballSpeedX = 2;
int ballSpeedY = 2;
void setup() {
pinMode(BTN_UP, INPUT_PULLUP);
pinMode(BTN_DOWN, INPUT_PULLUP);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
}
void loop() {
// Керування гравцем
if (!digitalRead(BTN_UP)) {
playerY -= 3;
}
if (!digitalRead(BTN_DOWN)) {
playerY += 3;
}
playerY = constrain(playerY, 0, SCREEN_HEIGHT - paddleHeight);
// Простий AI
if (ballY > enemyY + paddleHeight / 2) enemyY += 2;
if (ballY < enemyY + paddleHeight / 2) enemyY -= 2;
enemyY = constrain(enemyY, 0, SCREEN_HEIGHT - paddleHeight);
// Рух м'яча
ballX += ballSpeedX;
ballY += ballSpeedY;
// Відбиття від стін
if (ballY <= 0 || ballY >= SCREEN_HEIGHT) {
ballSpeedY = -ballSpeedY;
}
// Відбиття від ракеток
if (ballX <= 4 && ballY >= playerY && ballY <= playerY + paddleHeight) {
ballSpeedX = -ballSpeedX;
}
if (ballX >= 122 && ballY >= enemyY && ballY <= enemyY + paddleHeight) {
ballSpeedX = -ballSpeedX;
}
// Рестарт якщо пропустили
if (ballX < 0 || ballX > SCREEN_WIDTH) {
ballX = 64;
ballY = 32;
}
// Малювання
display.clearDisplay();
display.fillRect(2, playerY, paddleWidth, paddleHeight, WHITE);
display.fillRect(124, enemyY, paddleWidth, paddleHeight, WHITE);
display.fillCircle(ballX, ballY, 2, WHITE);
display.display();
delay(20);
}