#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// 初始化 LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
String target = ""; // 目標字串
String userInput = ""; // 玩家輸入字串
int targetLength = 10; // 目標字串長度
unsigned long startTime; // 記錄開始時間
unsigned long endTime; // 記錄結束時間
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
startNewGame(); // 開始新遊戲
}
void loop() {
if (Serial.available() >0) {
char c = Serial.read(); // 即時讀取玩家輸入
// 如果玩家按下 Enter 鍵,判定輸入完成
if (c == '\n' || c == '\r') {
endTime = millis(); // 記錄結束時間
showResult(); // 顯示結果
waitForKeyPress(); // 等待玩家按任意鍵繼續
startNewGame(); // 開始新遊戲
return;
}
userInput += c;
}
}
// 生成隨機字母與數字的函數
String generateRandomLetters(int length) {
String result = "";
randomSeed(analogRead(2)); // 初始化隨機數種子
for (int i = 0; i < length; i++) {
int randomValue = random(0, 62); // 0-61 共62種可能 (大小寫字母 + 數字)
if (randomValue < 26) { // A-Z
result += char('A' + randomValue);
} else if (randomValue < 52) { // a-z
result += char('a' + randomValue - 26);
} else { // 0-9
result += char('0' + randomValue - 52);
}
}
return result;
}
// 顯示結果
void showResult() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(userInput == target ? "Correct!" : "Wrong!");
// 計算完成秒數
if(userInput == target){
float elapsedSeconds = (endTime - startTime) / 1000.0;
lcd.setCursor(0, 1);
lcd.print("Time: ");
lcd.print(elapsedSeconds, 2); // 顯示小數點後兩位
lcd.print("s");
}else{
lcd.setCursor(0, 1);
lcd.print("You: "+userInput);
}
}
void waitForKeyPress() {//任意鍵繼續
while (!Serial.available()) {
delay(100);
}
Serial.read();
/*
while (Serial.available() == 0) {
delay(100);
}
Serial.read(); // 清空按下的鍵
*/
}
// 開始新遊戲
void startNewGame() {
userInput = ""; // 重置玩家輸入
target = generateRandomLetters(targetLength); // 生成新目標字串
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(target);
lcd.setCursor(0, 1);
lcd.print("Pls Type below->");
startTime = millis(); // 記錄開始時間
}