Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <sstream>
- using namespace std;
- //Simple rock, paper scissors game
- //Introduction to the program
- void introduction()
- {
- cout << "****Rock, Paper, Scissors****" << endl << endl;
- }
- //Determine user's choice (rock, paper, or scissors)
- int userChoice()
- {
- int choice;
- string input = "";
- //ensures that response is an integer (1, 2, or 3)
- while (true)
- {
- cout << "(1) Rock" << endl << "(2) Paper" << endl << "(3) Scissors" << endl << endl << "Choose 1, 2, or 3: ";
- getline(cin, input);
- stringstream myStream(input);
- if ((myStream >> choice) && (choice >0) && (choice <4))
- break;
- cout << endl << "Invalid choice. Please try again." << endl << endl;
- }
- return choice;
- }
- //Determine computer's 'choice'
- int cpuChoice()
- {
- //Assigns randomChoice a random number (1, 2, or 3)
- int randomChoice = (rand() % (3 - 0 + 1)) + 0;
- return randomChoice;
- }
- //Determine who wins
- char winner(int userChoice, int cpuChoice)
- {
- // t = tie, c = computer wins, u = user wins
- if (userChoice == cpuChoice)
- return 't';
- else if ((userChoice == 1) && (cpuChoice == 2))
- return 'c';
- else if ((userChoice == 1) && (cpuChoice == 3))
- return 'u';
- else if ((userChoice == 2) && (cpuChoice == 1))
- return 'u';
- else if ((userChoice == 2) && (cpuChoice == 3))
- return 'c';
- else if ((userChoice == 3) && (cpuChoice == 1))
- return 'c';
- else if ((userChoice == 3) && (cpuChoice == 2))
- return 'u';
- }
- //Ouput who won
- void outputWinner(char w, int c)
- {
- if (w=='t')
- cout << endl << "The game is a tie. ";
- else if (w== 'u')
- cout << endl << "Congratulations, you win! ";
- else
- cout << endl << "Sorry, you lost. ";
- if (c == 1)
- cout << "The CPU chose rock. " << endl;
- else if (c==2)
- cout << "The CPU chose paper. " << endl;
- else
- cout << "The CPU chose scissors. " << endl;
- }
- //Ask if user would like to try again
- char tryAgain()
- {
- string input = "";
- char response;
- //ensures response is a char and is either y, Y, n, or N
- while (true)
- {
- cout << endl;
- cout << "Would you like to try again? (Y/N): ";
- getline(cin, input);
- stringstream myStream(input);
- if (input.length() == 1)
- {
- response = input[0];
- if ((response == 'y') || (response == 'Y') || (response == 'n') || (response == 'N'))
- break;
- }
- cout << endl << "Please enter 'Y' or 'N'" << endl;
- }
- cout << endl;
- return response;
- }
- //int main()
- int _tmain(int argc, _TCHAR* argv[])
- {
- char response = 'y';
- do
- {
- introduction();
- int choice = userChoice();
- int randomChoice = cpuChoice();
- char w = winner(choice,randomChoice);
- outputWinner(w, randomChoice);
- response = tryAgain();
- } while ((response == 'y') || (response == 'Y'));
- return 0;
Advertisement
Add Comment
Please, Sign In to add comment