#include <pitches.h>
#define SPEAKER_PIN 9
#define MAX_GAME_LENGTH 100
const uint8_t ledsArr[]={2,3,6,7};
const uint8_t buttonsArr[]={0,1,5,4};
const uint8_t gameTones[]={NOTE_G3,NOTE_G5,NOTE_E4,NOTE_C4};
uint8_t gameSequence[MAX_GAME_LENGTH]={0};
uint8_t gameIndex=0;
const String arrColors[]={"yellow","blue","red","green"};
// const uint8_t colorsArr[]=[yellow,blue,red,green]
void setup()
{
Serial.begin(9600);
for(int i=0;i<4;i++)
{
pinMode(ledsArr[i], OUTPUT);
pinMode(buttonsArr[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
randomSeed(analogRead(8));
}
void lightLedAndPlayTone(uint8_t index)
{
digitalWrite(ledsArr[index], HIGH);
tone(SPEAKER_PIN,gameTones[index]);
delay(300);
digitalWrite(ledsArr[index], LOW);
noTone(SPEAKER_PIN);
}
void playSequence()
{
for(int i=0;i<gameIndex;i++)
{
lightLedAndPlayTone(gameSequence[i]);
delay(50);
}
}
int readButtons()
{
while(1)
{
for(int i=0;i<4;i++)
{
int state=digitalRead(buttonsArr[i]);
if(state==0)
return i;
}
delay(1);
}
return -1;
}
void gameOver()
{
Serial.println("GAME OVER!!!");
Serial.print("your level is: ");
Serial.println(gameIndex);
gameIndex=0;
delay(200);
tone(SPEAKER_PIN,NOTE_DS5);
delay(300);
tone(SPEAKER_PIN,NOTE_D5);
delay(300);
tone(SPEAKER_PIN,NOTE_CS5);
delay(300);
for(int i=0;i<10;i++)
{
for(int j=-10;j<10;j++)
{
tone(SPEAKER_PIN,NOTE_C5+j);
delay(6);
}
}
noTone(SPEAKER_PIN);
delay(500);
}
bool checkUserSequence()
{
for(int i=0;i<gameIndex;i++)
{
int led=gameSequence[i];
int btn=readButtons();
if(btn!=led)
return false;
lightLedAndPlayTone(btn);
delay(300);
}
return true;
}
void playLevelUpSound(){
tone(SPEAKER_PIN,NOTE_E4);
delay(150);
tone(SPEAKER_PIN,NOTE_G4);
delay(150);
tone(SPEAKER_PIN,NOTE_E5);
delay(150);
tone(SPEAKER_PIN,NOTE_C5);
delay(150);
tone(SPEAKER_PIN,NOTE_D5);
delay(150);
tone(SPEAKER_PIN,NOTE_B5);
delay(150);
noTone(SPEAKER_PIN);
}
void loop(){
uint8_t newLed=random(0,4);
gameSequence[gameIndex++]=newLed;
if(gameIndex>=MAX_GAME_LENGTH)
gameIndex=MAX_GAME_LENGTH-1;
playSequence();
if(checkUserSequence()==false)
gameOver();
delay(300);
if(gameIndex>0)
playLevelUpSound();
delay(300);
}