Below is the code for a Reaction Time game for the Sandbox.
The code is heavily modified from the tutorial code for The Reaction Tester.
The object of the game is to press D12 when LED 6 is lit.Each successful hit increases game speed.
The game displays misses, hits, keeps score, and reports the score (flashing blue light) after the first miss, then resets.
Enjoy.
int led = 4;
int num = 0;
int score = 0;
int speed = 250;
void setup()
{
// Set the button and switch as INPUTs:
pinMode(12, INPUT);
// Set LEDs as outputs:
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void loop()
{
if (digitalRead(12) == HIGH) // If the button is pressed
{
if (led == 6)
{
num = 0;
while(num < 10)
{
digitalWrite(4, HIGH); // flashes the “win” signal
digitalWrite(8, HIGH);
delay(50);
digitalWrite(4, LOW);
digitalWrite(8, LOW);
delay(50);
digitalWrite(5, HIGH);
digitalWrite(7, HIGH);
delay(50);
digitalWrite(5, LOW);
digitalWrite(7, LOW);
delay(50);
num++;
}
speed = speed -50; // increases speed for next level
score = score + 1; // records score
}
else
{
analogWrite(9, 255); //flashes the “wrong” signal
delay(1200);
analogWrite(9, 0);
delay(1200);
speed = 250; // resets the speed
while (score > 0)
{
analogWrite(11, 255); // displays the score
delay(300);
analogWrite(11, 0);
delay(300);
score = score - 1;
}
}
digitalWrite(led, HIGH); // Turn the active LED on, nothing else.
}
else // Otherwise, if the button is released
{
digitalWrite(led, LOW); // Turn the active LED off.
led = led + 1; // Increment the led variable by 1
if (led > 8) // If led is out of our range (4-8)
{
led = 4; // Set it back to the bottom (LED 4).
}
digitalWrite(led, HIGH); // Turn on the new LED
delay(speed); // Delay for speed ms.
}
}