西蒙游戏 Simon Game 《西蒙游戏》是一款益智休闲类小游戏,它的游戏规则是,让玩家记住不同颜色的灯的亮灯顺序后,依次点击灯,如果次序与AI给予的次序相同,则游戏继续并增加难度,否则游戏结束,重置游戏。 在线arduino西蒙游戏
代码
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include "pitches.h"
byte buttonPins[] = {1, 2, 3, 4};
#define SPEAKER_PIN 0
#define MAX_GAME_LENGTH 100
int gameTones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
byte gameSequence[MAX_GAME_LENGTH] = {0};
byte gameIndex = 0;
void setup() {
randomSeed(analogRead(1));
ADCSRA = 0;
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, INPUT);
}
ISR(PCINT0_vect) {
GIMSK &= ~0b00100000;
sleep_disable();
}
void sleep() {
sleep_enable();
noInterrupts();
GIMSK |= 0b00100000;
for (byte i = 0; i < 4; i++) {
PCMSK |= 1 << buttonPins[i];
}
interrupts();
sleep_cpu();
}
void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{
int x;
long delayAmount = (long)(1000000 / frequencyInHertz);
long loopTime = (long)((timeInMilliseconds * 1000) / (delayAmount * 2));
pinMode(speakerPin, OUTPUT);
for (x = 0; x < loopTime; x++) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(delayAmount);
digitalWrite(speakerPin, LOW);
delayMicroseconds(delayAmount);
}
pinMode(speakerPin, INPUT);
}
void lightLedAndPlaySound(byte ledIndex) {
pinMode(buttonPins[ledIndex], OUTPUT);
digitalWrite(buttonPins[ledIndex], LOW);
beep(SPEAKER_PIN, gameTones[ledIndex], 300);
pinMode(buttonPins[ledIndex], INPUT_PULLUP);
}
void playSequence() {
for (int i = 0; i < gameIndex; i++) {
byte currentLed = gameSequence[i];
lightLedAndPlaySound(currentLed);
delay(50);
}
}
byte readButton() {
for (;;) {
for (int i = 0; i < 4; i++) {
byte buttonPin = buttonPins[i];
if (digitalRead(buttonPin) == LOW) {
return i;
}
}
sleep();
}
}
void playButtonTone(byte buttonIndex) {
beep(SPEAKER_PIN, gameTones[buttonIndex], 150);
while (digitalRead(buttonPins[buttonIndex]) == LOW);
delay(50);
}
void gameOver() {
gameIndex = 0;
delay(200);
beep(SPEAKER_PIN, NOTE_DS5, 300);
beep(SPEAKER_PIN, NOTE_D5, 300);
beep(SPEAKER_PIN, NOTE_CS5, 300);
for (int i = 0; i < 200; i++) {
beep(SPEAKER_PIN, NOTE_C5 + (i % 20 - 10), 5);
}
delay(500);
}
void checkUserSequence() {
for (int i = 0; i < gameIndex; i++) {
byte expectedButton = gameSequence[i];
byte actualButton = readButton();
playButtonTone(actualButton);
if (expectedButton == actualButton) {
} else {
gameOver();
return;
}
}
}
void levelUp() {
beep(SPEAKER_PIN, NOTE_E4, 150);
beep(SPEAKER_PIN, NOTE_G4, 150);
beep(SPEAKER_PIN, NOTE_E5, 150);
beep(SPEAKER_PIN, NOTE_C5, 150);
beep(SPEAKER_PIN, NOTE_D5, 150);
beep(SPEAKER_PIN, NOTE_G5, 150);
}
void loop() {
gameSequence[gameIndex] = random(0, 4);
gameIndex++;
playSequence();
checkUserSequence();
delay(300);
if (gameIndex > 0) {
levelUp();
delay(300);
}
}
|