In this series of showing the power of a turing machine this time i created a musical memory game. It is also called simon game.
Here is the Turing machine
#include "pitches.h"
//this program needs pitches.h file. you can google for pitches.h
int lednotes[] = {
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4
};
void setup() {
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
randomSeed(analogRead(0));
}
int leds[] = {8, 9, 10, 11};
void turnOnLed(int p){
//play a sound while turning led on
int noteDuration = 1000 / 4;
tone(7, lednotes[p], noteDuration);
for(int i=0; i<4; i++){
if(p == i){
digitalWrite(leds[p], HIGH);
}
else{
digitalWrite(leds[i], LOW);
}
}
}
void turnOffLeds(){
for(int i=0; i<4; i++){
digitalWrite(leds[i], LOW);
}
}
int inputturn = false;
//store the led sequence
int sequence[100];
//store the player inputs
int inputs[100];
//length of the sequence. starts with 1 which means it lights one led.
int count = 1;
int inputcount = 0;
void playIncorrectSound(){
for(int i=0; i<2; i++){
int noteDuration = 1000 / 8;
tone(7, NOTE_G3, noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(7);
}
}
void checkAnswer(){
for(int i=0; i<count; i++){
if(inputs[i] != sequence[i]){
inputcount = 0;
count = 1;
inputturn = false;
playIncorrectSound();
return;
}
}
inputturn = false;
count += 1;
inputcount = 0;
}
void loop() {
//After showing the led sequence inputturn = true. This means its player turn to input the pattern using the buttons.
if(inputturn){
if(digitalRead(2) == LOW){
Serial.println("first pressed");
digitalWrite(8, HIGH);
inputs[inputcount] = 0;
inputcount += 1;
delay(200);
}
else{
digitalWrite(8, LOW);
}
if(digitalRead(3) == LOW){
Serial.println("second pressed");
digitalWrite(9, HIGH);
inputs[inputcount] = 1;
inputcount += 1;
delay(200);
}
else{
digitalWrite(9, LOW);
}
if(digitalRead(4) == LOW){
Serial.println("third pressed");
digitalWrite(10, HIGH);
inputs[inputcount] = 2;
inputcount += 1;
delay(200);
}
else{
digitalWrite(10, LOW);
}
if(digitalRead(5) == LOW){
Serial.println("fourth pressed");
digitalWrite(11, HIGH);
inputs[inputcount] = 3;
inputcount += 1;
delay(200);
}
else{
digitalWrite(11, LOW);
}
if(inputcount == count){
checkAnswer();
}
}
else{
//time to show the led sequence
turnOffLeds();
delay(100);
for(int i=0; i<count; i++){
int randNumber = random(0, 4);
sequence[i] = randNumber;
turnOnLed(randNumber);
delay(500);
turnOffLeds();
delay(100);
}
inputturn = true;
}
}
View the game play
No comments:
Post a Comment