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-05
- Revision:
- 0:29ea6e039941
- Child:
- 1:60ded2252111
File content as of revision 0:29ea6e039941:
//#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; //tentativas int nint = 0; //numero introduzido int nsec = 0; //numero secreto int acertou = 0; int valid = 0; //Numero e valido (0 ..9) int play = 1; char opcao='N'; 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("Introduza o Numero Secreto (0-9) \n"); nsec=pc.getc() - '0'; //scanf("%d", &nsec); if((nsec>=0)&(nsec<=9)) valid=1; else { valid=0; pc.printf("Numero invalido. O numero deve estar entre 0 e 9 \n"); } } while(! valid); ntent=3; acertou=0; // clrscr(); /* o jogador 2 nao pode ver os ecrans anteriores */ for (n=0; n<40; n++) { pc.printf(" \n"); } /* Tentativa N */ do { do { pc.printf("Adivinhe o numero. Tem %d tentativas \n",ntent); nint=pc.getc() -'0'; //scanf("%d", &nint); valid =(nint>=0)&(nint<=9); } while (! valid); ntent--; if (nint < nsec) { pc.printf("Valor baixo. \n"); redLED = 1; greenLED = 1; blueLED = 0; } else if (nint > nsec) { pc.printf("Valor alto. \n"); redLED = 0; greenLED = 1; blueLED = 1; } else { /* if (nint == nsec) */ pc.printf("Parabens acertou!! Faltavam %d tentativas! \n", ntent); acertou = 1; redLED = 1; greenLED = 0; blueLED = 1; } if (ntent ==0 & !acertou) { pc.printf("Perdeu!!! Esgotou as tentativas \n"); redLED = 0; greenLED = 1; blueLED = 1; } else if (!acertou) pc.printf("Tente novamente \n"); } while ((!acertou)&(ntent>0)); pc.printf("Novo Jogo? (S/N) \n"); opcao=pc.getc(); // scanf(" %c", &opcao); // opcao = getchar(); */ if((opcao =='S')||(opcao =='s')) play=1; else { play=0; // clrscr(); pc.printf("Jogo Terminado! \n"); } } while (play); redLED = 1; greenLED = 1; blueLED = 1; return 0; }