Home‎ > ‎Assignments‎ > ‎

RPS - solution


#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

int main(){
    string name;char hand;
    int r;int userwins=0; int gamebotwins=0;
    char myhand;
    cout << "My name is GameBot, what is your name? ";
    cin >> name;
    //user enters first hand
    cout<< "Choose a hand to play: \n Type R for rock, P for Paper, or S for Scissors.\n ";
    cout << "When you want to stop, type E for End instead. \n Your choice: ";
    cin >> hand;
    while (hand != 'E'){
        r = rand() % 3;
        switch (r)
        {
        case 0: 
            {
                myhand = 'R'; cout << "You picked " << hand << ". I picked " << myhand << ". \n"; 
                switch (hand)
                { 
                case 'P': cout << name << ", YOU WIN !!!!"; userwins++;break;
                case 'S': cout << "I win! HAHAHAHA!!"; gamebotwins++;break;
                }
                break;
            }
        case 1: {
            myhand = 'P'; cout <<"You picked " << hand << ". I picked "<< myhand << ".\n"; 
            switch (hand)
            {
            case 'R': cout << "I win! HAHAHAHA!!"; gamebotwins++; break;
            case 'S': cout << name << ", YOU WIN !!!!"; userwins++;break;
            }
            break;
                }
        case 2: {
            myhand = 'S'; cout <<"You picked " << hand << ". I picked "<< myhand << ".\n"; 
            switch (hand){
            case 'R': cout << name << ", YOU WIN !!!!"; userwins++;break;
            case 'P': cout << "I win! HAHAHAHA!!"; gamebotwins++;break;
            }
            break;
                }
        }
        if (hand == myhand) cout << "We are tied. No winner. Try again.";
        //user enters a new hand
        cout<< "Choose a hand to play: \n Type R for rock, P for Paper, or S for Scissors.\n ";
        cout << "When you want to stop, type E for End instead. \n Your choice: ";
        cin >> hand;
    }
    cout << "\nThank you for playing, "<< name<< ". \nYou won " << userwins << " hands.";
    cout << "\nI won " << gamebotwins << " hands.";
    if (userwins == gamebotwins) cout << "\nWe tied. There is no winner.";
    else if (userwins > gamebotwins) cout << "\nYou won the game!";
    else cout << "\nI win the game! I am clearly the better player. Nyah, nyah!";
    cout<<endl<<endl;
    return 0;
}


Comments