#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#define TFT_DC 22
#define TFT_CS 5
#define BUTTON_UP_PIN 25
#define BUTTON_DOWN_PIN 33
#define BUTTON_LEFT_PIN 32
#define BUTTON_RIGHT_PIN 34
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
const int TFT_WIDTH = 320;
const int TFT_HEIGHT = 240;
const int TILE_SIZE = 20;
const int MAP_WIDTH = TFT_WIDTH / TILE_SIZE;
const int MAP_HEIGHT = TFT_HEIGHT / TILE_SIZE;
int playerX = 1;
int playerY = 1;
int gameMap[MAP_HEIGHT][MAP_WIDTH] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1 },
{1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 },
{1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1 },
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
};
void setup() {
tft.begin();
tft.setRotation(3);
tft.fillScreen(ILI9341_BLACK);
pinMode(BUTTON_UP_PIN, INPUT_PULLUP);
pinMode(BUTTON_DOWN_PIN, INPUT_PULLUP);
pinMode(BUTTON_LEFT_PIN, INPUT_PULLUP);
pinMode(BUTTON_RIGHT_PIN, INPUT_PULLUP);
drawMap();
drawPlayer();
}
void loop() {
// 检测按键并移动角色
if (digitalRead(BUTTON_UP_PIN) == LOW) {
if (gameMap[playerY - 1][playerX] == 0) {
movePlayer(0, -1);
}
}
if (digitalRead(BUTTON_DOWN_PIN) == LOW) {
if (gameMap[playerY + 1][playerX] == 0) {
movePlayer(0, 1);
}
}
if (digitalRead(BUTTON_LEFT_PIN) == LOW) {
if (gameMap[playerY][playerX - 1] == 0) {
movePlayer(-1, 0);
}
}
if (digitalRead(BUTTON_RIGHT_PIN) == LOW) {
if (gameMap[playerY][playerX + 1] == 0) {
movePlayer(1, 0);
}
}
}
void drawMap() {
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
int tile = gameMap[y][x];
int color = (tile == 1) ? ILI9341_BLUE : ILI9341_WHITE;
tft.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE, color);
}
}
}
void drawPlayer() {
tft.fillRect(playerX * TILE_SIZE, playerY * TILE_SIZE, TILE_SIZE, TILE_SIZE, ILI9341_RED);
}
void movePlayer(int dx, int dy) {
tft.fillRect(playerX * TILE_SIZE, playerY * TILE_SIZE, TILE_SIZE, TILE_SIZE, ILI9341_BLACK);
playerX += dx;
playerY += dy;
drawPlayer();
}