#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display dimensions
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// I2C address for the OLED display
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Button pin
const int buttonPin = D10;
// Game variables
int dinoY = 44; // Y-position of the dinosaur
int dinoJumpHeight = 20; // Jump height
bool isJumping = false;
int jumpCounter = 0;
int obstacleX = SCREEN_WIDTH;
int obstacleSpeed = 3;
unsigned long previousMillis = 0;
const long frameDelay = 50;
// Score
int score = 0;
void setup() {
// Initialize the display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.display();
// Initialize the button pin
pinMode(buttonPin, INPUT_PULLUP);
// Draw initial frame
drawGame();
}
void loop() {
unsigned long currentMillis = millis();
// Check for frame delay
if (currentMillis - previousMillis >= frameDelay) {
previousMillis = currentMillis;
// Handle jumping
if (isJumping) {
if (jumpCounter < dinoJumpHeight) {
dinoY -= 2; // Move up
jumpCounter++;
} else if (jumpCounter < dinoJumpHeight * 2) {
dinoY += 2; // Move down
jumpCounter++;
} else {
isJumping = false;
jumpCounter = 0;
}
}
// Move obstacle
obstacleX -= obstacleSpeed;
if (obstacleX < 0) {
obstacleX = SCREEN_WIDTH; // Reset obstacle
score++; // Increment score when the obstacle is passed
}
// Check for collision
if (obstacleX < 20 && obstacleX > 5 && dinoY > 40) {
// Collision detected
gameOver();
return;
}
// Draw the game frame
drawGame();
}
// Check for button press to jump
if (digitalRead(buttonPin) == LOW && !isJumping) {
isJumping = true;
}
}
void drawGame() {
display.clearDisplay();
// Draw score
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Score: ");
display.print(score);
// Draw ground
display.drawLine(0, 54, SCREEN_WIDTH, 54, SSD1306_WHITE);
// Draw dinosaur (a small rectangle)
display.fillRect(10, dinoY, 10, 10, SSD1306_WHITE);
// Draw obstacle (a small rectangle)
display.fillRect(obstacleX, 44, 10, 10, SSD1306_WHITE);
// Update the display
display.display();
}
void gameOver() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 20);
display.println("GAME OVER");
display.display();
delay(2000);
// Reset game variables
dinoY = 44;
obstacleX = SCREEN_WIDTH;
isJumping = false;
jumpCounter = 0;
score = 0; // Reset score
drawGame();
}