#define P1 12 //button player left (1)
#define P2 26 //button player right (2)
#define RED 14 //red Pin
#define GREEN 27 //green Pin
#define BUZ 5 //buzzer
int del = 0;
bool ledOn = false;
int s1 = 0; //score player 1
int s2 = 0; // score player 2
int p1d = 0; // player 1 delay
int p2d = 0; // player 2 delay
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(P1, INPUT);
pinMode(P2, INPUT);
pinMode(BUZ, OUTPUT);
digitalWrite(RED, HIGH);
playSong();
}
/*
void loop() {
delay((Math.random()*(5000-3000+1))+3000)
digitalWrite(RED, LOW);
delay(10);
digitalWrite(GREEN, HIGH);
if(digitalRead(P1, HIGH) || digitalRead(P2, HIGH)) {
digitalWrite(GREEN, LOW);
delay(10);
digitalWrite(RED, HIGH);
if(digitalRead(P1, HIGH)) s1++;
else s2++;
displayScore();
}
delay(10);
}
*/
void loop() {
if(p1d>0) p1d--;
if(p2d>0) p2d--;
if(del>0) {
del--;
turnOff();
if(digitalRead(P1) == HIGH && (!ledOn) && p1d == 0) {
s1--;
displayScore();
player1Delay();
losingSound();
}
if(digitalRead(P2) == HIGH && (!ledOn) && p2d == 0) {
s2--;
displayScore();
player2Delay();
losingSound();
}
}
else {
turnOn();
if(digitalRead(P1) == HIGH && (ledOn) && p1d == 0) {
s1++;
turnOff();
displayScore();
player1Delay();
winningSound();
}
if(digitalRead(P2) == HIGH && (ledOn) && p2d == 0) {
s2++;
turnOff();
displayScore();
player2Delay();
winningSound();
}
if(digitalRead(P1) == HIGH && (!ledOn) && p1d == 0) {
s1--;
displayScore();
player1Delay();
losingSound();
}
if(digitalRead(P2) == HIGH && (!ledOn) && p2d == 0) {
s2--;
displayScore();
player2Delay();
losingSound();
}
if (!ledOn) {
initialize();
}
}
delay (10);
}
void displayScore() {
Serial.println("----------------");
Serial.print("Player 1: ");
Serial.println(s1);
Serial.print("Player 2: ");
Serial.println(s2);
}
void turnOff() {
digitalWrite(GREEN, LOW);
ledOn = false;
digitalWrite(RED, HIGH);
}
void turnOn() {
digitalWrite(RED, LOW);
ledOn = true;
digitalWrite(GREEN, HIGH);
}
void initialize() {
del = (random(300, 500));
}
void playSong() {
tone(BUZ, 329.6276, 100);
delay (200);
tone(BUZ, 329.6276, 100);
delay (300);
tone(BUZ, 329.6276, 100);
delay (150);
tone(BUZ, 261.6256, 80);
delay (200);
tone(BUZ, 329.6276, 100);
delay (250);
tone(BUZ, 391.9954, 100);
delay (400);
tone(BUZ, 198, 200);
delay (50);
}
void player1Delay() {
p1d = 40;
}
void player2Delay() {
p2d = 40;
}
void winningSound() {
tone(BUZ, 690, 100);
delay(50);
tone(BUZ, 1000, 100);
delay(50);
Serial.println("----------------");
Serial.println("winningSound");
Serial.println("----------------");
}
void losingSound() {
tone(BUZ, 400, 100);
delay(50);
tone(BUZ, 350, 100);
delay(50);
Serial.println("----------------");
Serial.println("losingSound");
Serial.println("----------------");
}