【Arduino】189种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百四十九:1.28寸圆形彩色TFT显示屏 高清IPS 模块 240*240 SPI接口GC9A01驱动
项目之一百一十八:ESP32+GC9A01之模拟自动运行迷宫寻路游戏
实验场景图 动态图
- /*
- 【Arduino】189种传感器模块系列实验(资料代码+仿真编程+图形编程)
- 实验二百四十九:1.28寸圆形彩色TFT显示屏 高清IPS 模块 240*240 SPI接口GC9A01驱动
- 项目之一百一十八:ESP32+GC9A01之模拟自动运行迷宫寻路游戏
- */
-
- // GC9A01---------- ESP32
- // RST ------------ NC(复位引脚,此处未连接)
- // CS ------------- D4(片选引脚,连接到ESP32的D4引脚)
- // DC ------------- D2(数据/命令选择引脚,连接到ESP32的D2引脚)
- // SDA ------------ D23 (green)(主数据输出引脚,连接到ESP32的D23引脚,绿色线)
- // SCL ------------ D18 (yellow)(时钟信号引脚,连接到ESP32的D18引脚,黄色线)
- // GND ------------ GND(接地引脚,连接到ESP32的接地端)
- // VCC -------------3V3(电源引脚,连接到ESP32的3.3V电源)
-
- #include <TFT_eSPI.h>
-
- #define SCREEN_WIDTH 240
- #define SCREEN_HEIGHT 240
- #define CELL_SIZE 20
- #define MAZE_ROWS 10 // 迷宫行数
- #define MAZE_COLS 10 // 迷宫列数
-
- TFT_eSPI tft = TFT_eSPI();
-
- // **迷宫数据(1 代表墙壁,0 代表可行走路径)**
- int maze[MAZE_ROWS][MAZE_COLS] = {
- {1,1,1,1,1,1,1,1,1,1},
- {1,0,0,0,0,0,0,0,0,1},
- {1,0,1,0,1,1,1,1,0,1},
- {1,0,1,0,0,0,0,1,0,1},
- {1,0,1,1,1,1,0,1,0,1},
- {1,0,0,0,0,1,0,1,0,1},
- {1,0,1,1,0,1,0,1,0,1},
- {1,0,0,1,0,0,0,1,0,1},
- {1,0,1,1,1,1,1,1,0,1},
- {1,1,1,1,1,1,1,1,1,1}
- };
-
- // **计算迷宫偏移量,使其居中**
- int mazeOffsetX = (SCREEN_WIDTH - (MAZE_COLS * CELL_SIZE)) / 2;
- int mazeOffsetY = (SCREEN_HEIGHT - (MAZE_ROWS * CELL_SIZE)) / 2;
-
- // **玩家位置**
- int playerX = 1;
- int playerY = 1;
- int exitX = MAZE_COLS - 2;
- int exitY = MAZE_ROWS - 2;
-
- /**
- * 初始化屏幕
- */
- void setup() {
- Serial.begin(115200);
- tft.init();
- tft.setRotation(1);
- tft.fillScreen(TFT_BLACK);
- drawMaze();
- }
-
- /**
- * 绘制迷宫(居中显示)
- */
- void drawMaze() {
- tft.fillScreen(TFT_BLACK);
- for (int i = 0; i < MAZE_ROWS; i++) {
- for (int j = 0; j < MAZE_COLS; j++) {
- if (maze[i][j] == 1) {
- tft.fillRect(mazeOffsetX + j * CELL_SIZE, mazeOffsetY + i * CELL_SIZE, CELL_SIZE, CELL_SIZE, TFT_BLUE);
- }
- }
- }
-
- // **绘制玩家(绿色)**
- tft.fillRect(mazeOffsetX + playerX * CELL_SIZE, mazeOffsetY + playerY * CELL_SIZE, CELL_SIZE, CELL_SIZE, TFT_GREEN);
-
- // **绘制出口(红色)**
- tft.fillRect(mazeOffsetX + exitX * CELL_SIZE, mazeOffsetY + exitY * CELL_SIZE, CELL_SIZE, CELL_SIZE, TFT_RED);
- }
-
- /**
- * 自动路径寻找
- */
- void movePlayer() {
- if (playerX < exitX && maze[playerY][playerX + 1] == 0) {
- playerX += 1; // **向右移动**
- } else if (playerY < exitY && maze[playerY + 1][playerX] == 0) {
- playerY += 1; // **向下移动**
- } else if (playerX > 1 && maze[playerY][playerX - 1] == 0) {
- playerX -= 1; // **向左移动**
- } else if (playerY > 1 && maze[playerY - 1][playerX] == 0) {
- playerY -= 1; // **向上移动**
- }
-
- drawMaze();
-
- // **到达出口后重置**
- if (playerX == exitX && playerY == exitY) {
- delay(1000);
- playerX = 1;
- playerY = 1;
- drawMaze();
- }
- }
-
- /**
- * 游戏主循环
- */
- void loop() {
- movePlayer(); // **自动寻路**
- delay(500); // **控制移动速度**
- }
复制代码
|