![](/media/cache/group/TVZ_logotip.png.50x50_q85.jpg)
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
Diff: Simon.cpp
- Revision:
- 0:d53b17bb7ffa
- Child:
- 1:fb29354d9073
- Child:
- 3:75399d0ba94e
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Simon.cpp Tue Feb 03 13:01:28 2015 +0000 @@ -0,0 +1,109 @@ +#include "mbed.h" +#include "PinDetect.h" +#include "Simon.h" +#include <vector> +#include <cstdlib> + + +DigitalOut Simon::leds[4] = {LED1, LED2, LED3, LED4}; +PinDetect Simon::button[4] = {p12, p13, p14, p15}; + +Simon::Simon() : queue(turn) { + LEDSOn(); + wait(0.4); + LEDSOff(); + for(i = 0; i < 4; i++) { + button[i].mode( PullDown ); + switch (i) { + case 0: + button[i].attach_asserted(this, &Simon::keyPressedSt); + break; + case 1: + button[i].attach_asserted(this, &Simon::keyPressedNd); + break; + case 2: + button[i].attach_asserted(this, &Simon::keyPressedRd); + break; + case 3: + button[i].attach_asserted(this, &Simon::keyPressedTh); + break; + } + button[i].setSampleFrequency(); + } +} +int Simon::TestQueue(int i) { + if (queue[i] == test_val) { + leds[queue[i]] = 1; + wait(0.2); + leds[queue[i]] = 0; + return 1; + } + else return 0; +} + +void Simon::LEDSOn() { + for(i = 0; i < 4; i++) leds[i] = 1; +} + +void Simon::LEDSOff() { + for(i = 0; i < 4; i++) leds[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++) { + leds[queue[i]] = 1; + wait(0.5); + leds[queue[i]] = 0; + wait(0.1); + } +} + +bool Simon::userTurn() { + LEDSOn(); + wait(0.5); + LEDSOff(); + i = 0; + while(i < turn){ + if (button_press == 1) { + if (TestQueue(i) == 0) { + i = turn; + button_press = 0; + LEDSOn();/* Indication of Game Over */ + wait(0.4); + LEDSOff(); + return false; + } + else if (TestQueue(i) == 1) { + i++; + button_press = 0; + } + } + } + this -> turn++; + return true; +} + +void Simon::keyPressedSt(void) { + button_press = 1; + test_val = 0; +} + +void Simon::keyPressedNd(void) { + button_press = 1; + test_val = 1; +} + +void Simon::keyPressedRd(void) { + button_press = 1; + test_val = 2; +} + +void Simon::keyPressedTh(void) { + button_press = 1; + test_val = 3; +} \ No newline at end of file