#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Joystick pins
const int SW_PIN = 2; // Switch pin
const int X_PIN = A0; // X-axis pin
const int Y_PIN = A1; // Y-axis pin
// Game state
enum { EMPTY, X, O };
int board[3][3];
int currentPlayer = X;
int selectedRow = 0;
int selectedCol = 0;
bool buttonPressed = false;
void setup() {
Serial.begin(9600);
// Initialize display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (1);
}
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
}
void loop() {
// Check for joystick input
int buttonState = digitalRead(SW_PIN);
if (buttonState == LOW && !buttonPressed) {
buttonPressed = true;
makeMove(selectedRow * 3 + selectedCol, currentPlayer);
currentPlayer = (currentPlayer == X) ? O : X;
delay(200); // Debounce
} else if (buttonState == HIGH) {
buttonPressed = false;
}
// Check for joystick movement
int xVal = analogRead(X_PIN);
int yVal = analogRead(Y_PIN);
if (xVal < 100) {
// Move left
selectedCol = (selectedCol == 0) ? 2 : selectedCol - 1;
delay(200); // Debounce
} else if (xVal > 900) {
// Move right
selectedCol = (selectedCol == 2) ? 0 : selectedCol + 1;
delay(200); // Debounce
} else if (yVal < 100) {
// Move up
selectedRow = (selectedRow == 0) ? 2 : selectedRow - 1;
delay(200); // Debounce
} else if (yVal > 900) {
// Move down
selectedRow = (selectedRow == 2) ? 0 : selectedRow + 1;
delay(200); // Debounce
}
// Update display only when necessary
updateDisplay();
}
void updateDisplay() {
display.clearDisplay();
display.setCursor(37, 0);
display.println("X-O Game");
display.drawLine(45, 13, 45, 55, 1);
display.drawLine(75, 13, 75, 55, 1);
display.drawLine(20, 42, 100, 42, 1);
display.drawLine(20, 22, 100, 22, 1);
// Draw selected box
display.drawRect(25 + selectedCol * 30, 15 + selectedRow * 20, 30, 20, WHITE);
// Draw X's and O's
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == X) {
drawX(i, j);
} else if (board[i][j] == O) {
drawO(i, j);
}
}
}
// Display player turn
display.setCursor(5, 58);
display.print((currentPlayer == X) ? "X's Turn" : "O's Turn");
display.display();
}
void drawX(int row, int col) {
display.drawLine(30 + col * 30, 10 + row * 20, 50 + col * 30, 30 + row * 20, WHITE);
display.drawLine(30 + col * 30, 30 + row * 20, 50 + col * 30, 10 + row * 20, WHITE);
}
void drawO(int row, int col) {
display.drawCircle(40 + col * 30, 20 + row * 20, 8, WHITE);
}
void makeMove(int move, int player) {
int row = move / 3;
int col = move % 3;
if (board[row][col] == EMPTY) {
board[row][col] = player;
}
}