#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display settings
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Pin for the jump button
#define JUMP_BUTTON 18
// Game variables
int dinoY = 40; // Dino's vertical position
int dinoHeight = 20; // Dino's height
bool isJumping = false; // Is the Dino in a jump?
int jumpSpeed = 3; // Speed of the jump
int gravity = 1; // Gravity
int groundLevel = 40; // Dino's ground level position
int jumpPeak = 20; // Peak of the jump
int obstacleX = SCREEN_WIDTH; // Obstacle's horizontal position
int obstacleY = 40; // Obstacle's vertical position
int obstacleWidth = 10; // Obstacle's width
int obstacleHeight = 20; // Obstacle's height
int obstacleSpeed = 2; // Speed of the obstacle
bool gameOver = false;
void setup() {
pinMode(JUMP_BUTTON, INPUT_PULLUP);
Serial.begin(115200);
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.display();
}
void loop() {
if (!gameOver) {
// Check if button is pressed
if (digitalRead(JUMP_BUTTON) == LOW && !isJumping && dinoY == groundLevel) {
isJumping = true;
Serial.println("Jump initiated!"); // Debugging
}
// Handle jump
if (isJumping) {
dinoY -= jumpSpeed; // Move up
if (dinoY <= groundLevel - jumpPeak) {
isJumping = false; // Reached the peak
}
} else if (dinoY < groundLevel) {
dinoY += gravity; // Gravity brings Dino down
if (dinoY > groundLevel) {
dinoY = groundLevel; // Stay at ground level
}
}
// Move obstacle
obstacleX -= obstacleSpeed;
if (obstacleX < 0) {
obstacleX = SCREEN_WIDTH; // Reset obstacle
}
// Check collision
if (obstacleX < 20 && obstacleX + obstacleWidth > 10 && dinoY + dinoHeight > obstacleY) {
gameOver = true;
}
// Render the game
renderGame();
} else {
displayGameOver();
delay(2000);
resetGame();
}
delay(30); // Frame delay
}
void renderGame() {
display.clearDisplay();
// Draw Dino
display.fillRect(10, dinoY, 10, dinoHeight, SSD1306_WHITE);
// Draw obstacle
display.fillRect(obstacleX, obstacleY, obstacleWidth, obstacleHeight, SSD1306_WHITE);
// Draw ground
display.drawLine(0, groundLevel + dinoHeight, SCREEN_WIDTH, groundLevel + dinoHeight, SSD1306_WHITE);
display.display();
}
void displayGameOver() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 20);
display.println(F("GAME OVER"));
display.display();
}
void resetGame() {
dinoY = groundLevel;
obstacleX = SCREEN_WIDTH;
gameOver = false;
}