#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
// 定義ILI9341的引腳
#define TFT_CS 2
#define TFT_RST 0
#define TFT_DC 4
// 定義按鈕的引腳
#define BUTTON_PIN 34
// 初始化ILI9341物件
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// 定義圓點的最大數量
#define MAX_CIRCLES 20
// 定義圓點的結構
struct Circle {
int x, y;
bool active;
};
// 圓點陣列
Circle circles[MAX_CIRCLES];
// 定義更新圓點位置的間隔時間(毫秒)
const unsigned long interval = 50;
const unsigned long spawnInterval = 1500; // 新圓點生成的間隔時間(毫秒)
unsigned long previousMillis = 0;
unsigned long previousSpawnMillis = 0;
// 按鈕防彈跳變數
unsigned long lastButtonPress = 0;
const unsigned long debounceDelay = 50;
// 定義分數變數
int score = 0;
void setup(void) {
// 初始化ILI9341螢幕
tft.begin();
// 設定畫面方向(預設為垂直方向)
tft.setRotation(1);
// 填滿螢幕為黑色
tft.fillScreen(ILI9341_BLACK);
// 在螢幕上繪製一條白色的垂直線
tft.drawLine(50, 0, 50, 240, ILI9341_WHITE); // 假設螢幕高度為240像素
// 初始化圓點陣列
for (int i = 0; i < MAX_CIRCLES; i++) {
circles[i].x = 360; // 起始位置
circles[i].y = 120;
circles[i].active = false;
}
// 初始化按鈕引腳
pinMode(BUTTON_PIN, INPUT_PULLUP);
// 顯示初始分數
displayScore();
}
void loop() {
// 取得目前的毫秒數
unsigned long currentMillis = millis();
// 檢查是否需要生成新的圓點
if (currentMillis - previousSpawnMillis >= spawnInterval) {
previousSpawnMillis = currentMillis;
// 找到一個未使用的圓點並激活它
for (int i = 0; i < MAX_CIRCLES; i++) {
if (!circles[i].active) {
circles[i].x = 360; // 新圓點的起始位置
circles[i].active = true;
break;
}
}
}
// 檢查是否已經過了設定的時間間隔
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// 更新每個圓點的位置
for (int i = 0; i < MAX_CIRCLES; i++) {
if (circles[i].active) {
// 清除圓點的上一個位置
tft.fillCircle(circles[i].x, circles[i].y, 5, ILI9341_BLACK);
// 更新圓點位置,使其往左移動
circles[i].x = circles[i].x - 5;
// 檢查圓點是否移出螢幕
if (circles[i].x < 0) {
circles[i].active = false; // 停止顯示此圓點
} else {
// 在新位置繪製圓點
tft.fillCircle(circles[i].x, circles[i].y, 5, ILI9341_RED);
}
}
}
}
// 檢查按鈕是否被按下
// 檢查按鈕是否被按下,並加入防彈跳
if (digitalRead(BUTTON_PIN) == HIGH) {
if ((currentMillis - lastButtonPress) > debounceDelay) {
lastButtonPress = currentMillis;
// 檢查是否有圓點在(50,120)位置
for (int i = 0; i < MAX_CIRCLES; i++) {
if (circles[i].active && circles[i].x == 50 && circles[i].y == 120) {
score += 500; // 增加分數
displayScore(); // 顯示更新後的分數
}
}
}
}
}
// 顯示分數的函數
void displayScore() {
// 清除舊分數
tft.fillRect(220, 0, 100, 20, ILI9341_BLACK);
// 設定文字顏色和大小
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
// 顯示新的分數
tft.setCursor(150, 0);
tft.print("Score:");
tft.print(score);
}