/* * rps.c * * Computer Science 50, Fall 2011 * section6 * * Practice with enumerated types && have fun! */ #include #include #include // define an enumerated type with typedef typedef enum { WIN, LOSE, DRAW } outcome; // define an enumerated type without typedef enum move {rock, paper, scissors}; // function prototype outcome play_round(char c); int main(void) { // save player's move and the score char choice; int score = 0, opp_score = 0; // get player's move and determine the round's result do { printf("\nRock, paper, scissors, shoot...\n"); printf("(play with 'r', 'p', 's' or type 'q' to quit)\n"); printf("Score: %02d\nComputer's Score: %02d\n", score, opp_score); choice = GetChar(); if(choice != 'q' && (choice == 'r' || choice == 'p' || choice == 's')) { outcome result = play_round(choice); if(result == WIN) { printf("You win!\n"); score++; } else if(result == LOSE) { printf("You lose!\n"); opp_score++; } else printf("You draw!\n"); } } while(choice != 'q'); // success return 0; } // plays a round outcome play_round(char c) { // initalize random seed srand(time(NULL)); // generate random number int x = rand() % 3; // figure out the opponent's move enum move opp_move; if(x == 0) { opp_move = rock; printf("The computer picked rock.\n"); } else if(x == 1) { opp_move = paper; printf("The computer picked paper.\n"); } else { opp_move = scissors; printf("The computer picked scissors.\n"); } // figure out what happened in the round switch(c) { case 'r': if(opp_move == rock) return DRAW; else if(opp_move == paper) return LOSE; else return WIN; case 'p': if(opp_move == rock) return WIN; else if(opp_move == paper) return DRAW; else return LOSE; default: // should only ever be 's' if(opp_move == rock) return LOSE; else if(opp_move == paper) return WIN; else return DRAW; } }