Simple Simon says mbed game which makes random queue, shows it with onboard LEDs and takes user input with push buttons.

Dependencies:   PinDetect mbed beep

Simon.cpp

Committer:
tsoic
Date:
2015-02-10
Revision:
5:94c215df2b7c
Parent:
4:32b02dd83c0d

File content as of revision 5:94c215df2b7c:

#include "mbed.h"
#include "PinDetect.h"
#include "Simon.h"
#include "Piezo.h"
#include <vector>
#include <cstdlib>

DigitalOut Simon::led[4] = {LED1, LED2, LED3, LED4};
PinDetect Simon::button[5] = {p12, p13, p14, p15, p16};
    
Simon::Simon() : queue(turn) {   
    piezo.NoteC4();
    wait(0.4);
    piezo.NoteB4();
    LEDSBlink();
    run = false;
    button[0].attach_asserted(this, &Simon::keyPressedSt);
    button[1].attach_asserted(this, &Simon::keyPressedNd); 
    button[2].attach_asserted(this, &Simon::keyPressedRd);
    button[3].attach_asserted(this, &Simon::keyPressedTh);
    button[4].attach_asserted(this, &Simon::ReStart);
    for(i = 0; i < 5; i++) {
        button[i].mode( PullDown );
        button[i].setSampleFrequency();
    }
}

void Simon::gameStart(int first_turn) {
    this -> first_turn = first_turn;
    turn = first_turn;
    while(1) {
        while(run == true) {
            newQueue();
            showQueue();
            run = userTurn(); 
        }
    }
}   

int Simon::testQueue() {
    if (queue[i] == test_val) {
        piezo.NoteFor(queue[i]);
        led[queue[i]] = 1;
        wait(0.2);
        led[queue[i]] = 0;
        return 1;
    }
    else return 0;   
} 

void Simon::LEDSBlink() {
    for(i = 0; i < 4; i++)  led[i] = 1;
    wait(0.4);
    for(i = 0; i < 4; i++)  led[i] = 0;
}

void Simon::newQueue() {  
    for(i = 0; i < turn; i++) queue[i] = rand() % 4;                  
}

void Simon::showQueue() {
     wait(0.2);
     for(i = 0; i < turn; i++) {
        piezo.NoteFor(queue[i]);
        led[queue[i]] = 1;
        wait(0.5);
        led[queue[i]] = 0;
        wait(0.1);   
    }   
}

bool Simon::userTurn() {
    i = 0;
    button_press = false;
    while(i < turn){
        if (button_press == 1) {
            if (testQueue() == 0) {
                i = turn;
                button_press = 0;
                LEDSBlink();
                piezo.NoteB4();
                wait(0.3);
                piezo.NoteC4();
                return false;
            }  
            else if (testQueue() == 1) {
                i++;
                button_press = 0;
            }
        }
    }
    this -> turn++;
    wait(0.5);
    return true;  
} 

void Simon::keyPressedSt() {
    button_press = 1;
    test_val = 0;
}

void Simon::keyPressedNd() {    
    button_press = 1;
    test_val = 1;
}

void Simon::keyPressedRd() {
    button_press = 1;
    test_val = 2;    
}

void Simon::keyPressedTh() {
    button_press = 1;
    test_val = 3;  
}

void Simon:: ReStart() {
    run = true;
    turn = first_turn;        
}