Simple Simon

 Arduino Code for Simple Simon Game



int LEDPins [4] = {2,3,4,5};

int buttonPins [4] = {6,7,8,9};

int LEDSequence [32];


void setup ()

{

  Serial.begin(9600);

  for(int i =0; i<4; i++){

  pinMode(LEDPins[i], OUTPUT);

  pinMode(buttonPins[i], INPUT);

  }


// setting the randomizer for game

randomSeed(analogRead(A0));

}



void loop ()

{

  bool lose = false;

  

  //line bellow will be the random sequence for the lights

  for (int i =0; i<32; i++)

  {

    LEDSequence[i] = random(4);

    Serial.println(LEDSequence[i]);

    delay(250);

  }

   

  //begining of the Simon game

  //doing a loop for the level

  for (int level =0; level <32; level++){

      

    //show loop here

     for (int i =0; i < level; i++){

        digitalWrite(LEDPins[LEDSequence[i]], HIGH);

        delay(750);

        digitalWrite(LEDPins[LEDSequence[i]], LOW);

        delay(750);

      }

    

    //line bellow will be the loop for the user responds

    for (int i=0; i < level; i++){

      int button =-1;

          

      while (button < 0){

        button = buttonPressed();

      }

          

      digitalWrite(LEDPins[button], HIGH);

      delay(250);

      digitalWrite(LEDPins[button], LOW);

      delay(250);

      

      if (LEDSequence[i] != button){

        lose = true;

        break;

      }

    }

    

    //win or loss loop

    if (lose == true){

      loseSeq();

      break;

    } else if (lose == false && level == 31) {

      //winner need 32 levels

      winSeq();

    }

  }

 }

  //end of loop

  

//list of methods

//sequence for the win

  

void winSeq(){

  for (int i =0; i <3; i++){

    for (int i =0; i<4; i++){

      digitalWrite(LEDPins[i],HIGH);

    }

    delay(500);

    for(int i=0; i<4; i++){

      digitalWrite(LEDPins[i], LOW);

    }

    delay(500);

  }

}

  

//sequence for the loss

void loseSeq(){

    for (int i =0; i<4; i++){

      digitalWrite(LEDPins[i],HIGH);

    }

  delay(1000);

  for(int i = 0; i<4; i++){

    digitalWrite(LEDPins[i], LOW);

    delay(1000);

  }

}

//check for debounce (from the game)

     

bool isPressed(int buttonNum){

  bool pressed = false;

  if (digitalRead(buttonPins[buttonNum])==HIGH){

    delay(10);

    while (digitalRead(buttonPins[buttonNum])==HIGH){}

    delay(10);

    pressed = true;

  }

  return pressed;

}

                   

//detect which button pressed (from the game)

 int buttonPressed(){

   int buttonNumb = -1;

   for(int i =0; i<4; i++){

   if(isPressed(i) == true){

     buttonNumb = i;

     }

   }


return buttonNumb;

      

}

    

Comments

Popular posts from this blog

Ultra Sonic Sensor

temperature LCD and DHT11

SIP CAR Code Ultra Sonic