#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
#define TFT_CS 10
#define TFT_DC 9
#define TFT_RST 8
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// الجويستيك
#define JOY_X A0
#define JOY_Y A1
// حجم الخانات
#define CELL 10
#define WIDTH 24
#define HEIGHT 32
int snakeX[100], snakeY[100];
int length = 3;
int dirX = 1, dirY = 0;
int foodX, foodY;
bool gameOver = false;
byte maze[HEIGHT][WIDTH]; // المتاهة
void drawCell(int x, int y, uint16_t color) {
tft.fillRect(x * CELL, y * CELL, CELL, CELL, color);
}
void placeFood() {
do {
foodX = random(1, WIDTH - 1);
foodY = random(1, HEIGHT - 1);
} while (maze[foodY][foodX] == 1);
drawCell(foodX, foodY, ILI9341_RED);
}
void setupMaze() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (x == 0 || x == WIDTH - 1 || y == 0 || y == HEIGHT - 1 || (x % 4 == 0 && y > 5)) {
maze[y][x] = 1;
drawCell(x, y, ILI9341_WHITE);
} else {
maze[y][x] = 0;
}
}
}
}
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
tft.begin();
tft.fillScreen(ILI9341_BLACK);
setupMaze();
// بدء موقع الدودة
snakeX[0] = 5; snakeY[0] = 5;
snakeX[1] = 4; snakeY[1] = 5;
snakeX[2] = 3; snakeY[2] = 5;
for (int i = 0; i < length; i++) {
drawCell(snakeX[i], snakeY[i], ILI9341_GREEN);
}
placeFood();
}
void loop() {
if (gameOver) return;
// قراءة الجويستيك
int xVal = analogRead(JOY_X);
int yVal = analogRead(JOY_Y);
if (xVal > 800) { dirX = 1; dirY = 0; }
else if (xVal < 200) { dirX = -1; dirY = 0; }
else if (yVal > 800) { dirX = 0; dirY = -1; }
else if (yVal < 200) { dirX = 0; dirY = 1; }
// تحريك الدودة
int newX = snakeX[0] + dirX;
int newY = snakeY[0] + dirY;
// تحقق من التصادم
if (maze[newY][newX] == 1) {
tft.setCursor(30, 150);
tft.setTextColor(ILI9341_RED);
tft.setTextSize(3);
tft.print("Game Over");
gameOver = true;
return;
}
// تحقق من التصادم مع النفس
for (int i = 0; i < length; i++) {
if (snakeX[i] == newX && snakeY[i] == newY) {
tft.setCursor(30, 150);
tft.setTextColor(ILI9341_RED);
tft.setTextSize(3);
tft.print("Self Hit!");
gameOver = true;
return;
}
}
// تحريك الجسم
for (int i = length; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] = newX;
snakeY[0] = newY;
// رسم الرأس
drawCell(newX, newY, ILI9341_GREEN);
// إذا أكلت الفاكهة
if (newX == foodX && newY == foodY) {
length++;
placeFood();
} else {
// امسح الذيل
drawCell(snakeX[length], snakeY[length], ILI9341_BLACK);
}
delay(150);
}