Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <time.h>
- #include <stdlib.h>
- void printDoors(int prin, int g);
- int getPrincessMove(int ppos);
- int main(void)
- {
- srand(time(0));
- int ppos;
- int guess;
- int numGuesses = 1;
- int pmove;
- int direction;
- //initial position for princess is 1-17
- ppos = (rand() % 17) + 1;
- guess = 2;
- direction = 1;
- while (guess != ppos)
- {
- //print board
- printDoors(ppos, guess);
- //update location
- ppos = ppos + getPrincessMove(ppos);
- //update day/guess
- //direction starts out as positive 1
- //stay on door 16 the first time
- //reverse direction after 2nd time on door 16
- if (numGuesses == 15)
- {
- direction = 0;
- }
- else if (numGuesses == 16)
- {
- direction = -1;
- }
- guess = guess + direction;
- //update total
- numGuesses++;
- }
- //print total guesses / status
- printf("You won in %i moves\n", numGuesses);
- }
- void printDoors(int prin, int g)
- {
- for (int i=1; i<=17; i++)
- {
- if (i==prin)
- {
- printf("P");
- }
- else if (i==g)
- {
- printf("X");
- }
- else
- {
- printf("_");
- }
- }
- printf("\n");
- }
- int getPrincessMove(int ppos)
- {
- //move princess
- int pmove = rand() % 2; //0 or 1
- //force move to -1 or +1
- if (pmove == 0)
- {
- pmove = -1;
- }
- //override random move if on edge
- if (ppos == 17)
- {
- pmove = -1;
- }
- else if (ppos == 1)
- {
- pmove = 1;
- }
- return pmove;
- }
Add Comment
Please, Sign In to add comment