#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#define PIN_RST 15
#define PIN_CE 14
#define PIN_DC 13
#define PIN_DIN 11
#define PIN_CLK 10
Adafruit_PCD8544 display(PIN_CLK, PIN_DIN, PIN_DC, PIN_CE, PIN_RST);
#define JOY_X A0 // GP26
#define JOY_Y A1 // GP27
#define JOY_BTN 16
#define SWITCH 17
#define WIDTH 84
#define HEIGHT 48
#define SNAKE_SIZE 3
int speedDelay = 200;
int score = 0;
int dirX = SNAKE_SIZE, dirY = 0;
int foodX, foodY;
struct Point { int x, y; };
Point snake[100];
int snakeLength = 5;
void setup() {
pinMode(JOY_BTN, INPUT_PULLUP);
pinMode(SWITCH, INPUT_PULLUP);
display.begin();
display.setContrast(50);
display.clearDisplay();
display.display();
randomSeed(analogRead(A0));
for (int i = 0; i < snakeLength; i++) {
snake[i] = { WIDTH / 2 - i * SNAKE_SIZE, HEIGHT / 2 };
}
spawnFood();
}
void loop() {
if (digitalRead(SWITCH) == LOW) {
showMenu();
startGame();
}
}
void showMenu() {
display.clearDisplay();
display.setCursor(30, 20);
display.setTextSize(1);
display.setTextColor(BLACK);
display.print("Snake");
display.display();
while (digitalRead(JOY_BTN) == HIGH);
delay(300);
}
void startGame() {
snakeLength = 5;
score = 0;
dirX = SNAKE_SIZE;
dirY = 0;
speedDelay = 200;
for (int i = 0; i < snakeLength; i++) {
snake[i] = { WIDTH / 2 - i * SNAKE_SIZE, HEIGHT / 2 };
}
spawnFood();
while (true) {
readJoystick();
moveSnake();
if (checkCollision()) {
gameOver();
return;
}
drawGame();
delay(speedDelay);
}
}
void readJoystick() {
int x = analogRead(JOY_X);
int y = analogRead(JOY_Y);
if (x < 300 && dirX == 0) { dirX = -SNAKE_SIZE; dirY = 0; }
if (x > 700 && dirX == 0) { dirX = SNAKE_SIZE; dirY = 0; }
if (y < 300 && dirY == 0) { dirX = 0; dirY = -SNAKE_SIZE; }
if (y > 700 && dirY == 0) { dirX = 0; dirY = SNAKE_SIZE; }
}
void moveSnake() {
for (int i = snakeLength - 1; i > 0; i--) {
snake[i] = snake[i - 1];
}
snake[0].x += dirX;
snake[0].y += dirY;
if (snake[0].x >= WIDTH) snake[0].x = 0;
if (snake[0].x < 0) snake[0].x = WIDTH - SNAKE_SIZE;
if (snake[0].y >= HEIGHT) snake[0].y = 0;
if (snake[0].y < 0) snake[0].y = HEIGHT - SNAKE_SIZE;
if (snake[0].x == foodX && snake[0].y == foodY) {
snakeLength++;
score++;
if (score % 10 == 0 && speedDelay > 50) speedDelay -= 20;
spawnFood();
}
}
void spawnFood() {
foodX = random(0, WIDTH / SNAKE_SIZE) * SNAKE_SIZE;
foodY = random(0, HEIGHT / SNAKE_SIZE) * SNAKE_SIZE;
}
bool checkCollision() {
for (int i = 1; i < snakeLength; i++) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
return true;
}
}
return false;
}
void gameOver() {
display.clearDisplay();
display.setCursor(15, 20);
display.setTextSize(1);
display.print("Game Over");
display.display();
delay(2000);
}
void drawGame() {
display.clearDisplay();
for (int i = 0; i < snakeLength; i++) {
display.fillRect(snake[i].x, snake[i].y, SNAKE_SIZE, SNAKE_SIZE, BLACK);
}
display.fillRect(foodX, foodY, SNAKE_SIZE, SNAKE_SIZE, BLACK);
display.display();
}
Loading
nokia-5110
nokia-5110