ssoni

prin1.c

Mar 2nd, 2022 (edited)
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <time.h>
  4. #include <stdlib.h>
  5.  
  6. void printDoors(int prin, int g);
  7. int getPrincessMove(int ppos);
  8.  
  9. int main(void)
  10. {
  11.     srand(time(0));
  12.  
  13.     int ppos;
  14.     int guess;
  15.     int numGuesses = 1;
  16.     int pmove;
  17.     int direction;
  18.  
  19.     //initial position for princess is 1-17
  20.     ppos = (rand() % 17) + 1;
  21.  
  22.     guess = 2;
  23.     direction = 1;
  24.  
  25.     while (guess != ppos)
  26.     {
  27.         //print board
  28.         printDoors(ppos, guess);
  29.  
  30.         //update location
  31.         ppos = ppos + getPrincessMove(ppos);
  32.  
  33.         //update day/guess
  34.         //direction starts out as positive 1
  35.         //stay on door 16 the first time
  36.         //reverse direction after 2nd time on door 16
  37.         if (numGuesses == 15)
  38.         {
  39.             direction = 0;
  40.         }
  41.         else if (numGuesses == 16)
  42.         {
  43.             direction = -1;
  44.         }
  45.         guess = guess + direction;
  46.  
  47.         //update total
  48.         numGuesses++;
  49.     }
  50.  
  51.     //print total guesses / status
  52.     printf("You won in %i moves\n", numGuesses);
  53. }
  54.  
  55. void printDoors(int prin, int g)
  56. {
  57.     for (int i=1; i<=17; i++)
  58.     {
  59.  
  60.         if (i==prin)
  61.         {
  62.             printf("P");
  63.         }
  64.         else if (i==g)
  65.         {
  66.             printf("X");
  67.         }
  68.         else
  69.         {
  70.             printf("_");
  71.         }
  72.     }
  73.     printf("\n");
  74. }
  75.  
  76.  
  77.  
  78. int getPrincessMove(int ppos)
  79. {
  80.     //move princess
  81.         int pmove = rand() % 2;     //0 or 1
  82.  
  83.         //force move to -1 or +1
  84.         if (pmove == 0)
  85.         {
  86.             pmove = -1;
  87.         }
  88.  
  89.         //override random move if on edge
  90.         if (ppos == 17)
  91.         {
  92.             pmove = -1;
  93.         }
  94.         else if (ppos == 1)
  95.         {
  96.             pmove = 1;
  97.         }
  98.         return pmove;
  99.  
  100. }
Add Comment
Please, Sign In to add comment