Guess a number. Using mbed serial port and a terminal on the PC, we can play this 2 player game. First player sets the secret number between 0 ..9, second player has 3 tries to guess it.
main.cpp
- Committer:
- lmsousa
- Date:
- 2015-05-07
- Revision:
- 1:60ded2252111
- Parent:
- 0:29ea6e039941
- Child:
- 2:7c413a5377b8
File content as of revision 1:60ded2252111:
// Code by Luis Sousa //#include <stdio.h> //#include <stdlib.h> //#include <time.h> //#include <conio.h> #include "mbed.h" Serial pc(USBTX, USBRX); DigitalOut redLED(LED_RED); // Define digital outputs for each LED color DigitalOut greenLED(LED_GREEN); DigitalOut blueLED(LED_BLUE); int main(void) { pc.baud(9600); int ntent = 3; //max tries int nint = 0; //guess int nsec = 0; //secret number int acertou = 0; int valid = 0; //valid number? int play = 1; char opcao='N'; //option int n=0; do { redLED = 1; // This a common anode RGB LED, with the anodes connected greenLED = 1; // to 1. Thus, to turn a color off you counterintuitively set blueLED = 1; // it to 1, so there is no voltage difference across the LED /* NEW GAME */ do { // clrscr(); pc.printf("Enter secret number ? (0-9) \n"); nsec=pc.getc() - '0'; //scanf("%d", &nsec); if((nsec>=0)&(nsec<=9)) valid=1; else { valid=0; pc.printf("Invalid number. Must be in the 0 .. 9 range \n "); } } while(! valid); ntent=3; acertou=0; // clrscr(); /* player 2 can't see previous screen */ for (n=0; n<40; n++) { pc.printf(" \n"); } do { do { pc.printf("Guess the number. You have %d tries \n",ntent); nint=pc.getc() -'0'; //scanf("%d", &nint); valid =(nint>=0)&(nint<=9); } while (! valid); ntent--; if (nint < nsec) { pc.printf("Too low. \n"); redLED = 1; greenLED = 1; blueLED = 0; } else if (nint > nsec) { pc.printf("Too high. \n"); redLED = 0; greenLED = 1; blueLED = 1; } else { /* if (nint == nsec) */ pc.printf("You guessed!! %d tries missing! \n", ntent); acertou = 1; redLED = 1; greenLED = 0; blueLED = 1; } if (ntent ==0 & !acertou) { pc.printf("No more tries!!! You lost! \n"); redLED = 0; greenLED = 1; blueLED = 1; } else if (!acertou) pc.printf("Try Again \n"); } while ((!acertou)&(ntent>0)); pc.printf("New game? (Y/N) \n"); opcao=pc.getc(); // scanf(" %c", &opcao); // opcao = getchar(); */ if((opcao =='Y')||(opcao =='y')) play=1; else { play=0; // clrscr(); pc.printf("Game Over! \n"); } } while (play); redLED = 1; greenLED = 1; blueLED = 1; return 0; }