Page 199 - ARM Based Microcontroller Projects Using MBED
P. 199

8.17  PROJECT 14—SERIAL INTERRUPT                 185
              /**************************************************************************

                                              HiLo Game
                                              =========
              This is the popular HiLo game. A random secret number is generated by the
              computer between 1 and 100 and the user attempts to guess this number. If
              the guess is higher than the secret number the message You are HIGH is
              displayed. Similarly, if the guess is lower then the message You are LOW is
              displayed. The message Success is displayed when the user finds the secret
              number. Additionally, the number of attempts is also displayed when the
              secret number is found.

              Author: Dogan Ibrahim
              Date  : August 2018
              File  : HiLo
              ***************************************************************************/
              #include "mbed.h"
              Serial MyPC(USBTX, USBRX);
              int main()
              {
                 int Flag, SecretNumber, GuessedNumber, Attempts = 0;

                 while(1)                                                 // Do forever
                 {
                      Flag = 0;
                      MyPC.printf("\n\r");                                // New line
                      MyPC.printf("\n\rStart of New Game");               // Display heading
                      MyPC.printf("\n\r===================");
                      SecretNumber = rand() % 100 + 1;                    // Between 1-100

                      while(Flag == 0)                                    // While not found
                      {
                          MyPC.printf("\n\rEnter Your Guess (1 - 100): ");
                          MyPC.scanf("%d", &GuessedNumber);
                          Attempts++;                                     // Increment attempts
                          if(GuessedNumber > SecretNumber)                // If higher
                                  MyPC.printf("\n\rYou are HIGH");
                          else if(GuessedNumber < SecretNumber)           // If lower
                                  MyPC.printf("\n\rYou are LOW");
                          else                                            // Success
                          {
                              MyPC.printf("\n\rSuccess...");
                              MyPC.printf("Attempts = %d", Attempts);     // Attempt count
                              Flag = 1;                                   // Terminate loop
                          }
                      }
                  }
              }
            FIG. 8.47  Program listing.
   194   195   196   197   198   199   200   201   202   203   204