Pre Code
Pre Code
h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>
class Player {
private:
int x; // X position of the player pixel
int y; // Y position of the player pixel
int tailX[MAX_LENGTH]; // X positions of the snake's body segments
int tailY[MAX_LENGTH]; // Y positions of the snake's body segments
int tailLength; // Current length of the snake
public:
Player(int initialX, int initialY) {
x = initialX;
y = initialY;
tailLength = 0;
}
void moveLeft() {
clearDisplay();
if (x > 0) {
x--; // Move left
}
drawPlayer();
}
void moveRight() {
clearDisplay();
if (x < SCREEN_WIDTH - 1) {
x++; // Move right
}
drawPlayer();
}
void moveUp() {
clearDisplay();
if (y > 0) {
y--; // Move up
}
drawPlayer();
}
void moveDown() {
clearDisplay();
if (y < SCREEN_HEIGHT - 1) {
y++; // Move down
}
drawPlayer();
}
void clearDisplay() {
display.clearDisplay();
}
void drawPlayer() {
// Draw the head of the snake
display.drawPixel(x, y, SH110X_WHITE);
int getX() {
return x;
}
int getY() {
return y;
}
void updateTail() {
// Move the body segments of the snake
for (int i = tailLength - 1; i > 0; i--) {
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
// Update the first body segment to the previous position of the head
if (tailLength > 0) {
tailX[0] = x;
tailY[0] = y;
}
}
void increaseLength() {
if (tailLength < MAX_LENGTH) {
tailX[tailLength] = x; // Add current head position to tailX array
tailY[tailLength] = y; // Add current head position to tailY array
tailLength++; // Increase the tail length
}
}
};
class Apple {
private:
int x; // X position of the apple
int y; // Y position of the apple
public:
Apple() {
spawn(); // Spawn the apple at a random position
}
void spawn() {
x = random(SCREEN_WIDTH);
y = random(SCREEN_HEIGHT);
}
int getX() {
return x;
}
int getY() {
return y;
}
void draw() {
// Draw the apple
display.drawPixel(x, y, SH110X_WHITE);
}
};
void setup() {
Serial.begin(115200);
display.begin(i2c_Address, true);
display.clearDisplay();
player.drawPlayer();
randomSeed(analogRead(A2));
apple.spawn();
display.drawPixel(apple.getX(), apple.getY(), SH110X_WHITE);
display.display();
}
void loop() {
if (player.getX() == apple.getX() && player.getY() == apple.getY()) {
// Respawn the apple at a new random position
apple.spawn();
player.increaseLength();
}
if (Serial.available()) {
unsigned char input = Serial.read();
if (input == 'a') {
movementFlags(true, false, false, false); // Set left movement flag to true
} else if (input == 'd') {
movementFlags(false, true, false, false); // Set right movement flag to true
} else if (input == 'w') {
movementFlags(false, false, true, false); // Set up movement flag to true
} else if (input == 's') {
movementFlags(false, false, false, true); // Set down movement flag to true
}
}
player.updateTail();
apple.draw();
display.display();
}