aduino打地鼠游戏代码
时间: 2023-07-03 21:30:39 浏览: 30
下面是一个简单的Arduino打地鼠游戏代码,你可以根据自己的需求进行修改和优化。
```
#include <Adafruit_RGBLCDShield.h>
#include <Wire.h>
#include <SPI.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
const int ROWS = 3; // 地鼠出现的行数
const int COLS = 4; // 地鼠出现的列数
const int MAX_SCORE = 10; // 游戏最高得分
int score = 0; // 当前得分
int time = 0; // 游戏时间
int last_mole_row = -1; // 上一个地鼠出现的行数
int last_mole_col = -1; // 上一个地鼠出现的列数
void setup() {
lcd.begin(16, 2);
lcd.setBacklight(0x7);
lcd.clear();
lcd.print("Whack-a-Mole");
delay(1000);
}
void loop() {
lcd.clear();
lcd.print("Score: ");
lcd.print(score);
lcd.setCursor(8, 0);
lcd.print("Time: ");
lcd.print(time);
lcd.setCursor(0, 1);
lcd.print("Whack me!");
int mole_row = random(ROWS);
int mole_col = random(COLS);
while (mole_row == last_mole_row && mole_col == last_mole_col) { // 确保新出现的地鼠和上一个不在同一个位置
mole_row = random(ROWS);
mole_col = random(COLS);
}
last_mole_row = mole_row;
last_mole_col = mole_col;
delay(random(500, 2000)); // 等待一段时间后地鼠出现
lcd.setCursor(mole_col * 4, mole_row + 1);
lcd.print("*"); // 地鼠出现
delay(random(1000, 3000)); // 地鼠停留时间
lcd.setCursor(mole_col * 4, mole_row + 1);
lcd.print(" "); // 地鼠消失
if (lcd.readButtons() & BUTTONS_UP) { // 如果按下了上键
if (mole_row == 0) { // 如果地鼠出现在第一行
score++;
lcd.setCursor(mole_col * 4, mole_row + 1);
lcd.print("O"); // 打中了
} else {
score--;
lcd.setCursor(mole_col * 4, mole_row + 1);
lcd.print("X"); // 打错了
}
}
if (score >= MAX_SCORE) { // 达到最高得分
lcd.clear();
lcd.print("You win!");
while (true) {} // 无限循环
}
time++;
}
```
这个游戏使用了Adafruit RGB LCD Shield和四个按键。游戏通过随机地在屏幕上的一个位置出现地鼠,然后你需要在一定时间内打中它们。如果你错过了地鼠,你的得分会减少。如果你达到了最高得分,你就赢了游戏。