// This example shows mechButton, wich debounces a button then,
// if desired, can do a callback when that button's state changes.
// Along with a timeObj, that works like a kitchen timer. Exceept
// in ms instead of minutes. These two classes can make your
// coding WAY eaiser. And, they are completely NON BLOCKING
//
//                  Hide the mess of millis!

#include <mechButton.h>
#include <timeObj.h>


#define NUM_PLAYERS 6
#define BLOCK_MS    2000
#define TONE_HZ     270
#define TONE_PIN    A0

bool        active;
timeObj     deadTimer(BLOCK_MS,false);
mechButton  btn[NUM_PLAYERS] {2, 3, 4, 5, 6, 7 };
int         LED[NUM_PLAYERS] { 8, 9, 10, 11, 12, 13 };

void setup() {
  
  for (int i=0;i<NUM_PLAYERS;i++) {   // For each player..
    pinMode(LED[i],OUTPUT);           // Make their LED pin an output.
    btn[i].setCallback(btnClk);       // Link their button to the button callback.
  }                                   // 
  active = true;                      // We are listining!
}


// When a button's state changes.. Call this!
void btnClk(void) {

  if (active) {                         // If we're acctive..
    for (int i=0;i<NUM_PLAYERS;i++) {   // For each player..
      if (!btn[i].getState()) {         // If this player's button is mashed..
        digitalWrite(LED[i],HIGH);      // Flick on her LED. WINNER!
        active = false;                 // No longer active.
        tone(TONE_PIN,TONE_HZ);         // Lets hear it!
        deadTimer.start();              // Start the deadTimer.
        return;                         // Bail out, our work is done.
      }
    }
  }
}


// Like it says. Shut off all the LEDs
void LEDsOff(void) {

  for (int i=0;i<NUM_PLAYERS;i++) { // For everyone..
    digitalWrite(LED[i],LOW);       // Shut off her LED>
  }
}


void loop() {
  
  idle();                   // Runs things like the buttons.
  if (deadTimer.ding()) {   // Timer expires?
    LEDsOff();              // Shut off LEDs
    noTone(TONE_PIN);       // Shut off beeper.
    active = true;          // We are active again!
    deadTimer.reset();      // Reset the timer to off.
  }
}