#include <LedControl.h>
// MAX7219 初始化(4 個模組,16x16 配置)
LedControl lc = LedControl(11, 13, 10, 4); // DIN, CLK, CS, 模組數量
// 玩家光點位置
int playerX = 0, playerY = 0;
// 目標位置
int targetX = 0, targetY = 0;
// 分數
int score = 0;
// 遊戲開始時間
unsigned long startTime;
void setup() {
// 初始化點矩陣模組
for (int i = 0; i < 4; i++) {
lc.shutdown(i, false);
lc.setIntensity(i, 8);
lc.clearDisplay(i);
}
// 初始化隨機數種子
randomSeed(analogRead(2));
// 生成第一個目標
generateTarget();
// 記錄遊戲開始時間
startTime = millis();
Serial.begin(9600);
Serial.println("Game Start!");
Serial.println("Use the joystick to move the light to eat the target!");
}
void loop() {
// 計算遊戲經過時間
if (millis() - startTime > 30000) { // 遊戲時長 30 秒
Serial.println("Game Over!");
Serial.print("Final Score: ");
Serial.println(score);
while (true); // 停止遊戲
}
int v = analogRead(A0); // Joystick 水平軸
int h = analogRead(A1); // Joystick 垂直軸
// 清除當前光點
lc.setLed(playerY / 8 + (playerX / 8) * 2, playerX % 8, playerY % 8, false);
// 控制玩家光點移動
// if( ) ?TURE:False
if (h >= 600) playerY = (playerY + 1 > 15) ? 15 : playerY + 1; // 往右
/* IF ELSE 簡寫
if (h>600)
if(playerY+1>15)
playerY=15;
else
playerY=playerY+1;
*/
if (h <= 400) playerY = (playerY - 1 < 0) ? 0 : playerY - 1; // 往左
if (v >= 600) playerX = (playerX - 1 < 0) ? 0 : playerX - 1; // 往上
if (v <= 400) playerX = (playerX + 1 > 15) ? 15 : playerX + 1; // 往下
// 更新光點位置
lc.setLed(playerY / 8 + (playerX / 8) * 2, playerX % 8, playerY % 8, true);
// 判斷是否吃掉目標
if (playerX == targetX && playerY == targetY) {
score++;
Serial.print("Score: ");
Serial.println(score);
generateTarget();
}
// 動態調整速度
int delayTime = 150 - score * 10; // 分數越高,速度越快
if (delayTime < 50) delayTime = 50; // 設定最小延遲時間
delay(delayTime);
}
void generateTarget() {
// 隨機生成目標位置,確保目標不與玩家重疊
do {
targetX = random(0, 16);
targetY = random(0, 16);
} while (targetX == playerX && targetY == playerY);
// 顯示目標
lc.setLed(targetY / 8 + (targetX / 8) * 2, targetX % 8, targetY % 8, true);
}